ROSE  0.9.10.54
MemoryMap.h
1 #ifndef ROSE_BinaryAnalysis_MemoryMap_H
2 #define ROSE_BinaryAnalysis_MemoryMap_H
3 
4 #include <ByteOrder.h>
5 #include <Combinatorics.h>
6 
7 #include <Sawyer/Access.h>
8 #include <Sawyer/AddressMap.h>
9 #include <Sawyer/AllocatingBuffer.h>
10 #include <Sawyer/MappedBuffer.h>
11 #include <Sawyer/NullBuffer.h>
12 #include <Sawyer/Optional.h>
13 #include <Sawyer/StaticBuffer.h>
14 
15 #include <boost/config.hpp>
16 #include <boost/serialization/access.hpp>
17 #include <boost/serialization/base_object.hpp>
18 #include <boost/serialization/export.hpp>
19 
20 namespace Rose {
21 namespace BinaryAnalysis {
22 
26 template<typename T>
27 T alignUp(T address, T alignment) {
28  return ((address + alignment - 1) / alignment) * alignment;
29 }
30 
35 template<typename T>
36 T alignDown(T address, T alignment) {
37  return (address / alignment) * alignment;
38 }
39 
97 class MemoryMap: public Sawyer::Container::AddressMap<rose_addr_t, uint8_t>, public Sawyer::SharedObject {
98 public:
100  typedef rose_addr_t Address;
101  typedef uint8_t Value;
111 
113  struct Attach { // For consistency with other <Feature>::Boolean types
114  enum Boolean {
115  NO,
117  };
118  };
119 
120 private:
121  ByteOrder::Endianness endianness_;
122 
123 #ifdef ROSE_HAVE_BOOST_SERIALIZATION_LIB
124 private:
125  friend class boost::serialization::access;
126 
127  template<class S>
128  void serialize(S &s, const unsigned /*version*/) {
129  s.template register_type<AllocatingBuffer>();
130  s.template register_type<MappedBuffer>();
131  s.template register_type<NullBuffer>();
132  s.template register_type<StaticBuffer>();
133  s & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Super);
134  s & BOOST_SERIALIZATION_NVP(endianness_);
135  }
136 #endif
137 
138 public:
139 
140  // Whoever pollutes all namespaces with these common word preprocessor symbols is a lunatic!
141 # if defined(READABLE) || defined(WRITABLE) || defined(EXECUTABLE) || defined(IMMUTABLE) || defined(PRIVATE)
142 # ifdef _MSC_VER
143 # pragma message("Undefining common words from the global namespace: READABLE, WRITABLE, EXECUTABLE, IMMUTABLE, PRIVATE")
144 # else
145 # warning "Undefining common words from the global namespace: READABLE, WRITABLE, EXECUTABLE, IMMUTABLE, PRIVATE"
146 # endif
147 # undef READABLE
148 # undef WRITABLE
149 # undef EXECUTABLE
150 # undef IMMUTABLE
151 # undef PRIVATE
152 # endif
153 
154  // Accessibility flags
155  static const unsigned NO_ACCESS = 0;
156  static const unsigned READABLE = Sawyer::Access::READABLE;
157  static const unsigned WRITABLE = Sawyer::Access::WRITABLE;
158  static const unsigned EXECUTABLE = Sawyer::Access::EXECUTABLE;
159  static const unsigned IMMUTABLE = Sawyer::Access::IMMUTABLE;
160  static const unsigned PRIVATE = Sawyer::Access::PRIVATE;
161  static const unsigned INITIALIZED = 0x00000200; // Partitioner2: initialized memory even if writable
162 
163  // Aggregate accessibility flags
164  static const unsigned READ_WRITE = READABLE | WRITABLE;
165  static const unsigned READ_EXECUTE = READABLE | EXECUTABLE;
166  static const unsigned READ_WRITE_EXECUTE = READABLE | WRITABLE | EXECUTABLE;
167 
168  // These bits are reserved for use in ROSE
169  static const unsigned RESERVED_ACCESS_BITS = 0x0000ffff;
170 
171 
172 public:
174  class Exception: public std::runtime_error {
175  public:
176  Exception(const std::string &mesg, const MemoryMap::Ptr map): std::runtime_error(mesg), map(map) {}
177  virtual ~Exception() throw() {}
178  virtual std::string leader(std::string dflt="memory map problem") const;
179  virtual std::string details(bool) const;
180  virtual void print(std::ostream&, bool verbose=true) const;
181  friend std::ostream& operator<<(std::ostream&, const Exception&);
182  public:
184  };
185 
190  struct Inconsistent : public Exception {
191  Inconsistent(const std::string &mesg, const MemoryMap::Ptr &map,
192  const AddressInterval &new_range, const Segment &new_segment,
193  const AddressInterval &old_range, const Segment &old_segment)
194  : Exception(mesg, map),
195  new_range(new_range), old_range(old_range),
196  new_segment(new_segment), old_segment(old_segment) {}
197  virtual ~Inconsistent() throw() {}
198  virtual void print(std::ostream&, bool verbose=true) const;
199  friend std::ostream& operator<<(std::ostream&, const Inconsistent&);
200  AddressInterval new_range, old_range;
201  Segment new_segment, old_segment;
202  };
203 
205  struct NotMapped : public Exception {
206  NotMapped(const std::string &mesg, const MemoryMap::Ptr &map, rose_addr_t va)
207  : Exception(mesg, map), va(va) {}
208  virtual ~NotMapped() throw() {}
209  virtual void print(std::ostream&, bool verbose=true) const;
210  friend std::ostream& operator<<(std::ostream&, const NotMapped&);
211  rose_addr_t va;
212  };
213 
215  struct NoFreeSpace : public Exception {
216  NoFreeSpace(const std::string &mesg, const MemoryMap::Ptr &map, size_t size)
217  : Exception(mesg, map), size(size) {}
218  virtual ~NoFreeSpace() throw() {}
219  virtual void print(std::ostream&, bool verbose=true) const;
220  friend std::ostream& operator<<(std::ostream&, const NoFreeSpace&);
221  size_t size;
222  };
223 
225  struct SyntaxError: public Exception {
226  SyntaxError(const std::string &mesg, const MemoryMap::Ptr &map, const std::string &filename,
227  unsigned linenum, int colnum=-1)
228  : Exception(mesg, map), filename(filename), linenum(linenum), colnum(colnum) {}
229  virtual ~SyntaxError() throw() {}
230  virtual void print(std::ostream&, bool verbose=true) const;
231  friend std::ostream& operator<<(std::ostream&, const SyntaxError&);
232  std::string filename;
233  unsigned linenum;
234  int colnum;
235  };
236 
237 protected:
239  MemoryMap(): endianness_(ByteOrder::ORDER_UNSPECIFIED) {}
240 
241 public:
243  static Ptr instance() {
244  return Ptr(new MemoryMap);
245  }
246 
250  Ptr shallowCopy() {
251  return Ptr(new MemoryMap(*this));
252  }
253 
261  ByteOrder::Endianness byteOrder() const { return endianness_; }
262  void byteOrder(ByteOrder::Endianness order) { endianness_ = order; }
265  // Note that the order of the enum members is for backward compatibility with an older version of insertFile whose third
266  // argument was "bool writable = false" (MAP_RDONLY, but now intended to be MAP_PRIVATE) and when it was true was the same
267  // as MAP_READWRITE.
268  //
277  };
278 
283  size_t insertFile(const std::string &fileName, rose_addr_t va, InsertFileMapMode mode = MAP_PRIVATE,
284  std::string segmentName = "");
285 
361  AddressInterval insertFile(const std::string &locatorString);
362 
364  static std::string insertFileDocumentation();
365 
366 #ifdef BOOST_WINDOWS
367  void insertProcess(int pid, Attach::Boolean attach);
368 #else
369 
370  void insertProcess(pid_t pid, Attach::Boolean attach);
371 #endif
372 
376  void insertProcess(const std::string &locatorString);
377 
379  static std::string insertProcessDocumentation();
380 
382  void eraseZeros(size_t minsize);
383 
394  bool shrinkUnshare();
395 
397  size_t readQuick(void *buf, rose_addr_t startVa, size_t desired) const {
398  return at(startVa).limit(desired).require(READABLE).read((uint8_t*)buf).size();
399  }
400 
413  std::string readString(rose_addr_t startVa, size_t desired, int(*validChar)(int)=NULL, int(*invalidChar)(int)=NULL,
414  unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0, char terminator='\0') const;
415 
421  template<typename U>
422  Sawyer::Optional<U> readUnsigned(rose_addr_t startVa) const {
423  U val = 0;
424  if (at(startVa).limit(sizeof val).read((uint8_t*)&val).size() != sizeof val)
425  return Sawyer::Nothing();
426  ByteOrder::convert((void*)&val, sizeof val, endianness_, ByteOrder::host_order());
427  return val;
428  }
429 
431  SgUnsignedCharList readVector(rose_addr_t startVa, size_t desired, unsigned requiredPerms=READABLE) const;
432 
434  size_t writeQuick(const void *buf, rose_addr_t startVa, size_t desired) {
435  return at(startVa).limit(desired).require(WRITABLE).write((const uint8_t*)buf).size();
436  }
437 
445  Sawyer::Optional<rose_addr_t> findAny(const Extent &limits, const std::vector<uint8_t> &bytesToFind,
446  unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0) const;
447  Sawyer::Optional<rose_addr_t> findAny(const AddressInterval &limits, const std::vector<uint8_t> &bytesToFind,
448  unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0) const;
456  Sawyer::Optional<rose_addr_t> findSequence(const AddressInterval &interval, const std::vector<uint8_t> &sequence) const;
457 
461  void dump(FILE*, const char *prefix="") const;
462  void dump(std::ostream&, std::string prefix="") const;
463  void print(std::ostream &o, std::string prefix="") const { dump(o, prefix); }
481 
483  static std::string segmentTitle(const Segment&);
484 
485  friend std::ostream& operator<<(std::ostream&, const MemoryMap&);
486 };
487 
488 } // namespace
489 } // namespace
490 
491 // Register the types needed for serialization since some of them are derived from polymorphic class templates.
492 #ifdef ROSE_HAVE_BOOST_SERIALIZATION_LIB
494 BOOST_CLASS_EXPORT_KEY(Rose::BinaryAnalysis::MemoryMap::MappedBuffer);
495 BOOST_CLASS_EXPORT_KEY(Rose::BinaryAnalysis::MemoryMap::NullBuffer);
496 BOOST_CLASS_EXPORT_KEY(Rose::BinaryAnalysis::MemoryMap::StaticBuffer);
497 #endif
498 
499 
500 #endif
Exception thrown by find_free() when there's not enough free space left.
Definition: MemoryMap.h:215
int colnum
Optional column number (0-origin; negative if unknown).
Definition: MemoryMap.h:234
T alignDown(T address, T alignment)
Align address upward to boundary.
Definition: MemoryMap.h:36
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:225
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:463
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:270
MemoryMap()
Constructs an empty memory map.
Definition: MemoryMap.h:239
Holds a value or nothing.
Definition: Optional.h:49
MemoryMap::Ptr map
Map that caused the exception if available, null otherwise.
Definition: MemoryMap.h:183
Attach with ptrace, get memory, then detach.
Definition: MemoryMap.h:116
AddressSegment< rose_addr_t, uint8_t > Segment
Type of segments stored by this map.
Definition: AddressMap.h:978
Main namespace for the ROSE library.
Memory mapped file.
Definition: MappedBuffer.h:43
File is mapped with read-only permission.
Definition: MemoryMap.h:275
Allocates memory as needed.
std::string filename
Name of index file where error occurred.
Definition: MemoryMap.h:232
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:243
void byteOrder(ByteOrder::Endianness order)
Property: byte order.
Definition: MemoryMap.h:262
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:273
size_t readQuick(void *buf, rose_addr_t startVa, size_t desired) const
Read data into buffer.
Definition: MemoryMap.h:397
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:205
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:97
unsigned linenum
Line number (1 origin) where error occurred.
Definition: MemoryMap.h:233
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:22
Exception for an inconsistent mapping.
Definition: MemoryMap.h:190
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:113
bool shrinkUnshare()
Shrink buffers and remove sharing.
Represents no value.
Definition: Optional.h:32
ByteOrder::Endianness byteOrder() const
Property: byte order.
Definition: MemoryMap.h:261
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.
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:434
T alignUp(T address, T alignment)
Align address downward to boundary.
Definition: MemoryMap.h:27
Sawyer::Optional< U > readUnsigned(rose_addr_t startVa) const
Read an unsigned value.
Definition: MemoryMap.h:422
Exception for MemoryMap operations.
Definition: MemoryMap.h:174
Assume ptrace is attached and process is stopped.
Definition: MemoryMap.h:115
Ptr shallowCopy()
Create a new copy of the memory map.
Definition: MemoryMap.h:250