ROSE  0.9.10.230
MemoryMap.h
1 #ifndef ROSE_BinaryAnalysis_MemoryMap_H
2 #define ROSE_BinaryAnalysis_MemoryMap_H
3 
4 #include <ByteOrder.h>
5 #include <Combinatorics.h>
6 #include <RoseException.h>
7 
8 #include <Sawyer/Access.h>
9 #include <Sawyer/AddressMap.h>
10 #include <Sawyer/AllocatingBuffer.h>
11 #include <Sawyer/MappedBuffer.h>
12 #include <Sawyer/NullBuffer.h>
13 #include <Sawyer/Optional.h>
14 #include <Sawyer/StaticBuffer.h>
15 
16 #include <boost/config.hpp>
17 #include <boost/utility/enable_if.hpp>
18 #include <boost/serialization/access.hpp>
19 #include <boost/serialization/base_object.hpp>
20 #include <boost/serialization/export.hpp>
21 #include <boost/type_traits/is_integral.hpp>
22 
23 namespace Rose {
24 namespace BinaryAnalysis {
25 
31 template<typename T, typename U>
32 typename boost::enable_if_c<boost::is_integral<T>::value && boost::is_integral<U>::value, T>::type
33 alignUp(T address, U alignment) {
34  ASSERT_require(alignment > 0);
35  T almt = static_cast<T>(alignment);
36  return ((address + almt - 1) / almt) * almt;
37 }
38 
44 template<typename T, typename U>
45 typename boost::enable_if_c<boost::is_integral<T>::value && boost::is_integral<U>::value, T>::type
46 alignDown(T address, U alignment) {
47  ASSERT_require(alignment > 0);
48  T almt = static_cast<T>(alignment);
49  return (address / almt) * almt;
50 }
51 
109 class MemoryMap: public Sawyer::Container::AddressMap<rose_addr_t, uint8_t>, public Sawyer::SharedObject {
110 public:
112  typedef rose_addr_t Address;
113  typedef uint8_t Value;
123 
125  struct Attach { // For consistency with other <Feature>::Boolean types
126  enum Boolean {
127  NO,
129  };
130  };
131 
132 private:
133  ByteOrder::Endianness endianness_;
134 
135 #ifdef ROSE_HAVE_BOOST_SERIALIZATION_LIB
136 private:
137  friend class boost::serialization::access;
138 
139  template<class S>
140  void serialize(S &s, const unsigned /*version*/) {
141  s.template register_type<AllocatingBuffer>();
142  s.template register_type<MappedBuffer>();
143  s.template register_type<NullBuffer>();
144  s.template register_type<StaticBuffer>();
145  s & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Super);
146  s & BOOST_SERIALIZATION_NVP(endianness_);
147  }
148 #endif
149 
150 public:
151 
152  // Whoever pollutes all namespaces with these common word preprocessor symbols is a lunatic!
153 # if defined(READABLE) || defined(WRITABLE) || defined(EXECUTABLE) || defined(IMMUTABLE) || defined(PRIVATE)
154 # ifdef _MSC_VER
155 # pragma message("Undefining common words from the global namespace: READABLE, WRITABLE, EXECUTABLE, IMMUTABLE, PRIVATE")
156 # else
157 # warning "Undefining common words from the global namespace: READABLE, WRITABLE, EXECUTABLE, IMMUTABLE, PRIVATE"
158 # endif
159 # undef READABLE
160 # undef WRITABLE
161 # undef EXECUTABLE
162 # undef IMMUTABLE
163 # undef PRIVATE
164 # endif
165 
166  // Accessibility flags
167  static const unsigned NO_ACCESS = 0;
168  static const unsigned READABLE = Sawyer::Access::READABLE;
169  static const unsigned WRITABLE = Sawyer::Access::WRITABLE;
170  static const unsigned EXECUTABLE = Sawyer::Access::EXECUTABLE;
171  static const unsigned IMMUTABLE = Sawyer::Access::IMMUTABLE;
172  static const unsigned PRIVATE = Sawyer::Access::PRIVATE;
173  static const unsigned INITIALIZED = 0x00000200; // Partitioner2: initialized memory even if writable
174 
175  // Aggregate accessibility flags
176  static const unsigned READ_WRITE = READABLE | WRITABLE;
177  static const unsigned READ_EXECUTE = READABLE | EXECUTABLE;
178  static const unsigned READ_WRITE_EXECUTE = READABLE | WRITABLE | EXECUTABLE;
179 
180  // These bits are reserved for use in ROSE
181  static const unsigned RESERVED_ACCESS_BITS = 0x0000ffff;
182 
183 
184 public:
186  class Exception: public Rose::Exception {
187  public:
188  Exception(const std::string &mesg, const MemoryMap::Ptr map): Rose::Exception(mesg), map(map) {}
189  virtual ~Exception() throw() {}
190  virtual std::string leader(std::string dflt="memory map problem") const;
191  virtual std::string details(bool) const;
192  virtual void print(std::ostream&, bool verbose=true) const;
193  friend std::ostream& operator<<(std::ostream&, const Exception&);
194  public:
196  };
197 
202  struct Inconsistent : public Exception {
203  Inconsistent(const std::string &mesg, const MemoryMap::Ptr &map,
204  const AddressInterval &new_range, const Segment &new_segment,
205  const AddressInterval &old_range, const Segment &old_segment)
206  : Exception(mesg, map),
207  new_range(new_range), old_range(old_range),
208  new_segment(new_segment), old_segment(old_segment) {}
209  virtual ~Inconsistent() throw() {}
210  virtual void print(std::ostream&, bool verbose=true) const;
211  friend std::ostream& operator<<(std::ostream&, const Inconsistent&);
212  AddressInterval new_range, old_range;
213  Segment new_segment, old_segment;
214  };
215 
217  struct NotMapped : public Exception {
218  NotMapped(const std::string &mesg, const MemoryMap::Ptr &map, rose_addr_t va)
219  : Exception(mesg, map), va(va) {}
220  virtual ~NotMapped() throw() {}
221  virtual void print(std::ostream&, bool verbose=true) const;
222  friend std::ostream& operator<<(std::ostream&, const NotMapped&);
223  rose_addr_t va;
224  };
225 
227  struct NoFreeSpace : public Exception {
228  NoFreeSpace(const std::string &mesg, const MemoryMap::Ptr &map, size_t size)
229  : Exception(mesg, map), size(size) {}
230  virtual ~NoFreeSpace() throw() {}
231  virtual void print(std::ostream&, bool verbose=true) const;
232  friend std::ostream& operator<<(std::ostream&, const NoFreeSpace&);
233  size_t size;
234  };
235 
237  struct SyntaxError: public Exception {
238  SyntaxError(const std::string &mesg, const MemoryMap::Ptr &map, const std::string &filename,
239  unsigned linenum, int colnum=-1)
240  : Exception(mesg, map), filename(filename), linenum(linenum), colnum(colnum) {}
241  virtual ~SyntaxError() throw() {}
242  virtual void print(std::ostream&, bool verbose=true) const;
243  friend std::ostream& operator<<(std::ostream&, const SyntaxError&);
244  std::string filename;
245  unsigned linenum;
246  int colnum;
247  };
248 
249 protected:
251  MemoryMap(): endianness_(ByteOrder::ORDER_UNSPECIFIED) {}
252 
253 public:
255  static Ptr instance() {
256  return Ptr(new MemoryMap);
257  }
258 
262  Ptr shallowCopy() {
263  return Ptr(new MemoryMap(*this));
264  }
265 
273  ByteOrder::Endianness byteOrder() const { return endianness_; }
274  void byteOrder(ByteOrder::Endianness order) { endianness_ = order; }
277  // Note that the order of the enum members is for backward compatibility with an older version of insertFile whose third
278  // argument was "bool writable = false" (MAP_RDONLY, but now intended to be MAP_PRIVATE) and when it was true was the same
279  // as MAP_READWRITE.
280  //
289  };
290 
295  size_t insertFile(const std::string &fileName, rose_addr_t va, InsertFileMapMode mode = MAP_PRIVATE,
296  std::string segmentName = "");
297 
373  AddressInterval insertFile(const std::string &locatorString);
374 
376  static std::string insertFileDocumentation();
377 
404  AddressInterval insertData(const std::string &locatorString);
405 
407  static std::string insertDataDocumentation();
408 
409 
410 #ifdef BOOST_WINDOWS
411  void insertProcess(int pid, Attach::Boolean attach);
412 #else
413 
414  void insertProcess(pid_t pid, Attach::Boolean attach);
415 #endif
416 
420  void insertProcess(const std::string &locatorString);
421 
423  static std::string insertProcessDocumentation();
424 
426  void eraseZeros(size_t minsize);
427 
438  bool shrinkUnshare();
439 
441  size_t readQuick(void *buf, rose_addr_t startVa, size_t desired) const {
442  return at(startVa).limit(desired).require(READABLE).read((uint8_t*)buf).size();
443  }
444 
457  std::string readString(rose_addr_t startVa, size_t desired, int(*validChar)(int)=NULL, int(*invalidChar)(int)=NULL,
458  unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0, char terminator='\0') const;
459 
465  template<typename U>
466  Sawyer::Optional<U> readUnsigned(rose_addr_t startVa) const {
467  U val = 0;
468  if (at(startVa).limit(sizeof val).read((uint8_t*)&val).size() != sizeof val)
469  return Sawyer::Nothing();
470  ByteOrder::convert((void*)&val, sizeof val, endianness_, ByteOrder::host_order());
471  return val;
472  }
473 
475  SgUnsignedCharList readVector(rose_addr_t startVa, size_t desired, unsigned requiredPerms=READABLE) const;
476 
478  size_t writeQuick(const void *buf, rose_addr_t startVa, size_t desired) {
479  return at(startVa).limit(desired).require(WRITABLE).write((const uint8_t*)buf).size();
480  }
481 
489  Sawyer::Optional<rose_addr_t> findAny(const Extent &limits, const std::vector<uint8_t> &bytesToFind,
490  unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0) const;
491  Sawyer::Optional<rose_addr_t> findAny(const AddressInterval &limits, const std::vector<uint8_t> &bytesToFind,
492  unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0) const;
500  Sawyer::Optional<rose_addr_t> findSequence(const AddressInterval &interval, const std::vector<uint8_t> &sequence) const;
501 
505  void dump(FILE*, const char *prefix="") const;
506  void dump(std::ostream&, std::string prefix="") const;
507  void print(std::ostream &o, std::string prefix="") const { dump(o, prefix); }
525 
527  static std::string segmentTitle(const Segment&);
528 
529  friend std::ostream& operator<<(std::ostream&, const MemoryMap&);
530 };
531 
532 } // namespace
533 } // namespace
534 
535 // Register the types needed for serialization since some of them are derived from polymorphic class templates.
536 #ifdef ROSE_HAVE_BOOST_SERIALIZATION_LIB
538 BOOST_CLASS_EXPORT_KEY(Rose::BinaryAnalysis::MemoryMap::MappedBuffer);
539 BOOST_CLASS_EXPORT_KEY(Rose::BinaryAnalysis::MemoryMap::NullBuffer);
540 BOOST_CLASS_EXPORT_KEY(Rose::BinaryAnalysis::MemoryMap::StaticBuffer);
541 #endif
542 
543 
544 #endif
Exception thrown by find_free() when there's not enough free space left.
Definition: MemoryMap.h:227
int colnum
Optional column number (0-origin; negative if unknown).
Definition: MemoryMap.h:246
Points to static data.
Definition: StaticBuffer.h:30
Exception thrown by load() when there's a syntax error in the index file.
Definition: MemoryMap.h:237
virtual std::string leader(std::string dflt="memory map problem") const
Leading part of the error message.
void print(std::ostream &o, std::string prefix="") const
Prints the contents of the map for debugging.
Definition: MemoryMap.h:507
virtual std::string details(bool) const
Details emitted on following lines, indented two spaces.
AddressMapConstraints< const AddressMap > at(Address x) const
Constraint: anchor point.
Definition: AddressMap.h:1082
static std::string insertFileDocumentation()
Documentation string for insertFile.
size_t insertFile(const std::string &fileName, rose_addr_t va, InsertFileMapMode mode=MAP_PRIVATE, std::string segmentName="")
Insert file contents into memory map.
A contiguous range of values.
Definition: rangemap.h:50
InsertFileMapMode
Mapping mode for insertFile.
Definition: MemoryMap.h:282
MemoryMap()
Constructs an empty memory map.
Definition: MemoryMap.h:251
Holds a value or nothing.
Definition: Optional.h:49
MemoryMap::Ptr map
Map that caused the exception if available, null otherwise.
Definition: MemoryMap.h:195
Attach with ptrace, get memory, then detach.
Definition: MemoryMap.h:128
AddressSegment< rose_addr_t, uint8_t > Segment
Type of segments stored by this map.
Definition: AddressMap.h:978
AddressInterval insertData(const std::string &locatorString)
Insert data into a memory map.
Main namespace for the ROSE library.
Memory mapped file.
Definition: MappedBuffer.h:43
File is mapped with read-only permission.
Definition: MemoryMap.h:287
Allocates memory as needed.
std::string filename
Name of index file where error occurred.
Definition: MemoryMap.h:244
Combinatorics::Hasher & hash(Combinatorics::Hasher &) const
Compute a hash of the entire memory contents.
static Ptr instance()
Construct an empty memory map.
Definition: MemoryMap.h:255
void byteOrder(ByteOrder::Endianness order)
Property: byte order.
Definition: MemoryMap.h:274
Sawyer::Container::Interval< Address > read(Value *buf, const AddressMapConstraints< const AddressMap > &c, MatchFlags flags=0) const
Reads data into the supplied buffer.
Definition: AddressMap.h:1657
File is mapped with read and write permission.
Definition: MemoryMap.h:285
size_t readQuick(void *buf, rose_addr_t startVa, size_t desired) const
Read data into buffer.
Definition: MemoryMap.h:441
void insertProcess(pid_t pid, Attach::Boolean attach)
Insert the memory of some other process into this memory map.
Exception for when we try to access a virtual address that isn't mapped.
Definition: MemoryMap.h:217
A mapping from address space to values.
Definition: AddressMap.h:971
Buffer that has no data.
Definition: NullBuffer.h:26
Base class for all buffers.
Definition: Buffer.h:25
An efficient mapping from an address space to stored data.
Definition: MemoryMap.h:109
boost::enable_if_c< boost::is_integral< T >::value &&boost::is_integral< U >::value, T >::type alignDown(T address, U alignment)
Align address upward to boundary.
Definition: MemoryMap.h:46
boost::enable_if_c< boost::is_integral< T >::value &&boost::is_integral< U >::value, T >::type alignUp(T address, U alignment)
Align address downward to boundary.
Definition: MemoryMap.h:33
unsigned linenum
Line number (1 origin) where error occurred.
Definition: MemoryMap.h:245
Constraints are used to select addresses from a memory map.
Definition: AddressMap.h:76
Sawyer::Optional< rose_addr_t > findSequence(const AddressInterval &interval, const std::vector< uint8_t > &sequence) const
Search for a byte sequence.
std::string readString(rose_addr_t startVa, size_t desired, int(*validChar)(int)=NULL, int(*invalidChar)(int)=NULL, unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0, char terminator='\0') const
Reads a NUL-terminated string from the memory map.
Base class for reference counted objects.
Definition: SharedObject.h:64
Exception for an inconsistent mapping.
Definition: MemoryMap.h:202
void dump(FILE *, const char *prefix="") const
Prints the contents of the map for debugging.
void eraseZeros(size_t minsize)
Erases regions of zero bytes that are executable and readable and at least minsize in size...
SgUnsignedCharList readVector(rose_addr_t startVa, size_t desired, unsigned requiredPerms=READABLE) const
Read quickly into a vector.
Attach with ptrace first when reading a process?
Definition: MemoryMap.h:125
bool shrinkUnshare()
Shrink buffers and remove sharing.
Represents no value.
Definition: Optional.h:32
ByteOrder::Endianness byteOrder() const
Property: byte order.
Definition: MemoryMap.h:273
static std::string insertDataDocumentation()
Documentation string for insertData.
Sawyer::Optional< rose_addr_t > findAny(const Extent &limits, const std::vector< uint8_t > &bytesToFind, unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0) const
Search for any byte.
static std::string segmentTitle(const Segment &)
Title of a segment when printing the map.
Base class for all ROSE exceptions.
Definition: RoseException.h:9
static std::string insertProcessDocumentation()
Documentation string for insertProcess.
AddressMapConstraints< const AddressMap > limit(size_t x) const
Constraint: limit matched size.
Definition: AddressMap.h:1123
size_t writeQuick(const void *buf, rose_addr_t startVa, size_t desired)
Write data from buffer.
Definition: MemoryMap.h:478
Sawyer::Optional< U > readUnsigned(rose_addr_t startVa) const
Read an unsigned value.
Definition: MemoryMap.h:466
Exception for MemoryMap operations.
Definition: MemoryMap.h:186
Assume ptrace is attached and process is stopped.
Definition: MemoryMap.h:127
Ptr shallowCopy()
Create a new copy of the memory map.
Definition: MemoryMap.h:262