openMSX
serialize.cc
Go to the documentation of this file.
1 #include "serialize.hh"
2 #include "Base64.hh"
3 #include "HexDump.hh"
4 #include "XMLLoader.hh"
5 #include "XMLElement.hh"
6 #include "ConfigException.hh"
7 #include "XMLException.hh"
8 #include "DeltaBlock.hh"
9 #include "MemBuffer.hh"
10 #include "StringOp.hh"
11 #include "FileOperations.hh"
12 #include "Version.hh"
13 #include "Date.hh"
14 #include "cstdiop.hh" // for dup()
15 #include <cstring>
16 #include <limits>
17 
18 using std::string;
19 
20 namespace openmsx {
21 
22 template<typename Derived>
23 void ArchiveBase<Derived>::attribute(const char* name, const char* value)
24 {
25  string valueStr(value);
26  self().attribute(name, valueStr);
27 }
28 template class ArchiveBase<MemOutputArchive>;
29 template class ArchiveBase<XmlOutputArchive>;
30 
32 
34  : lastId(0)
35 {
36 }
37 
38 unsigned OutputArchiveBase2::generateID1(const void* p)
39 {
40  #ifdef linux
41  assert("Can't serialize ID of object located on the stack" &&
42  !addressOnStack(p));
43  #endif
44  ++lastId;
45  assert(polyIdMap.find(p) == end(polyIdMap));
46  polyIdMap[p] = lastId;
47  return lastId;
48 }
49 unsigned OutputArchiveBase2::generateID2(
50  const void* p, const std::type_info& typeInfo)
51 {
52  #ifdef linux
53  assert("Can't serialize ID of object located on the stack" &&
54  !addressOnStack(p));
55  #endif
56  ++lastId;
57  auto key = std::make_pair(p, std::type_index(typeInfo));
58  assert(idMap.find(key) == end(idMap));
59  idMap[key] = lastId;
60  return lastId;
61 }
62 
63 unsigned OutputArchiveBase2::getID1(const void* p)
64 {
65  auto it = polyIdMap.find(p);
66  return it != end(polyIdMap) ? it->second : 0;
67 }
68 unsigned OutputArchiveBase2::getID2(
69  const void* p, const std::type_info& typeInfo)
70 {
71  auto it = idMap.find({p, std::type_index(typeInfo)});
72  return it != end(idMap) ? it->second : 0;
73 }
74 
75 
76 template<typename Derived>
78  const char* tag, const void* data_, size_t len, bool /*diff*/)
79 {
80  auto* data = static_cast<const uint8_t*>(data_);
81 
82  string encoding;
83  string tmp;
84  if (false) {
85  // useful for debugging
86  encoding = "hex";
87  tmp = HexDump::encode(data, len);
88  } else if (false) {
89  encoding = "base64";
90  tmp = Base64::encode(data, len);
91  } else {
92  encoding = "gz-base64";
93  // TODO check for overflow?
94  auto dstLen = uLongf(len + len / 1000 + 12 + 1); // worst-case
95  MemBuffer<byte> buf(dstLen);
96  if (compress2(buf.data(), &dstLen,
97  reinterpret_cast<const Bytef*>(data),
98  uLong(len), 9)
99  != Z_OK) {
100  throw MSXException("Error while compressing blob.");
101  }
102  tmp = Base64::encode(buf.data(), dstLen);
103  }
104  this->self().beginTag(tag);
105  this->self().attribute("encoding", encoding);
106  Saver<string> saver;
107  saver(this->self(), tmp, false);
108  this->self().endTag(tag);
109 }
110 
113 
115 
117 {
118  auto it = idMap.find(id);
119  return it != end(idMap) ? it->second : nullptr;
120 }
121 
122 void InputArchiveBase2::addPointer(unsigned id, const void* p)
123 {
124  assert(idMap.find(id) == end(idMap));
125  idMap[id] = const_cast<void*>(p);
126 }
127 
128 unsigned InputArchiveBase2::getId(const void* ptr) const
129 {
130  for (const auto& p : idMap) {
131  if (p.second == ptr) return p.first;
132  }
133  return 0;
134 }
135 
136 template<typename Derived>
138  const char* tag, void* data, size_t len, bool /*diff*/)
139 {
140  this->self().beginTag(tag);
141  string encoding;
142  this->self().attribute("encoding", encoding);
143 
144  string_ref tmp = this->self().loadStr();
145  this->self().endTag(tag);
146 
147  if (encoding == "gz-base64") {
148  auto p = Base64::decode(tmp);
149  auto dstLen = uLongf(len); // TODO check for overflow?
150  if ((uncompress(reinterpret_cast<Bytef*>(data), &dstLen,
151  reinterpret_cast<const Bytef*>(p.first.data()), uLong(p.second))
152  != Z_OK) ||
153  (dstLen != len)) {
154  throw MSXException("Error while decompressing blob.");
155  }
156  } else if ((encoding == "hex") || (encoding == "base64")) {
157  bool ok = (encoding == "hex")
158  ? HexDump::decode_inplace(tmp, static_cast<uint8_t*>(data), len)
159  : Base64 ::decode_inplace(tmp, static_cast<uint8_t*>(data), len);
160  if (!ok) {
162  << "Length of decoded blob different from "
163  "expected value (" << len << ')');
164  }
165  } else {
166  throw XMLException("Unsupported encoding \"" + encoding + "\" for blob");
167  }
168 }
169 
170 template class InputArchiveBase<MemInputArchive>;
171 template class InputArchiveBase<XmlInputArchive>;
172 
174 
175 void MemOutputArchive::save(const std::string& s)
176 {
177  auto size = s.size();
178  byte* buf = buffer.allocate(sizeof(size) + size);
179  memcpy(buf, &size, sizeof(size));
180  memcpy(buf + sizeof(size), s.data(), size);
181 }
182 
184 {
185  return buffer.release(size);
186 }
187 
189 
190 void MemInputArchive::load(std::string& s)
191 {
192  size_t length;
193  load(length);
194  s.resize(length);
195  if (length) {
196  get(&s[0], length);
197  }
198 }
199 
201 {
202  size_t length;
203  load(length);
204  const byte* p = buffer.getCurrentPos();
205  buffer.skip(length);
206  return string_ref(reinterpret_cast<const char*>(p), length);
207 }
208 
210 
211 // Too small inputs don't compress very well (often the compressed size is even
212 // bigger than the input). It also takes a relatively long time (because often
213 // compression has a relatively large setup time). I choose this value
214 // semi-arbitrary. I only made it >= 52 so that the (incompressible) RP5C01
215 // registers won't be compressed.
216 static const size_t SMALL_SIZE = 64;
217 void MemOutputArchive::serialize_blob(const char*, const void* data, size_t len,
218  bool diff)
219 {
220  // Delta-compress in-memory blobs, see DeltaBlock.hh for more details.
221  if (len > SMALL_SIZE) {
222  unsigned deltaBlockIdx = deltaBlocks.size();
223  save(deltaBlockIdx); // see comment below in MemInputArchive
224  deltaBlocks.push_back(diff
225  ? lastDeltaBlocks.createNew(
226  data, static_cast<const uint8_t*>(data), len)
227  : lastDeltaBlocks.createNullDiff(
228  data, static_cast<const uint8_t*>(data), len));
229  } else {
230  byte* buf = buffer.allocate(len);
231  memcpy(buf, data, len);
232  }
233 
234 }
235 
236 void MemInputArchive::serialize_blob(const char*, void* data, size_t len, bool /*diff*/)
237 {
238  if (len > SMALL_SIZE) {
239  // Usually blobs are saved in the same order as they are loaded
240  // (via the serialize_blob() methods in respectively
241  // MemOutputArchive and MemInputArchive). In that case keeping
242  // track of the deltaBlockIdx in the savestate itself is
243  // redundant (it will simply be an increasing value). However
244  // in rare cases, via the {begin,end,skip)Section() methods, it
245  // is possible that certain blobs are stored in the savestate,
246  // but skipped while loading. That's why we do need the index.
247  unsigned deltaBlockIdx; load(deltaBlockIdx);
248  deltaBlocks[deltaBlockIdx]->apply(static_cast<uint8_t*>(data), len);
249  } else {
250  memcpy(data, buffer.getCurrentPos(), len);
251  buffer.skip(len);
252  }
253 }
254 
256 
257 XmlOutputArchive::XmlOutputArchive(const string& filename)
258  : root("serial")
259 {
260  root.addAttribute("openmsx_version", Version::full());
261  root.addAttribute("date_time", Date::toString(time(nullptr)));
262  root.addAttribute("platform", TARGET_PLATFORM);
263  {
264  auto f = FileOperations::openFile(filename, "wb");
265  if (!f) goto error;
266  int duped_fd = dup(fileno(f.get()));
267  if (duped_fd == -1) goto error;
268  file = gzdopen(duped_fd, "wb9");
269  if (!file) {
270  close(duped_fd);
271  goto error;
272  }
273  current.push_back(&root);
274  return; // success
275  // on scope-exit 'File* f' is closed, and 'gzFile file'
276  // uses the dup()'ed file descriptor.
277  }
278 
279 error:
280  throw XMLException("Could not open compressed file \"" + filename + "\"");
281 }
282 
284 {
285  assert(current.back() == &root);
286  const char* header =
287  "<?xml version=\"1.0\" ?>\n"
288  "<!DOCTYPE openmsx-serialize SYSTEM 'openmsx-serialize.dtd'>\n";
289  gzwrite(file, const_cast<char*>(header), unsigned(strlen(header)));
290  string dump = root.dump();
291  gzwrite(file, const_cast<char*>(dump.data()), unsigned(dump.size()));
292  gzclose(file);
293 }
294 
296 {
297  save(string(1, c));
298 }
299 void XmlOutputArchive::save(const string& str)
300 {
301  assert(!current.empty());
302  assert(current.back()->getData().empty());
303  current.back()->setData(str);
304 }
306 {
307  assert(!current.empty());
308  assert(current.back()->getData().empty());
309  current.back()->setData(b ? "true" : "false");
310 }
311 void XmlOutputArchive::save(unsigned char b)
312 {
313  save(unsigned(b));
314 }
315 void XmlOutputArchive::save(signed char c)
316 {
317  save(int(c));
318 }
320 {
321  save(int(c));
322 }
324 {
325  saveImpl(i);
326 }
327 void XmlOutputArchive::save(unsigned u)
328 {
329  saveImpl(u);
330 }
331 void XmlOutputArchive::save(unsigned long long ull)
332 {
333  saveImpl(ull);
334 }
335 
336 void XmlOutputArchive::attribute(const char* name, const string& str)
337 {
338  assert(!current.empty());
339  assert(!current.back()->hasAttribute(name));
340  current.back()->addAttribute(name, str);
341 }
342 void XmlOutputArchive::attribute(const char* name, int i)
343 {
344  attributeImpl(name, i);
345 }
346 void XmlOutputArchive::attribute(const char* name, unsigned u)
347 {
348  attributeImpl(name, u);
349 }
350 
351 void XmlOutputArchive::beginTag(const char* tag)
352 {
353  assert(!current.empty());
354  auto& elem = current.back()->addChild(tag);
355  current.push_back(&elem);
356 }
357 void XmlOutputArchive::endTag(const char* tag)
358 {
359  assert(!current.empty());
360  assert(current.back()->getName() == tag); (void)tag;
361  current.pop_back();
362 }
363 
365 
366 XmlInputArchive::XmlInputArchive(const string& filename)
367  : rootElem(XMLLoader::load(filename, "openmsx-serialize.dtd"))
368 {
369  elems.emplace_back(&rootElem, 0);
370 }
371 
373 {
374  if (!elems.back().first->getChildren().empty()) {
375  throw XMLException("No child tags expected for primitive type");
376  }
377  return elems.back().first->getData();
378 }
379 void XmlInputArchive::load(string& t)
380 {
381  t = loadStr().str();
382 }
384 {
385  std::string str;
386  load(str);
387  std::istringstream is(str);
388  is >> c;
389 }
391 {
392  string_ref s = loadStr();
393  if ((s == "true") || (s == "1")) {
394  b = true;
395  } else if ((s == "false") || (s == "0")) {
396  b = false;
397  } else {
398  throw XMLException("Bad value found for boolean: " + s);
399  }
400 }
401 
402 // This function parses a number from a string. It's similar to the generic
403 // templatized XmlInputArchive::load() method, but _much_ faster. It does
404 // have some limitations though:
405 // - it can't handle leading whitespace
406 // - it can't handle extra characters at the end of the string
407 // - it can only handle one base (only decimal, not octal or hexadecimal)
408 // - it doesn't understand a leading '+' sign
409 // - it doesn't detect overflow or underflow (The generic implementation sets
410 // a 'bad' flag on the stream and clips the result to the min/max allowed
411 // value. Though this 'bad' flag was ignored by the openMSX code).
412 // This routine is only used to parse strings we've written ourselves (and the
413 // savestate/replay XML files are not meant to be manually edited). So the
414 // above limitations don't really matter. And we can use the speed gain.
415 template<bool IS_SIGNED> struct ConditionalNegate;
416 template<> struct ConditionalNegate<true> {
417  template<typename T> void operator()(bool negate, T& t) {
418  if (negate) t = -t; // ok to negate a signed type
419  }
420 };
421 template<> struct ConditionalNegate<false> {
422  template<typename T> void operator()(bool negate, T& /*t*/) {
423  assert(!negate); (void)negate; // can't negate unsigned type
424  }
425 };
426 template<typename T> static inline void fastAtoi(string_ref str, T& t)
427 {
428  t = 0;
429  bool neg = false;
430  size_t i = 0;
431  size_t l = str.size();
432 
433  static const bool IS_SIGNED = std::numeric_limits<T>::is_signed;
434  if (IS_SIGNED) {
435  if (l == 0) return;
436  if (str[0] == '-') {
437  neg = true;
438  i = 1;
439  }
440  }
441  for (; i < l; ++i) {
442  unsigned d = str[i] - '0';
443  if (unlikely(d > 9)) {
444  throw XMLException("Invalid integer: " + str);
445  }
446  t = 10 * t + d;
447  }
448  // The following stuff does the equivalent of:
449  // if (neg) t = -t;
450  // Though this expression triggers a warning on VC++ when T is an
451  // unsigned type. This complex template stuff avoids the warning.
452  ConditionalNegate<IS_SIGNED> negateFunctor;
453  negateFunctor(neg, t);
454 }
456 {
457  string_ref str = loadStr();
458  fastAtoi(str, i);
459 }
460 void XmlInputArchive::load(unsigned& u)
461 {
462  string_ref str = loadStr();
463  fastAtoi(str, u);
464 }
465 void XmlInputArchive::load(unsigned long long& ull)
466 {
467  string_ref str = loadStr();
468  fastAtoi(str, ull);
469 }
470 void XmlInputArchive::load(unsigned char& b)
471 {
472  unsigned i;
473  load(i);
474  b = i;
475 }
476 void XmlInputArchive::load(signed char& c)
477 {
478  int i;
479  load(i);
480  c = i;
481 }
483 {
484  int i;
485  load(i);
486  c = i;
487 }
488 
489 void XmlInputArchive::beginTag(const char* tag)
490 {
491  auto* child = elems.back().first->findNextChild(
492  tag, elems.back().second);
493  if (!child) {
494  string path;
495  for (auto& e : elems) {
496  path += e.first->getName() + '/';
497  }
499  "No child tag \"" << tag <<
500  "\" found at location \"" << path << '\"');
501  }
502  elems.emplace_back(child, 0);
503 }
504 void XmlInputArchive::endTag(const char* tag)
505 {
506  const auto& elem = *elems.back().first;
507  if (elem.getName() != tag) {
508  throw XMLException("End tag \"" + elem.getName() +
509  "\" not equal to begin tag \"" + tag + "\"");
510  }
511  auto& elem2 = const_cast<XMLElement&>(elem);
512  elem2.clearName(); // mark this elem for later beginTag() calls
513  elems.pop_back();
514 }
515 
516 void XmlInputArchive::attribute(const char* name, string& t)
517 {
518  try {
519  t = elems.back().first->getAttribute(name);
520  } catch (ConfigException& ex) {
521  throw XMLException(ex.getMessage());
522  }
523 }
524 void XmlInputArchive::attribute(const char* name, int& i)
525 {
526  attributeImpl(name, i);
527 }
528 void XmlInputArchive::attribute(const char* name, unsigned& u)
529 {
530  attributeImpl(name, u);
531 }
532 bool XmlInputArchive::hasAttribute(const char* name)
533 {
534  return elems.back().first->hasAttribute(name);
535 }
536 bool XmlInputArchive::findAttribute(const char* name, unsigned& value)
537 {
538  return elems.back().first->findAttributeInt(name, value);
539 }
541 {
542  return int(elems.back().first->getChildren().size());
543 }
544 
545 } // namespace openmsx
void attribute(const char *name, T &t)
Definition: serialize.hh:823
T length(const vecN< N, T > &x)
Definition: gl_vec.hh:322
bool findAttribute(const char *name, unsigned &value)
Definition: serialize.cc:536
string_ref::const_iterator end(const string_ref &x)
Definition: string_ref.hh:167
void serialize_blob(const char *, const void *data, size_t len, bool diff=true)
Definition: serialize.cc:217
void operator()(bool negate, T &t)
Definition: serialize.cc:417
std::string str() const
Definition: string_ref.cc:12
#define unlikely(x)
Definition: likely.hh:15
void loadChar(char &c)
Definition: serialize.cc:383
XmlInputArchive(const std::string &filename)
Definition: serialize.cc:366
void * getPointer(unsigned id)
Definition: serialize.cc:116
void serialize_blob(const char *tag, void *data, size_t len, bool diff=true)
Definition: serialize.cc:137
void save(const T &t)
Definition: serialize.hh:616
unsigned getId(const void *p) const
Definition: serialize.cc:128
bool decode_inplace(string_ref input, uint8_t *output, size_t outSize)
Definition: HexDump.cc:74
uint8_t byte
8 bit unsigned integer
Definition: openmsx.hh:26
This class implements a subset of the proposal for std::string_ref (proposed for the next c++ standar...
Definition: string_ref.hh:18
void endTag(const char *tag)
Definition: serialize.cc:504
std::string dump() const
Definition: XMLElement.cc:281
void addPointer(unsigned id, const void *p)
Definition: serialize.cc:122
bool decode_inplace(string_ref input, uint8_t *output, size_t outSize)
Definition: Base64.cc:125
MemBuffer< byte > releaseBuffer(size_t &size)
Definition: serialize.cc:183
size_type size() const
Definition: string_ref.hh:55
XMLElement load(string_ref filename, string_ref systemID)
Definition: XMLLoader.cc:31
bool hasAttribute(const char *name)
Definition: serialize.cc:532
void save(SDL_Surface *surface, const std::string &filename)
Definition: PNG.cc:369
void attribute(const char *name, const T &t)
Definition: serialize.hh:760
void endTag(const char *tag)
Definition: serialize.cc:357
void attributeImpl(const char *name, const T &t)
Definition: serialize.hh:756
void attribute(const char *name, T &t)
Load/store an attribute from/in the archive.
Definition: serialize.hh:212
void save(const T &t)
Definition: serialize.hh:731
const std::string & getMessage() const
Definition: MSXException.hh:14
void uncompress(const char *input, size_t inLen, char *output, size_t outLen)
Definition: snappy.cc:166
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
std::string toString(time_t time)
Definition: Date.cc:152
void serialize_blob(const char *, void *data, size_t len, bool diff=true)
Definition: serialize.cc:236
void operator()(bool negate, T &)
Definition: serialize.cc:422
void serialize_blob(const char *tag, const void *data, size_t len, bool diff=true)
Definition: serialize.cc:77
void beginTag(const char *tag)
Definition: serialize.cc:489
int countChildren() const
Definition: serialize.cc:540
uint8_t * data()
void addAttribute(string_ref name, string_ref value)
Definition: XMLElement.cc:57
size_t size() const
static std::string full()
Definition: Version.cc:7
FILE_t openFile(const std::string &filename, const std::string &mode)
Call fopen() in a platform-independent manner.
void saveImpl(const T &t)
Definition: serialize.hh:725
XmlOutputArchive(const std::string &filename)
Definition: serialize.cc:257
void beginTag(const char *tag)
Definition: serialize.cc:351
const T * data() const
Returns pointer to the start of the memory buffer.
Definition: MemBuffer.hh:90
void attributeImpl(const char *name, T &t)
Definition: serialize.hh:816