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 "snappy.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)
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 template<typename Derived>
130  const char* tag, void* data, size_t len)
131 {
132  this->self().beginTag(tag);
133  string encoding;
134  this->self().attribute("encoding", encoding);
135 
136  string_ref tmp = this->self().loadStr();
137  this->self().endTag(tag);
138 
139  if (encoding == "gz-base64") {
140  auto p = Base64::decode(tmp);
141  auto dstLen = uLongf(len); // TODO check for overflow?
142  if ((uncompress(reinterpret_cast<Bytef*>(data), &dstLen,
143  reinterpret_cast<const Bytef*>(p.first.data()), uLong(p.second))
144  != Z_OK) ||
145  (dstLen != len)) {
146  throw MSXException("Error while decompressing blob.");
147  }
148  } else if ((encoding == "hex") || (encoding == "base64")) {
149  bool ok = (encoding == "hex")
150  ? HexDump::decode_inplace(tmp, static_cast<uint8_t*>(data), len)
151  : Base64 ::decode_inplace(tmp, static_cast<uint8_t*>(data), len);
152  if (!ok) {
154  << "Length of decoded blob different from "
155  "expected value (" << len << ')');
156  }
157  } else {
158  throw XMLException("Unsupported encoding \"" + encoding + "\" for blob");
159  }
160 }
161 
162 template class InputArchiveBase<MemInputArchive>;
163 template class InputArchiveBase<XmlInputArchive>;
164 
166 
167 void MemOutputArchive::save(const std::string& s)
168 {
169  auto size = s.size();
170  byte* buf = buffer.allocate(sizeof(size) + size);
171  memcpy(buf, &size, sizeof(size));
172  memcpy(buf + sizeof(size), s.data(), size);
173 }
174 
176 {
177  return buffer.release(size);
178 }
179 
181 
182 void MemInputArchive::load(std::string& s)
183 {
184  size_t length;
185  load(length);
186  s.resize(length);
187  if (length) {
188  get(&s[0], length);
189  }
190 }
191 
193 {
194  size_t length;
195  load(length);
196  const byte* p = buffer.getCurrentPos();
197  buffer.skip(length);
198  return string_ref(reinterpret_cast<const char*>(p), length);
199 }
200 
202 
203 // Too small inputs don't compress very well (often the compressed size is even
204 // bigger than the input). It also takes a relatively long time (because snappy
205 // has a relatively large setup time). I choose this value semi-arbitrary. I
206 // only made it >= 52 so that the (incompressible) RP5C01 registers won't be
207 // compressed.
208 static const size_t SMALL_SIZE = 100;
209 void MemOutputArchive::serialize_blob(const char*, const void* data, size_t len)
210 {
211  // Compress in-memory blobs:
212  //
213  // This is a bit slower than memcpy, but it uses a lot less memory.
214  // Memory usage is important for the reverse feature, where we keep a
215  // lot of savestates in memory.
216  //
217  // I compared 'gzip level=1' (fastest version with lowest compression
218  // ratio) with 'lzo'. lzo was considerably faster. Compression ratio
219  // was about the same (maybe lzo was slightly better (OTOH on higher
220  // levels gzip compresses better)). So I decided to go with lzo.
221  //
222  // Later I compared 'lzo' with 'snappy', lzo compresses 6-25% better,
223  // but 'snappy' is about twice as fast. So I switched to 'snappy'.
224  if (len >= SMALL_SIZE) {
225  size_t dstLen = snappy::maxCompressedLength(len);
226  byte* buf = buffer.allocate(sizeof(dstLen) + dstLen);
227  snappy::compress(static_cast<const char*>(data), len,
228  reinterpret_cast<char*>(&buf[sizeof(dstLen)]), dstLen);
229  memcpy(buf, &dstLen, sizeof(dstLen)); // fill-in actual size
230  buffer.deallocate(&buf[sizeof(dstLen) + dstLen]); // dealloc unused portion
231  } else {
232  byte* buf = buffer.allocate(len);
233  memcpy(buf, data, len);
234  }
235 
236 }
237 
238 void MemInputArchive::serialize_blob(const char*, void* data, size_t len)
239 {
240  if (len >= SMALL_SIZE) {
241  size_t srcLen; load(srcLen);
242  snappy::uncompress(reinterpret_cast<const char*>(buffer.getCurrentPos()),
243  srcLen, reinterpret_cast<char*>(data), len);
244  buffer.skip(srcLen);
245  } else {
246  memcpy(data, buffer.getCurrentPos(), len);
247  buffer.skip(len);
248  }
249 }
250 
252 
253 XmlOutputArchive::XmlOutputArchive(const string& filename)
254  : root("serial")
255 {
256  root.addAttribute("openmsx_version", Version::full());
257  root.addAttribute("date_time", Date::toString(time(nullptr)));
258  root.addAttribute("platform", TARGET_PLATFORM);
259  {
260  auto f = FileOperations::openFile(filename, "wb");
261  if (!f) goto error;
262  int duped_fd = dup(fileno(f.get()));
263  if (duped_fd == -1) goto error;
264  file = gzdopen(duped_fd, "wb9");
265  if (!file) {
266  close(duped_fd);
267  goto error;
268  }
269  current.push_back(&root);
270  return; // success
271  // on scope-exit 'File* f' is closed, and 'gzFile file'
272  // uses the dup()'ed file descriptor.
273  }
274 
275 error:
276  throw XMLException("Could not open compressed file \"" + filename + "\"");
277 }
278 
280 {
281  assert(current.back() == &root);
282  const char* header =
283  "<?xml version=\"1.0\" ?>\n"
284  "<!DOCTYPE openmsx-serialize SYSTEM 'openmsx-serialize.dtd'>\n";
285  gzwrite(file, const_cast<char*>(header), unsigned(strlen(header)));
286  string dump = root.dump();
287  gzwrite(file, const_cast<char*>(dump.data()), unsigned(dump.size()));
288  gzclose(file);
289 }
290 
292 {
293  save(string(1, c));
294 }
295 void XmlOutputArchive::save(const string& str)
296 {
297  assert(!current.empty());
298  assert(current.back()->getData().empty());
299  current.back()->setData(str);
300 }
302 {
303  assert(!current.empty());
304  assert(current.back()->getData().empty());
305  current.back()->setData(b ? "true" : "false");
306 }
307 void XmlOutputArchive::save(unsigned char b)
308 {
309  save(unsigned(b));
310 }
311 void XmlOutputArchive::save(signed char c)
312 {
313  save(int(c));
314 }
316 {
317  save(int(c));
318 }
320 {
321  saveImpl(i);
322 }
323 void XmlOutputArchive::save(unsigned u)
324 {
325  saveImpl(u);
326 }
327 void XmlOutputArchive::save(unsigned long long ull)
328 {
329  saveImpl(ull);
330 }
331 
332 void XmlOutputArchive::attribute(const char* name, const string& str)
333 {
334  assert(!current.empty());
335  assert(!current.back()->hasAttribute(name));
336  current.back()->addAttribute(name, str);
337 }
338 void XmlOutputArchive::attribute(const char* name, int i)
339 {
340  attributeImpl(name, i);
341 }
342 void XmlOutputArchive::attribute(const char* name, unsigned u)
343 {
344  attributeImpl(name, u);
345 }
346 
347 void XmlOutputArchive::beginTag(const char* tag)
348 {
349  assert(!current.empty());
350  auto& elem = current.back()->addChild(tag);
351  current.push_back(&elem);
352 }
353 void XmlOutputArchive::endTag(const char* tag)
354 {
355  assert(!current.empty());
356  assert(current.back()->getName() == tag); (void)tag;
357  current.pop_back();
358 }
359 
361 
362 XmlInputArchive::XmlInputArchive(const string& filename)
363  : rootElem(XMLLoader::load(filename, "openmsx-serialize.dtd"))
364 {
365  elems.emplace_back(&rootElem, 0);
366 }
367 
369 {
370  if (!elems.back().first->getChildren().empty()) {
371  throw XMLException("No child tags expected for primitive type");
372  }
373  return elems.back().first->getData();
374 }
375 void XmlInputArchive::load(string& t)
376 {
377  t = loadStr().str();
378 }
380 {
381  std::string str;
382  load(str);
383  std::istringstream is(str);
384  is >> c;
385 }
387 {
388  string_ref s = loadStr();
389  if ((s == "true") || (s == "1")) {
390  b = true;
391  } else if ((s == "false") || (s == "0")) {
392  b = false;
393  } else {
394  throw XMLException("Bad value found for boolean: " + s);
395  }
396 }
397 
398 // This function parses a number from a string. It's similar to the generic
399 // templatized XmlInputArchive::load() method, but _much_ faster. It does
400 // have some limitations though:
401 // - it can't handle leading whitespace
402 // - it can't handle extra characters at the end of the string
403 // - it can only handle one base (only decimal, not octal or hexadecimal)
404 // - it doesn't understand a leading '+' sign
405 // - it doesn't detect overflow or underflow (The generic implementation sets
406 // a 'bad' flag on the stream and clips the result to the min/max allowed
407 // value. Though this 'bad' flag was ignored by the openMSX code).
408 // This routine is only used to parse strings we've written ourselves (and the
409 // savestate/replay XML files are not meant to be manually edited). So the
410 // above limitations don't really matter. And we can use the speed gain.
411 template<bool IS_SIGNED> struct ConditionalNegate;
412 template<> struct ConditionalNegate<true> {
413  template<typename T> void operator()(bool negate, T& t) {
414  if (negate) t = -t; // ok to negate a signed type
415  }
416 };
417 template<> struct ConditionalNegate<false> {
418  template<typename T> void operator()(bool negate, T& /*t*/) {
419  assert(!negate); (void)negate; // can't negate unsigned type
420  }
421 };
422 template<typename T> static inline void fastAtoi(string_ref str, T& t)
423 {
424  t = 0;
425  bool neg = false;
426  size_t i = 0;
427  size_t l = str.size();
428 
429  static const bool IS_SIGNED = std::numeric_limits<T>::is_signed;
430  if (IS_SIGNED) {
431  if (l == 0) return;
432  if (str[0] == '-') {
433  neg = true;
434  i = 1;
435  }
436  }
437  for (; i < l; ++i) {
438  unsigned d = str[i] - '0';
439  if (unlikely(d > 9)) {
440  throw XMLException("Invalid integer: " + str);
441  }
442  t = 10 * t + d;
443  }
444  // The following stuff does the equivalent of:
445  // if (neg) t = -t;
446  // Though this expression triggers a warning on VC++ when T is an
447  // unsigned type. This complex template stuff avoids the warning.
448  ConditionalNegate<IS_SIGNED> negateFunctor;
449  negateFunctor(neg, t);
450 }
452 {
453  string_ref str = loadStr();
454  fastAtoi(str, i);
455 }
456 void XmlInputArchive::load(unsigned& u)
457 {
458  string_ref str = loadStr();
459  fastAtoi(str, u);
460 }
461 void XmlInputArchive::load(unsigned long long& ull)
462 {
463  string_ref str = loadStr();
464  fastAtoi(str, ull);
465 }
466 void XmlInputArchive::load(unsigned char& b)
467 {
468  unsigned i;
469  load(i);
470  b = i;
471 }
472 void XmlInputArchive::load(signed char& c)
473 {
474  int i;
475  load(i);
476  c = i;
477 }
479 {
480  int i;
481  load(i);
482  c = i;
483 }
484 
485 void XmlInputArchive::beginTag(const char* tag)
486 {
487  auto* child = elems.back().first->findNextChild(
488  tag, elems.back().second);
489  if (!child) {
490  string path;
491  for (auto& e : elems) {
492  path += e.first->getName() + '/';
493  }
495  "No child tag \"" << tag <<
496  "\" found at location \"" << path << '\"');
497  }
498  elems.emplace_back(child, 0);
499 }
500 void XmlInputArchive::endTag(const char* tag)
501 {
502  const auto& elem = *elems.back().first;
503  if (elem.getName() != tag) {
504  throw XMLException("End tag \"" + elem.getName() +
505  "\" not equal to begin tag \"" + tag + "\"");
506  }
507  auto& elem2 = const_cast<XMLElement&>(elem);
508  elem2.clearName(); // mark this elem for later beginTag() calls
509  elems.pop_back();
510 }
511 
512 void XmlInputArchive::attribute(const char* name, string& t)
513 {
514  try {
515  t = elems.back().first->getAttribute(name);
516  } catch (ConfigException& ex) {
517  throw XMLException(ex.getMessage());
518  }
519 }
520 void XmlInputArchive::attribute(const char* name, int& i)
521 {
522  attributeImpl(name, i);
523 }
524 void XmlInputArchive::attribute(const char* name, unsigned& u)
525 {
526  attributeImpl(name, u);
527 }
528 bool XmlInputArchive::hasAttribute(const char* name)
529 {
530  return elems.back().first->hasAttribute(name);
531 }
532 bool XmlInputArchive::findAttribute(const char* name, unsigned& value)
533 {
534  return elems.back().first->findAttributeInt(name, value);
535 }
537 {
538  return int(elems.back().first->getChildren().size());
539 }
540 
541 } // namespace openmsx
void attribute(const char *name, T &t)
Definition: serialize.hh:787
T length(const vecN< N, T > &x)
Definition: gl_vec.hh:322
size_t maxCompressedLength(size_t inLen)
Definition: snappy.cc:616
bool findAttribute(const char *name, unsigned &value)
Definition: serialize.cc:532
void serialize_blob(const char *tag, void *data, size_t len)
Definition: serialize.cc:129
string_ref::const_iterator end(const string_ref &x)
Definition: string_ref.hh:167
void operator()(bool negate, T &t)
Definition: serialize.cc:413
std::string str() const
Definition: string_ref.cc:12
#define unlikely(x)
Definition: likely.hh:15
void loadChar(char &c)
Definition: serialize.cc:379
XmlInputArchive(const std::string &filename)
Definition: serialize.cc:362
void * getPointer(unsigned id)
Definition: serialize.cc:116
void save(const T &t)
Definition: serialize.hh:588
bool decode_inplace(string_ref input, uint8_t *output, size_t outSize)
Definition: HexDump.cc:74
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:500
void serialize_blob(const char *, void *data, size_t len)
Definition: serialize.cc:238
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:175
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:528
void compress(const char *input, size_t inLen, char *output, size_t &outLen)
Definition: snappy.cc:603
void attribute(const char *name, const T &t)
Definition: serialize.hh:724
void endTag(const char *tag)
Definition: serialize.cc:353
void attributeImpl(const char *name, const T &t)
Definition: serialize.hh:720
void attribute(const char *name, T &t)
Load/store an attribute from/in the archive.
Definition: serialize.hh:205
void serialize_blob(const char *, const void *data, size_t len)
Definition: serialize.cc:209
void save(const T &t)
Definition: serialize.hh:695
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
unsigned char byte
8 bit unsigned integer
Definition: openmsx.hh:25
void operator()(bool negate, T &)
Definition: serialize.cc:418
void beginTag(const char *tag)
Definition: serialize.cc:485
int countChildren() const
Definition: serialize.cc:536
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:689
XmlOutputArchive(const std::string &filename)
Definition: serialize.cc:253
void beginTag(const char *tag)
Definition: serialize.cc:347
void serialize_blob(const char *tag, const void *data, size_t len)
Definition: serialize.cc:77
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:780