ROSE  0.9.10.89
BinarySerialIo.h
1 #ifndef Rose_BinaryAnalysis_SerialIo_H
2 #define Rose_BinaryAnalysis_SerialIo_H
3 
4 #include <Progress.h>
5 #include <boost/filesystem.hpp>
6 #include <boost/lexical_cast.hpp>
7 #include <boost/thread.hpp>
8 #include <Sawyer/Message.h>
9 #include <Sawyer/ProgressBar.h>
10 #include <Sawyer/Synchronization.h>
11 
12 // Define this if you need to debug SerialIo -- it causes everything to run in the calling thread and avoid catching exceptions.
13 //#define ROSE_DEBUG_SERIAL_IO
14 
15 #if defined(BOOST_WINDOWS)
16  // Lacks POSIX file system, so we can't monitor the I/O progress
17  #undef ROSE_SUPPORTS_SERIAL_IO
18 #elif !defined(ROSE_HAVE_BOOST_SERIALIZATION_LIB)
19  // Lacks Boost's serialization library, which is how we convert objects to bytes and vice versa
20  #undef ROSE_SUPPORTS_SERIAL_IO
21 #elif defined(__GNUC__)
22  #if __GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNU_C_PATCHLEVEL__ <= 40204
23  // GCC <= 4.2.4 gets segfaults compiling this file
24  #undef ROSE_SUPPORTS_SERIAL_IO
25  #else
26  #define ROSE_SUPPORTS_SERIAL_IO /*supported*/
27  #endif
28 #else
29  #define ROSE_SUPPORTS_SERIAL_IO /*supported*/
30 #endif
31 
32 #ifdef ROSE_SUPPORTS_SERIAL_IO
33 #include <boost/archive/binary_iarchive.hpp>
34 #include <boost/archive/binary_oarchive.hpp>
35 #include <boost/archive/text_iarchive.hpp>
36 #include <boost/archive/text_oarchive.hpp>
37 #include <boost/archive/xml_iarchive.hpp>
38 #include <boost/archive/xml_oarchive.hpp>
39 #include <boost/iostreams/device/file_descriptor.hpp>
40 #include <boost/iostreams/stream.hpp>
41 #endif
42 
43 namespace Rose {
44 namespace BinaryAnalysis {
45 
46 namespace Partitioner2 {
47 class Partitioner;
48 }
49 
51 // SerialIo
53 
111 public:
114 
116  enum Format {
124  };
125 
127  enum Savable {
128  NO_OBJECT = 0x00000000,
129  PARTITIONER = 0x00000001,
130  AST = 0x00000002,
131  END_OF_DATA = 0x0000fffe,
132  ERROR = 0x0000ffff,
133  USER_DEFINED = 0x00010000,
134  USER_DEFINED_LAST = 0xffffffff
135  };
136 
138  class Exception: public std::runtime_error {
139  public:
141  explicit Exception(const std::string &s): std::runtime_error(s) {}
142  ~Exception() throw() {}
143  };
144 
145 private:
146  mutable SAWYER_THREAD_TRAITS::Mutex mutex_; // protects the following data members
147  Format format_;
148  Progress::Ptr progress_;
149  bool isOpen_;
150  Savable objectType_;
151 
152 protected:
153  Sawyer::ProgressBar<size_t> progressBar_;
154 
155  // We use low-level file descriptors under an std::stream I/O interface in order to provide progress reports. This
156  // allows one thread to be reading from or writing to the file and another thread to monitor the file position to
157  // report progress. The C++ standard library doesn't have an API for wrapping file descriptors in a stream interface,
158  // so we use Boost.
159  int fd_;
160 
161 protected:
162  SerialIo()
163  : format_(BINARY), progress_(Progress::instance()), isOpen_(false), objectType_(NO_OBJECT),
164  progressBar_(mlog[Sawyer::Message::MARCH]), fd_(-1) {
165  init();
166  }
167 
168 public:
171 
179  virtual ~SerialIo();
180 
189  Format format() const;
190  void format(Format);
201  Progress::Ptr progress() const;
202  void progress(const Progress::Ptr&);
213  virtual void open(const boost::filesystem::path&) = 0;
214 
226  virtual void close() = 0;
227 
233  bool isOpen() const;
234 
239  Savable objectType() const;
240 
241 protected:
242  // Set or clear the isOpen flag.
243  void setIsOpen(bool b);
244 
245  // Set object type to ERROR to indicate that a read was unsuccessful
246  void objectType(Savable);
247 
248 private:
249  void init();
250 };
251 
252 
254 // SerialOutput
256 
260 class SerialOutput: public SerialIo {
261 public:
263 
264 private:
265 #ifdef ROSE_SUPPORTS_SERIAL_IO
266  boost::iostreams::file_descriptor_sink device_;
267  boost::iostreams::stream<boost::iostreams::file_descriptor_sink> file_;
268  boost::archive::binary_oarchive *binary_archive_;
269  boost::archive::text_oarchive *text_archive_;
270  boost::archive::xml_oarchive *xml_archive_;
271 #endif
272 
273 protected:
274 #ifdef ROSE_SUPPORTS_SERIAL_IO
275  SerialOutput(): binary_archive_(NULL), text_archive_(NULL), xml_archive_(NULL) {}
276 #else
277  SerialOutput() {}
278 #endif
279 
280 public:
281  ~SerialOutput();
282  void open(const boost::filesystem::path &fileName) ROSE_OVERRIDE;
283  void close() ROSE_OVERRIDE;
284 
289  static Ptr instance() { return Ptr(new SerialOutput); }
290 
301 
313  void saveAst(SgAsmNode*);
314  void saveAst(SgBinaryComposite*);
315 private:
316  // The saveAstHelper is what actually gets called for the functions above. It doesn't descriminate between nodes that
317  // support serialization and those that don't, which is why it's private. Use only the public functions because they'll
318  // give you a nice compiler error if you try to save an Ast node type that isn't supported.
319  void saveAstHelper(SgNode*);
320 public:
321 
336  template<class T>
337  void saveObject(Savable objectTypeId, const T &object) {
338  if (!isOpen())
339  throw Exception("cannot save object when no file is open");
340  if (ERROR == objectType())
341  throw Exception("cannot save object because stream is in error state");
342 
343 #ifndef ROSE_SUPPORTS_SERIAL_IO
344  throw Exception("binary state files are not supported in this configuration");
345 #elif defined(ROSE_DEBUG_SERIAL_IO)
346  std::string errorMessage;
347  asyncSave(objectTypeId, object, &errorMessage);
348 #else
349  // A different thread saves the object while this thread updates the progress
350  std::string errorMessage;
351  boost::thread worker(startWorker<T>, this, objectTypeId, object, &errorMessage);
352  boost::chrono::milliseconds timeout((unsigned)(1000 * Sawyer::ProgressBarSettings::minimumUpdateInterval()));
353  while (!worker.try_join_for(timeout)) {
354  off_t cur = ::lseek(fd_, 0, SEEK_CUR);
355  if (-1 == cur) {
356  ++progressBar_; // so a spinner moves
357  } else {
358  progressBar_.value(cur);
359  if (Progress::Ptr p = progress())
360  p->update(Progress::Report(cur, NAN));
361  }
362  }
363  if (!errorMessage.empty())
364  throw Exception(errorMessage);
365 #endif
366  }
367 
368 private:
369  template<class T>
370  static void startWorker(SerialOutput *saver, Savable objectTypeId, const T &object, std::string *errorMessage) {
371  saver->asyncSave(objectTypeId, object, errorMessage);
372  }
373 
374  // This might run in its own thread.
375  template<class T>
376  void asyncSave(Savable objectTypeId, const T &object, std::string *errorMessage) {
377  ASSERT_not_null(errorMessage);
378 #ifndef ROSE_SUPPORTS_SERIAL_IO
379  ASSERT_not_reachable("not supported in this configuration");
380 #else
381 #if !defined(ROSE_DEBUG_SERIAL_IO)
382  try {
383 #endif
384  objectType(ERROR);
385  switch (format()) {
386  case BINARY:
387  ASSERT_not_null(binary_archive_);
388  *binary_archive_ <<BOOST_SERIALIZATION_NVP(objectTypeId);
389  *binary_archive_ <<BOOST_SERIALIZATION_NVP(object);
390  break;
391  case TEXT:
392  ASSERT_not_null(text_archive_);
393  *text_archive_ <<BOOST_SERIALIZATION_NVP(objectTypeId);
394  *text_archive_ <<BOOST_SERIALIZATION_NVP(object);
395  break;
396  case XML:
397  ASSERT_not_null(xml_archive_);
398  *xml_archive_ <<BOOST_SERIALIZATION_NVP(objectTypeId);
399  *xml_archive_ <<BOOST_SERIALIZATION_NVP(object);
400  break;
401  }
402  objectType(objectTypeId);
403 #if !defined(ROSE_DEBUG_SERIAL_IO)
404  } catch (const Exception &e) {
405  *errorMessage = e.what();
406  } catch (...) {
407  *errorMessage = "failed to write object to output stream";
408  }
409 #endif
410 #endif
411  }
412 };
413 
414 
416 // SerialInput
418 
422 class SerialInput: public SerialIo {
423 public:
425 
426 private:
427 #ifdef ROSE_SUPPORTS_SERIAL_IO
428  size_t fileSize_;
429  boost::iostreams::file_descriptor_source device_;
430  boost::iostreams::stream<boost::iostreams::file_descriptor_source> file_;
431  boost::archive::binary_iarchive *binary_archive_;
432  boost::archive::text_iarchive *text_archive_;
433  boost::archive::xml_iarchive *xml_archive_;
434 #endif
435 
436 protected:
437 #ifdef ROSE_SUPPORTS_SERIAL_IO
438  SerialInput(): fileSize_(0), binary_archive_(NULL), text_archive_(NULL), xml_archive_(NULL) {}
439 #else
440  SerialInput() {}
441 #endif
442 
443 public:
444  ~SerialInput();
445  void open(const boost::filesystem::path &fileName) ROSE_OVERRIDE;
446  void close() ROSE_OVERRIDE;
447 
452  static Ptr instance() { return Ptr(new SerialInput); }
453 
462 
470 
478  SgNode* loadAst();
479 
480  template<class T>
481  T loadObject(Savable objectTypeId) {
482  if (!isOpen())
483  throw Exception("cannot load object when no file is open");
484 
485 #ifndef ROSE_SUPPORTS_SERIAL_IO
486  throw Exception("binary state files are not supported in this configuration");
487 #else
488  if (ERROR == objectType())
489  throw Exception("cannot read object because stream is in error state");
490  if (objectType() != objectTypeId) {
491  throw Exception("unexpected object type (expected " + boost::lexical_cast<std::string>(objectTypeId) +
492  " but read " + boost::lexical_cast<std::string>(objectType()) + ")");
493  }
494  objectType(ERROR); // in case of exception
495  T object;
496  std::string errorMessage;
497 #ifdef ROSE_DEBUG_SERIAL_IO
498  asyncLoad(object, &errorMessage);
499 #else
500  boost::thread worker(startWorker<T>, this, &object, &errorMessage);
501  boost::chrono::milliseconds timeout((unsigned)(1000 * Sawyer::ProgressBarSettings::minimumUpdateInterval()));
502  while (!worker.try_join_for(timeout)) {
503  if (fileSize_ > 0) {
504  off_t cur = ::lseek(fd_, 0, SEEK_CUR);
505  if (cur != -1) {
506  progressBar_.value(cur);
507  if (Progress::Ptr p = progress())
508  p->update(Progress::Report(cur, fileSize_));
509  }
510  } else {
511  ++progressBar_; // so the spinner moves
512  }
513  }
514  if (!errorMessage.empty())
515  throw Exception(errorMessage);
516 #endif
517  advanceObjectType();
518  return object;
519 #endif
520  }
521 
522 private:
523  template<class T>
524  static void startWorker(SerialInput *loader, T *object, std::string *errorMessage) {
525  loader->asyncLoad(*object, errorMessage);
526  }
527 
528  // Might run in its own thread
529  template<class T>
530  void asyncLoad(T &object, std::string *errorMessage) {
531  ASSERT_not_null(errorMessage);
532 #ifndef ROSE_SUPPORTS_SERIAL_IO
533  ASSERT_not_reachable("not supported in this configuration");
534 #else
535 #if !defined(ROSE_DEBUG_SERIAL_IO)
536  try {
537 #endif
538  switch (format()) {
539  case BINARY:
540  ASSERT_not_null(binary_archive_);
541  *binary_archive_ >>object;
542  break;
543  case TEXT:
544  ASSERT_not_null(text_archive_);
545  *text_archive_ >>object;
546  break;
547  case XML:
548  ASSERT_not_null(xml_archive_);
549  *xml_archive_ >>BOOST_SERIALIZATION_NVP(object);
550  break;
551  }
552 #if !defined(ROSE_DEBUG_SERIAL_IO)
553  } catch (const Exception &e) {
554  *errorMessage = e.what();
555  } catch (...) {
556  *errorMessage = "failed to read object from input stream";
557  }
558 #endif
559 #endif
560  }
561 
562 protected:
563  // Read the next object type from the input stream
564  void advanceObjectType();
565 };
566 
567 } // namespace
568 } // namespace
569 
570 #endif
Savable
Types of objects that can be saved.
A single progress report.
Definition: Progress.h:178
double minimumUpdateInterval()
Minimum time between updates.
Base class for all binary analysis IR nodes.
Textual binary state files use a custom format (Boost serialization format) that stores the data as A...
void savePartitioner(const Partitioner2::Partitioner &)
Save a binary analysis partitioner.
void close() ROSE_OVERRIDE
Detach a file.
Collection of streams.
Definition: Message.h:1579
First user-defined object number.
void saveObject(Savable objectTypeId, const T &object)
Save an object to the output stream.
Format format() const
Property: File format.
Output binary analysis state.
STL namespace.
Rose::BinaryAnalysis::Partitioner2::Partitioner.
void saveAst(SgAsmNode *)
Save a binary AST.
static Sawyer::Message::Facility mlog
Message facility.
Main namespace for the ROSE library.
Base class for binary state input and output.
Progress::Ptr progress() const
Property: Progress reporter.
SgNode * loadAst()
Load an AST from the input stream.
Reference-counting smart pointer.
Definition: SharedPointer.h:34
Name space for the entire library.
Definition: Access.h:13
Object type for newly-initialized serializers.
Savable objectType() const
Type ID for next object.
Exception(const std::string &s)
Construct an exception with an error message.
virtual void open(const boost::filesystem::path &)=0
Attach a file.
Marks that the stream has encountered an error condition.
void open(const boost::filesystem::path &fileName) ROSE_OVERRIDE
Attach a file.
void close() ROSE_OVERRIDE
Detach a file.
static Ptr instance()
Factory method to create a new instance.
The states are stored as XML, which is a very verbose and slow format.
This class represents the base class for all IR nodes within Sage III.
Definition: Cxx_Grammar.h:8752
static Ptr instance()
Factory method to create a new instance.
void open(const boost::filesystem::path &fileName) ROSE_OVERRIDE
Attach a file.
ValueType value() const
Value for the progress bar.
Definition: ProgressBar.h:163
Partitioner2::Partitioner loadPartitioner()
Load a partitioner from the input stream.
bool isOpen() const
Whether a file is attached.
virtual ~SerialIo()
Destructor.
Base class for reference counted objects.
Definition: SharedObject.h:22
A general, thread-safe way to report progress made on some task.
Definition: Progress.h:164
Marks the end of the data stream.
Format
Format of the state file.
Partitions instructions into basic blocks and functions.
Definition: Partitioner.h:293
Binary state files are smaller and faster than the other formats, but are not portable across archite...
virtual void close()=0
Detach a file.
Input binary analysis state.
Sawyer::SharedPointer< SerialIo > Ptr
Reference-counting pointer.
Savable nextObjectType()
Type of next object in the input stream.