ROSE  0.10.7.0
MemoryMap.h
1 #ifndef ROSE_BinaryAnalysis_MemoryMap_H
2 #define ROSE_BinaryAnalysis_MemoryMap_H
3 
4 #include <rosePublicConfig.h>
5 #ifdef ROSE_BUILD_BINARY_ANALYSIS_SUPPORT
6 
7 #include <ByteOrder.h>
8 #include <Combinatorics.h>
9 #include <RoseException.h>
10 
11 #include <Sawyer/Access.h>
12 #include <Sawyer/AddressMap.h>
13 #include <Sawyer/AllocatingBuffer.h>
14 #include <Sawyer/MappedBuffer.h>
15 #include <Sawyer/NullBuffer.h>
16 #include <Sawyer/Optional.h>
17 #include <Sawyer/StaticBuffer.h>
18 
19 #include <boost/config.hpp>
20 #include <boost/utility/enable_if.hpp>
21 #include <boost/serialization/access.hpp>
22 #include <boost/serialization/base_object.hpp>
23 #include <boost/serialization/export.hpp>
24 #include <boost/type_traits/is_integral.hpp>
25 
26 namespace Rose {
27 namespace BinaryAnalysis {
28 
34 template<typename T, typename U>
35 typename boost::enable_if_c<boost::is_integral<T>::value && boost::is_integral<U>::value, T>::type
36 alignUp(T address, U alignment) {
37  ASSERT_require(alignment > 0);
38  T almt = static_cast<T>(alignment);
39  return ((address + almt - 1) / almt) * almt;
40 }
41 
47 template<typename T, typename U>
48 typename boost::enable_if_c<boost::is_integral<T>::value && boost::is_integral<U>::value, T>::type
49 alignDown(T address, U alignment) {
50  ASSERT_require(alignment > 0);
51  T almt = static_cast<T>(alignment);
52  return (address / almt) * almt;
53 }
54 
112 class MemoryMap: public Sawyer::Container::AddressMap<rose_addr_t, uint8_t>, public Sawyer::SharedObject {
113 public:
115  typedef rose_addr_t Address;
116  typedef uint8_t Value;
126 
128  struct Attach { // For consistency with other <Feature>::Boolean types
129  enum Boolean {
130  NO,
132  };
133  };
134 
135 private:
136  ByteOrder::Endianness endianness_;
137 
138 #ifdef ROSE_HAVE_BOOST_SERIALIZATION_LIB
139 private:
140  friend class boost::serialization::access;
141 
142  template<class S>
143  void serialize(S &s, const unsigned /*version*/) {
144  s.template register_type<AllocatingBuffer>();
145  s.template register_type<MappedBuffer>();
146  s.template register_type<NullBuffer>();
147  s.template register_type<StaticBuffer>();
148  s & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Super);
149  s & BOOST_SERIALIZATION_NVP(endianness_);
150  }
151 #endif
152 
153 public:
154 
155  // Whoever pollutes all namespaces with these common word preprocessor symbols is a lunatic!
156 # if defined(READABLE) || defined(WRITABLE) || defined(EXECUTABLE) || defined(IMMUTABLE) || defined(PRIVATE)
157 # ifdef _MSC_VER
158 # pragma message("Undefining common words from the global namespace: READABLE, WRITABLE, EXECUTABLE, IMMUTABLE, PRIVATE")
159 # else
160 # warning "Undefining common words from the global namespace: READABLE, WRITABLE, EXECUTABLE, IMMUTABLE, PRIVATE"
161 # endif
162 # undef READABLE
163 # undef WRITABLE
164 # undef EXECUTABLE
165 # undef IMMUTABLE
166 # undef PRIVATE
167 # endif
168 
169  // Accessibility flags
170  static const unsigned NO_ACCESS = 0;
171  static const unsigned READABLE = Sawyer::Access::READABLE;
172  static const unsigned WRITABLE = Sawyer::Access::WRITABLE;
173  static const unsigned EXECUTABLE = Sawyer::Access::EXECUTABLE;
174  static const unsigned IMMUTABLE = Sawyer::Access::IMMUTABLE;
175  static const unsigned PRIVATE = Sawyer::Access::PRIVATE;
176  static const unsigned INITIALIZED = 0x00000200; // Partitioner2: initialized memory even if writable
177 
178  // Aggregate accessibility flags
179  static const unsigned READ_WRITE = READABLE | WRITABLE;
180  static const unsigned READ_EXECUTE = READABLE | EXECUTABLE;
181  static const unsigned READ_WRITE_EXECUTE = READABLE | WRITABLE | EXECUTABLE;
182 
183  // These bits are reserved for use in ROSE
184  static const unsigned RESERVED_ACCESS_BITS = 0x0000ffff;
185 
186 
187 public:
189  class Exception: public Rose::Exception {
190  public:
191  Exception(const std::string &mesg, const MemoryMap::Ptr map): Rose::Exception(mesg), map(map) {}
192  virtual ~Exception() throw() {}
193  virtual std::string leader(std::string dflt="memory map problem") const;
194  virtual std::string details(bool) const;
195  virtual void print(std::ostream&, bool verbose=true) const;
196  friend std::ostream& operator<<(std::ostream&, const Exception&);
197  public:
199  };
200 
205  struct Inconsistent : public Exception {
206  Inconsistent(const std::string &mesg, const MemoryMap::Ptr &map,
207  const AddressInterval &new_range, const Segment &new_segment,
208  const AddressInterval &old_range, const Segment &old_segment)
209  : Exception(mesg, map),
210  new_range(new_range), old_range(old_range),
211  new_segment(new_segment), old_segment(old_segment) {}
212  virtual ~Inconsistent() throw() {}
213  virtual void print(std::ostream&, bool verbose=true) const;
214  friend std::ostream& operator<<(std::ostream&, const Inconsistent&);
215  AddressInterval new_range, old_range;
216  Segment new_segment, old_segment;
217  };
218 
220  struct NotMapped : public Exception {
221  NotMapped(const std::string &mesg, const MemoryMap::Ptr &map, rose_addr_t va)
222  : Exception(mesg, map), va(va) {}
223  virtual ~NotMapped() throw() {}
224  virtual void print(std::ostream&, bool verbose=true) const;
225  friend std::ostream& operator<<(std::ostream&, const NotMapped&);
226  rose_addr_t va;
227  };
228 
230  struct NoFreeSpace : public Exception {
231  NoFreeSpace(const std::string &mesg, const MemoryMap::Ptr &map, size_t size)
232  : Exception(mesg, map), size(size) {}
233  virtual ~NoFreeSpace() throw() {}
234  virtual void print(std::ostream&, bool verbose=true) const;
235  friend std::ostream& operator<<(std::ostream&, const NoFreeSpace&);
236  size_t size;
237  };
238 
240  struct SyntaxError: public Exception {
241  SyntaxError(const std::string &mesg, const MemoryMap::Ptr &map, const std::string &filename,
242  unsigned linenum, int colnum=-1)
243  : Exception(mesg, map), filename(filename), linenum(linenum), colnum(colnum) {}
244  virtual ~SyntaxError() throw() {}
245  virtual void print(std::ostream&, bool verbose=true) const;
246  friend std::ostream& operator<<(std::ostream&, const SyntaxError&);
247  std::string filename;
248  unsigned linenum;
249  int colnum;
250  };
251 
252 protected:
254  MemoryMap(): endianness_(ByteOrder::ORDER_UNSPECIFIED) {}
255 
256 public:
258  static Ptr instance() {
259  return Ptr(new MemoryMap);
260  }
261 
265  Ptr shallowCopy() {
266  return Ptr(new MemoryMap(*this));
267  }
268 
276  ByteOrder::Endianness byteOrder() const { return endianness_; }
277  void byteOrder(ByteOrder::Endianness order) { endianness_ = order; }
280  // Note that the order of the enum members is for backward compatibility with an older version of insertFile whose third
281  // argument was "bool writable = false" (MAP_RDONLY, but now intended to be MAP_PRIVATE) and when it was true was the same
282  // as MAP_READWRITE.
283  //
292  };
293 
298  size_t insertFile(const std::string &fileName, rose_addr_t va, InsertFileMapMode mode = MAP_PRIVATE,
299  std::string segmentName = "");
300 
376  AddressInterval insertFile(const std::string &locatorString);
377 
379  static std::string insertFileDocumentation();
380 
407  AddressInterval insertData(const std::string &locatorString);
408 
410  static std::string insertDataDocumentation();
411 
412 
413 #ifdef BOOST_WINDOWS
414  void insertProcess(int pid, Attach::Boolean attach);
415 #else
416 
417  void insertProcess(pid_t pid, Attach::Boolean attach);
418 #endif
419 
423  void insertProcess(const std::string &locatorString);
424 
426  static std::string insertProcessDocumentation();
427 
429  void eraseZeros(size_t minsize);
430 
441  bool shrinkUnshare();
442 
444  size_t readQuick(void *buf, rose_addr_t startVa, size_t desired) const {
445  return at(startVa).limit(desired).require(READABLE).read((uint8_t*)buf).size();
446  }
447 
460  std::string readString(rose_addr_t startVa, size_t desired, int(*validChar)(int)=NULL, int(*invalidChar)(int)=NULL,
461  unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0, char terminator='\0') const;
462 
468  template<typename U>
469  Sawyer::Optional<U> readUnsigned(rose_addr_t startVa) const {
470  U val = 0;
471  if (at(startVa).limit(sizeof val).read((uint8_t*)&val).size() != sizeof val)
472  return Sawyer::Nothing();
473  ByteOrder::convert((void*)&val, sizeof val, endianness_, ByteOrder::host_order());
474  return val;
475  }
476 
478  SgUnsignedCharList readVector(rose_addr_t startVa, size_t desired, unsigned requiredPerms=READABLE) const;
479 
481  size_t writeQuick(const void *buf, rose_addr_t startVa, size_t desired) {
482  return at(startVa).limit(desired).require(WRITABLE).write((const uint8_t*)buf).size();
483  }
484 
492  Sawyer::Optional<rose_addr_t> findAny(const Extent &limits, const std::vector<uint8_t> &bytesToFind,
493  unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0) const;
494  Sawyer::Optional<rose_addr_t> findAny(const AddressInterval &limits, const std::vector<uint8_t> &bytesToFind,
495  unsigned requiredPerms=READABLE, unsigned prohibitedPerms=0) const;
503  Sawyer::Optional<rose_addr_t> findSequence(const AddressInterval &interval, const std::vector<uint8_t> &sequence) const;
504 
508  void dump(FILE*, const char *prefix="") const;
509  void dump(std::ostream&, std::string prefix="") const;
510  void print(std::ostream &o, std::string prefix="") const { dump(o, prefix); }
528 
530  static std::string segmentTitle(const Segment&);
531 
532  friend std::ostream& operator<<(std::ostream&, const MemoryMap&);
533 };
534 
535 } // namespace
536 } // namespace
537 
538 // Register the types needed for serialization since some of them are derived from polymorphic class templates.
539 #ifdef ROSE_HAVE_BOOST_SERIALIZATION_LIB
541 BOOST_CLASS_EXPORT_KEY(Rose::BinaryAnalysis::MemoryMap::MappedBuffer);
542 BOOST_CLASS_EXPORT_KEY(Rose::BinaryAnalysis::MemoryMap::NullBuffer);
543 BOOST_CLASS_EXPORT_KEY(Rose::BinaryAnalysis::MemoryMap::StaticBuffer);
544 #endif
545 
546 #endif
547 #endif
Exception thrown by find_free() when there's not enough free space left.
Definition: MemoryMap.h:230
int colnum
Optional column number (0-origin; negative if unknown).
Definition: MemoryMap.h:249
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:240
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:510
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:285
MemoryMap()
Constructs an empty memory map.
Definition: MemoryMap.h:254
Holds a value or nothing.
Definition: Optional.h:49
MemoryMap::Ptr map
Map that caused the exception if available, null otherwise.
Definition: MemoryMap.h:198
Attach with ptrace, get memory, then detach.
Definition: MemoryMap.h:131
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:290
Allocates memory as needed.
std::string filename
Name of index file where error occurred.
Definition: MemoryMap.h:247
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:258
void byteOrder(ByteOrder::Endianness order)
Property: byte order.
Definition: MemoryMap.h:277
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:288
size_t readQuick(void *buf, rose_addr_t startVa, size_t desired) const
Read data into buffer.
Definition: MemoryMap.h:444
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:220
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:112
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:49
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:36
unsigned linenum
Line number (1 origin) where error occurred.
Definition: MemoryMap.h:248
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:205
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:128
bool shrinkUnshare()
Shrink buffers and remove sharing.
Represents no value.
Definition: Optional.h:32
ByteOrder::Endianness byteOrder() const
Property: byte order.
Definition: MemoryMap.h:276
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:481
Sawyer::Optional< U > readUnsigned(rose_addr_t startVa) const
Read an unsigned value.
Definition: MemoryMap.h:469
Exception for MemoryMap operations.
Definition: MemoryMap.h:189
Assume ptrace is attached and process is stopped.
Definition: MemoryMap.h:130
Ptr shallowCopy()
Create a new copy of the memory map.
Definition: MemoryMap.h:265