1 : // Copyright 2012 Google Inc. All Rights Reserved.
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // http://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 : //
15 : // A block graph is a an abstract graph of blocks, each of which has an ID,
16 : // a type, a size and a few other properties. Each block represents either code
17 : // or data, and blocks can reference one another through references of various
18 : // types.
19 : //
20 : // The BlockGraph also stores minimum knowledge of sections (names and
21 : // characteristics), and each block belongs to at most one section. In this
22 : // sense, a BlockGraph acts as top-level division of blocks.
23 :
24 : #ifndef SYZYGY_BLOCK_GRAPH_BLOCK_GRAPH_H_
25 : #define SYZYGY_BLOCK_GRAPH_BLOCK_GRAPH_H_
26 :
27 : #include <hash_map>
28 : #include <map>
29 : #include <set>
30 : #include <string>
31 : #include <vector>
32 :
33 : #include "base/basictypes.h"
34 : #include "base/string_piece.h"
35 : #include "syzygy/common/align.h"
36 : #include "syzygy/core/address.h"
37 : #include "syzygy/core/address_space.h"
38 :
39 : namespace block_graph {
40 :
41 : // Forward declaration.
42 : class BlockGraphSerializer;
43 :
44 : // The invalid address can never occur in an graph, it's used as default
45 : // value for block addresses.
46 : extern const core::RelativeAddress kInvalidAddress;
47 :
48 : #define BLOCK_ATTRIBUTE_ENUM(F) \
49 : /* Set for functions declared non-returning. */ \
50 : F(NON_RETURN_FUNCTION) \
51 : /* Set for blocks that are inferred by the decomposer. */ \
52 : F(GAP_BLOCK) \
53 : /* Set for blocks that are parsed by the PEFileParser. These */ \
54 : /* blocks are unmovable, indivisible, etc, and have to be treated */ \
55 : /* specially. */ \
56 : F(PE_PARSED) \
57 : /* Set for blocks that are created from section contribution */ \
58 : /* information. */ \
59 : F(SECTION_CONTRIB) \
60 : /* This is used to indicate that a block consists purely of padding */ \
61 : /* data. */ \
62 : F(PADDING_BLOCK) \
63 : /* Indicates blocks that contain inline assembly. */ \
64 : F(HAS_INLINE_ASSEMBLY) \
65 : /* Indicates that the block was built by a compiler whose precise */ \
66 : /* behaviour and semantics we are unfamiliar with. */ \
67 : F(BUILT_BY_UNSUPPORTED_COMPILER) \
68 : /* Indicates that the block has been built by the Syzygy toolchain, and */ \
69 : /* thus is inherently safe for basic-block decomposition without having */ \
70 : /* to perform the myriad of safety checks we do otherwise. */ \
71 : F(BUILT_BY_SYZYGY) \
72 : /* This is set for blocks whose initial disassembly was incomplete. */ \
73 : /* This is not necessarily an error, as we see have seen blocks with */ \
74 : /* unreachable code, even in release mode. */ \
75 : F(INCOMPLETE_DISASSEMBLY) \
76 : /* This is set for blocks whose disassembly was unable to finish due to */ \
77 : /* an error. This block has violated assumptions that we make or */ \
78 : /* conventions that we have observed the compiler to use. It is not safe */\
79 : /* for basic block disassembly. */ \
80 : F(ERRORED_DISASSEMBLY) \
81 : /* This is set for functions that have exception handling enabled. */ \
82 : /* Without delving far deeper into the specifics, it is unsafe to basic */ \
83 : /* block decompose these blocks. */ \
84 : F(HAS_EXCEPTION_HANDLING) \
85 : /* This is set for blocks whose disassembly went off the end of the */ \
86 : /* block, or into data. These blocks have control flow that we are not */ \
87 : /* aware of, or are otherwise malformed. */ \
88 : F(DISASSEMBLED_PAST_END) \
89 : /* This is set for blocks that have a thunk symbol pointing to them. */ \
90 : /* Typically thunk blocks are compiler or linker-generated, such as */ \
91 : /* e.g. import thunks, delay load import thunks, etc. */ \
92 : F(THUNK) \
93 : /* This is set for blocks that have been parsed as COFF groups. The */ \
94 : /* contents of these blocks are semantically indivisible. */ \
95 : F(COFF_GROUP) \
96 : /* This always needs to be set to the next available attribute bit. */ \
97 : F(BLOCK_ATTRIBUTES_MAX)
98 :
99 : // The BlockGraph is a top-level container for Blocks.
100 : class BlockGraph {
101 : public:
102 : typedef core::RelativeAddress RelativeAddress;
103 :
104 : typedef size_t SectionId;
105 : typedef size_t BlockId;
106 : typedef size_t Size;
107 : typedef ptrdiff_t Offset;
108 : typedef uint32 BlockAttributes;
109 : typedef uint32 LabelAttributes;
110 :
111 : // The BlockGraph maintains a list of sections, and each block belongs
112 : // to one of them. This is the set of information we keep regarding them.
113 : struct Section;
114 : // The section map contains all sections, indexed by id.
115 : typedef std::map<SectionId, Section> SectionMap;
116 :
117 : static const SectionId kInvalidSectionId;
118 :
119 : // Assign distinct bit IDs to each attribute constant.
120 : enum BlockAttributeIdEnum {
121 : #define DECLARE_ENUM_BIT(name) name##_BIT,
122 : BLOCK_ATTRIBUTE_ENUM(DECLARE_ENUM_BIT)
123 : #undef DECLARE_ENUM_BIT
124 : };
125 :
126 : enum BlockAttributeEnum {
127 : #define DECLARE_ENUM(name) name = (1 << name##_BIT),
128 : BLOCK_ATTRIBUTE_ENUM(DECLARE_ENUM)
129 : #undef DECLARE_ENUM
130 : };
131 :
132 : // Returns a string containing the names of the supplied attributes.
133 : static std::string BlockAttributesToString(BlockAttributes attrs);
134 :
135 : enum BlockType {
136 : CODE_BLOCK,
137 : DATA_BLOCK,
138 :
139 : // NOTE: This must always be last, and kBlockType must be kept in sync
140 : // with this enum.
141 : BLOCK_TYPE_MAX
142 : };
143 :
144 : static const char* BlockTypeToString(BlockType type);
145 :
146 : // Label attributes. Attributes of the form _END_LABEL type actually
147 : // point to the first byte past the range they delineate. To make the
148 : // semantics of moving labels easier, we shift these labels left by one and
149 : // make them follow the last byte of the delineated range.
150 : enum LabelAttributesEnum {
151 : // The label points to an entry-point in a code block.
152 : CODE_LABEL = (1 << 0),
153 :
154 : // Mark the start and end of the debuggable portion of a code block.
155 : DEBUG_START_LABEL = (1 << 1),
156 : DEBUG_END_LABEL = (1 << 2),
157 :
158 : // Mark the start and end of an embedded scope in a code block.
159 : SCOPE_START_LABEL = (1 << 3),
160 : SCOPE_END_LABEL = (1 << 4),
161 :
162 : // Marks the location of a (virtual table?) call.
163 : CALL_SITE_LABEL = (1 << 5),
164 :
165 : // The label points to the start of a jump table. The length is inferred
166 : // by the location of the next label, or the end of the block. This will
167 : // also have DATA_LABEL set.
168 : JUMP_TABLE_LABEL = (1 << 6),
169 : // The label points to the start of a case table. The length is inferred
170 : // by the location of the next label, or the end of the block. This will
171 : // also have DATA_LABEL set.
172 : CASE_TABLE_LABEL = (1 << 7),
173 : // The label originated from a data symbol. The length is inferred by the
174 : // location of the next label, or the end of the block. The type of data
175 : // is unknown.
176 : DATA_LABEL = (1 << 8),
177 :
178 : // Used to mark a label that was derived from a public symbol. These are
179 : // usually actually pointing to code and global data symbols, but we can't
180 : // always tell (there may be public symbols pointing to data in a code
181 : // block).
182 : PUBLIC_SYMBOL_LABEL = (1 << 9),
183 :
184 : // This always needs to be the most significant bit.
185 : LABEL_ATTRIBUTES_MAX = (1 << 10),
186 : };
187 :
188 : static std::string LabelAttributesToString(LabelAttributes label_attributes);
189 :
190 : enum ReferenceType {
191 : PC_RELATIVE_REF,
192 : ABSOLUTE_REF,
193 : RELATIVE_REF,
194 : FILE_OFFSET_REF,
195 : // Must be last!
196 : REFERENCE_TYPE_MAX,
197 : };
198 :
199 : // Forward declarations.
200 : class AddressSpace;
201 : class Block;
202 : class Label;
203 : class Reference;
204 :
205 : // The block map contains all blocks, indexed by id.
206 : typedef std::map<BlockId, Block> BlockMap;
207 :
208 : BlockGraph();
209 : ~BlockGraph();
210 :
211 : // Adds a section with the given name.
212 : //
213 : // @param name The section name.
214 : // @param characteristics The section characteristics.
215 : // @returns the newly created section.
216 : Section* AddSection(const base::StringPiece& name, uint32 characteristics);
217 :
218 : // Finds a section with the given name, returning NULL if no such section
219 : // exists.
220 : //
221 : // @param name The section name.
222 : // @returns the section if one is found, NULL otherwise.
223 : Section* FindSection(const base::StringPiece& name);
224 :
225 : // Find or adds section with the given name.
226 : //
227 : // If a section with the given name already exists, updates its
228 : // characteristics and returns it. Otherwise, creates a new section and
229 : // returns it. If multiple sections exist with the given name, the first
230 : // one encountered is returned.
231 : //
232 : // TODO(chrisha): The semantics of this function are a little odd. It would
233 : // make more sense for it to return only if a section with matching name
234 : // AND characteristics is found, otherwise to create a new one.
235 : //
236 : // @param name The section name.
237 : // @param characteristics The section characteristics.
238 : // @returns the new or found section.
239 : Section* FindOrAddSection(const base::StringPiece& name,
240 : uint32 characteristics);
241 :
242 : // Removes the given section from the BlockGraph.
243 : //
244 : // The section must belong to this block graph. Be aware that this can leave
245 : // Blocks with dangling section_ids.
246 : //
247 : // @param section The section to remove.
248 : // @returns true on success, false otherwise.
249 : bool RemoveSection(Section* section);
250 :
251 : // Removes the section with the given id from the BlockGraph.
252 : //
253 : // @param section The id of the section to remove.
254 : // @returns true on success, false otherwise.
255 : bool RemoveSectionById(SectionId id);
256 :
257 : // Add @p block of type @p type and @p size and
258 : // return the new block.
259 : // @returns the new block.
260 : Block* AddBlock(BlockType type, Size size, const base::StringPiece& name);
261 :
262 : // Deletes the given block from the BlockGraph. The block must belong to this
263 : // block graph, and have no references or referrers. Returns true on success,
264 : // false otherwise. On failure, the BlockGraph has not been changed.
265 : bool RemoveBlock(Block* block);
266 :
267 : // Deletes the block with the given @p id from the block graph. The block id
268 : // must be valid, and the block must have no references or referrers. Returns
269 : // true on success, false otherwise. On failure, the BlockGraph has not been
270 : // changed.
271 : bool RemoveBlockById(BlockId id);
272 :
273 : // Accessors.
274 E : const SectionMap& sections() const { return sections_; }
275 E : SectionMap& sections_mutable() { return sections_; }
276 E : const BlockMap& blocks() const { return blocks_; }
277 E : BlockMap& blocks_mutable() { return blocks_; }
278 :
279 : // @{
280 : // Retrieve the section with the given id.
281 : //
282 : // @param id The id of the section to retrieve.
283 : // @returns the section in question or NULL if no such section.
284 : Section* GetSectionById(SectionId id);
285 : const Section* GetSectionById(SectionId id) const;
286 : // @}
287 :
288 : // @{
289 : // Retrieve the block with id.
290 : // @returns the block in question or NULL if no such block.
291 : Block* GetBlockById(BlockId id);
292 : const Block* GetBlockById(BlockId id) const;
293 : // @}
294 :
295 : private:
296 : // Give BlockGraphSerializer access to our innards for serialization.
297 : friend BlockGraphSerializer;
298 :
299 : // Removes a block by the iterator to it. The iterator must be valid.
300 : bool RemoveBlockByIterator(BlockMap::iterator it);
301 :
302 : // All sections we contain.
303 : SectionMap sections_;
304 :
305 : // Our section ID allocator.
306 : SectionId next_section_id_;
307 :
308 : // All blocks we contain.
309 : BlockMap blocks_;
310 :
311 : // Our block ID allocator.
312 : BlockId next_block_id_;
313 : };
314 :
315 : // The BlockGraph maintains a list of sections, and each block belongs
316 : // to one of them. This is the set of information we keep regarding them.
317 : struct BlockGraph::Section {
318 : // Default constructor. Required for serialization.
319 E : Section() : id_(kInvalidSectionId), characteristics_(0) {
320 E : }
321 :
322 : // Full constructor.
323 : //
324 : // @param id The section id. This must not be kInvalidSectionId.
325 : // @param name The name of the section. Must not be empty or NULL.
326 : // @param characteristics The characteristics of the section.
327 E : Section(SectionId id, const base::StringPiece& name, uint32 characteristics)
328 : : id_(id), name_(), characteristics_(characteristics) {
329 E : DCHECK_NE(kInvalidSectionId, id);
330 E : DCHECK(name != NULL);
331 E : name.CopyToString(&name_);
332 E : DCHECK(!name_.empty());
333 E : }
334 :
335 : // Get the id of this section.
336 : //
337 : // @returns the id of the section.
338 E : SectionId id() const { return id_; }
339 :
340 : // Get the name of this section.
341 : //
342 : // @returns the section name.
343 E : const std::string& name() const { return name_; }
344 :
345 : // Sets the name for this section.
346 : //
347 : // @param name The name of the section. If NULL or empty, this will fail.
348 : // @returns true if the name is set, false otherwise.
349 : bool set_name(const base::StringPiece& name);
350 :
351 : // Get the characteristics of this section.
352 : //
353 : // @returns the section characteristics.
354 E : uint32 characteristics() const { return characteristics_; }
355 :
356 : // Sets the characteristics for this section.
357 : //
358 : // @param characteristics The new characteristics to set.
359 E : void set_characteristics(uint32 characteristics) {
360 E : characteristics_ = characteristics;
361 E : }
362 :
363 : // Sets a one or more additional characteristics for this section.
364 : //
365 : // @param characteristic The new characteristic(s) to set for this section.
366 E : void set_characteristic(uint32 characteristic) {
367 E : characteristics_ |= characteristic;
368 E : }
369 :
370 : // Clears one or more characteristics for this section.
371 : //
372 : // @param characteristic The characteristic(s) to clear for this section.
373 E : void clear_characteristic(uint32 characteristic) {
374 E : characteristics_ &= ~characteristic;
375 E : }
376 :
377 : // @name Serialization functions.
378 : // @{
379 : bool Save(core::OutArchive* out_archive) const;
380 : bool Load(core::InArchive* in_archive);
381 : // @}
382 :
383 : // A simple comparison operator for serialization tests.
384 E : bool operator==(const Section& other) const {
385 : return id_ == other.id_ && name_ == other.name_ &&
386 E : characteristics_ == other.characteristics_;
387 E : }
388 :
389 : // A not-equal comparison operator.
390 E : bool operator!=(const Section& other) const {
391 E : return !operator==(other);
392 E : }
393 :
394 : private:
395 : // The id of the section. This has no particular meaning other than as a way
396 : // to identify sections uniquely.
397 : SectionId id_;
398 : // The name of the section. This will be truncated to a max of 8 characters
399 : // on output.
400 : std::string name_;
401 : // The section characteristics, a bitmask of IMAGE_SCN_* values.
402 : uint32 characteristics_;
403 : };
404 :
405 : // A label denotes the beginning (or end) of a sub-region within a (code)
406 : // block. In particular, a code label represents an instruction boundary
407 : // at which disassembly can begin and a data label represents the beginning
408 : // of embedded data.
409 : class BlockGraph::Label {
410 : public:
411 : // Default constructor.
412 E : Label() : attributes_(0) {
413 E : }
414 :
415 : // Full constructor.
416 E : Label(const base::StringPiece& name, LabelAttributes attributes)
417 : : name_(name.begin(), name.end()), attributes_(attributes) {
418 E : }
419 :
420 : // Copy construction.
421 E : Label(const Label& other)
422 : : name_(other.name_), attributes_(other.attributes_) {
423 E : }
424 :
425 : // @name Accessors.
426 : // @{
427 E : const std::string& name() const { return name_; }
428 : // @}
429 :
430 : // A helper function for logging and debugging.
431 : std::string ToString() const;
432 :
433 : // Equality comparator for unittesting.
434 E : bool operator==(const Label& other) const {
435 E : return name_ == other.name_ && attributes_ == other.attributes_;
436 E : }
437 :
438 : // The label attributes are a bitmask. You can set them wholesale,
439 : // or set and clear them individually by bitmasking.
440 E : LabelAttributes attributes() const { return attributes_; }
441 E : void set_attributes(LabelAttributes attributes) { attributes_ = attributes; }
442 :
443 : // Set or clear one or more attributes.
444 E : void set_attribute(LabelAttributes attribute) { attributes_ |= attribute; }
445 E : void clear_attribute(LabelAttributes attribute) { attributes_ &= ~attribute; }
446 :
447 : // Determines if all or any of the given attributes are set.
448 E : bool has_attributes(LabelAttributes attributes) const {
449 E : return (attributes_ & attributes) == attributes;
450 E : }
451 E : bool has_any_attributes(LabelAttributes attributes) const {
452 E : return (attributes_ & attributes) != 0;
453 E : }
454 :
455 : // @returns true if this label is valid, false otherwise.
456 : bool IsValid() const;
457 :
458 : // Tests a set of label attributes for validity.
459 : // @param attributes the attributes to test.
460 : // @returns true if the provided attributes are valid, false otherwise.
461 : static bool AreValidAttributes(LabelAttributes attributes);
462 :
463 : private:
464 : // The name by which this label is known.
465 : std::string name_;
466 :
467 : // The disposition of the bytes found at this label.
468 : LabelAttributes attributes_;
469 : };
470 :
471 : // A block represents a block of either code or data.
472 : //
473 : // Since blocks may be split and up and glued together in arbitrary ways, each
474 : // block maintains an address-space over its data, associating ranges of block
475 : // data to ranges of bytes in the original image. This effectively encodes OMAP
476 : // data, allowing the PDB file to be updated.
477 : //
478 : // Each block also stores references to other blocks in the graph, their
479 : // relative location within the block and their type and size.
480 : //
481 : // Each block has a set of attributes, including a size, a name and a
482 : // "current" address. Most of those attributes are mutable, and are set in the
483 : // process of creating and manipulating images and graph address spaces.
484 : class BlockGraph::Block {
485 : public:
486 : // Set of the blocks that have a reference to this block.
487 : // This is keyed on block and source offset (not destination offset),
488 : // to allow one to easily locate and remove the backreferences on change or
489 : // deletion.
490 : typedef std::pair<Block*, Offset> Referrer;
491 : typedef std::set<Referrer> ReferrerSet;
492 :
493 : // Map of references that this block makes to other blocks.
494 : typedef std::map<Offset, Reference> ReferenceMap;
495 :
496 : // Represents a range of data in this block.
497 : typedef core::AddressRange<Offset, Size> DataRange;
498 :
499 : // Represents a range of data in the original image.
500 : typedef core::AddressRange<RelativeAddress, Size> SourceRange;
501 :
502 : // A map between bytes in this block and bytes in the original image.
503 : typedef core::AddressRangeMap<DataRange, SourceRange> SourceRanges;
504 :
505 : // Typed labels associated with various offsets in the block. Some of these
506 : // labels (of type CODE_LABEL) represent code start points for disassembly
507 : // while others (of type DATA_LABEL) represent the start of embedded data
508 : // within the block. Note that, while possible, it is NOT guaranteed that
509 : // all basic blocks are marked with a label. Basic block decomposition should
510 : // disassemble from the code labels to discover all basic blocks.
511 : typedef std::map<Offset, Label> LabelMap;
512 :
513 : // Blocks need to be default constructible for serialization.
514 : Block();
515 :
516 : Block(BlockId id,
517 : BlockType type,
518 : Size size,
519 : const base::StringPiece& name);
520 : ~Block();
521 :
522 : // Accessors.
523 E : BlockId id() const { return id_; }
524 E : BlockType type() const { return type_; }
525 E : void set_type(BlockType type) { type_ = type; }
526 :
527 E : Size size() const { return size_; }
528 :
529 : // Set the total size of the block. Note that allocated data_size_ must
530 : // always be less than or equal to the total size.
531 E : void set_size(Size size) {
532 E : DCHECK_LE(data_size_, size);
533 E : size_ = size;
534 E : }
535 :
536 E : const std::string& name() const { return name_; }
537 E : void set_name(const base::StringPiece& name) { name.CopyToString(&name_); }
538 :
539 E : Size alignment() const { return alignment_; }
540 E : void set_alignment(Size alignment) {
541 : // Ensure that alignment is a non-zero power of two.
542 E : DCHECK(common::IsPowerOfTwo(alignment));
543 E : alignment_ = alignment;
544 E : }
545 :
546 : // The address of the block is set any time the block is assigned
547 : // an address in an address space.
548 E : RelativeAddress addr() const { return addr_; }
549 E : void set_addr(RelativeAddress addr) { addr_ = addr; }
550 :
551 : // The section ID for the block. These IDs are wrt to the SectionMap in the
552 : // parent BlockGraph.
553 E : SectionId section() const { return section_; }
554 E : void set_section(SectionId section) { section_ = section; }
555 :
556 : // The block attributes are a bitmask. You can set them wholesale,
557 : // or set and clear them individually by bitmasking.
558 E : BlockAttributes attributes() const { return attributes_; }
559 E : void set_attributes(BlockAttributes attributes) { attributes_ = attributes; }
560 :
561 : // Set or clear one or more attributes.
562 E : void set_attribute(BlockAttributes attribute) { attributes_ |= attribute; }
563 E : void clear_attribute(BlockAttributes attribute) {
564 E : attributes_ &= ~attribute;
565 E : }
566 :
567 : // This is true iff data_ is in the ownership of the block.
568 : // Iff true, the block will delete [] data_ on destruction or when
569 : // data is overwritten.
570 E : bool owns_data() const { return owns_data_; }
571 :
572 : // Makes room for the given amount of data at the given offset. This is
573 : // special in that it will patch up any labels, source ranges and referrers
574 : // that land beyond the newly created data, shifting them to the right by
575 : // @p size. If the data for this block is actually allocated it will also
576 : // patch up the allocated data by zeroing the newly allocate range of data,
577 : // and shifting the tail by @p size. If the new data is strictly implicit
578 : // (offset > data_size), then the allocated data is not affected in any way
579 : // unless @p always_allocate_data is true.
580 : //
581 : // @param offset the offset at which to insert the new data.
582 : // @param size the size of the new data to be inserted.
583 : // @param always_allocate_data if true, then data_size will be grown if
584 : // necessary to ensure that the newly created data can be written.
585 : // @pre 0 <= offset <= size()
586 : void InsertData(Offset offset, Size size, bool always_allocate_data);
587 :
588 : // Removes the data in the given range. This will refuse to remove labels,
589 : // references and referrers that land in the range, and will fail if any
590 : // exist. It will also shift any labels, references and referrers that land
591 : // beyond the end of the removed range. Source ranges will also be fixed. If
592 : // the removed range lies within the initialized data then the data will also
593 : // be truncated/shifted as necessary.
594 : //
595 : // @param offset the offset at which to remove data.
596 : // @param size the size of the data to remove, in bytes.
597 : // @returns true on success, false otherwise.
598 : // @pre 0 <= offset <= size
599 : bool RemoveData(Offset offset, Size size);
600 :
601 : // Performs an inline resize of data in a BlockGraph. If the data is shrinking
602 : // this equates to a RemoveData operation. If it is growing it equates to an
603 : // InsertData operation.
604 : //
605 : // @param offset the offset of the data to resize.
606 : // @param current_size the current size of the data to resize.
607 : // @param new_size the desired size of the data.
608 : // @param always_allocate_data if true, then data_size will be grown if
609 : // necessary to ensure that the resized data can be written.
610 : // @returns true on success, false otherwise.
611 : // @pre 0 <= offset <= size
612 : bool InsertOrRemoveData(Offset offset, Size current_size, Size new_size,
613 : bool always_allocate_data);
614 :
615 : // Set the data the block refers to.
616 : // @param data NULL or the data this block refers to.
617 : // The underlying data must outlive this block.
618 : // @param data_size the size of data, or zero if data == NULL.
619 : // @pre data_size <= size().
620 : void SetData(const uint8* data, size_t data_size);
621 :
622 : // Allocates and returns a new data buffer of the given size. The returned
623 : // data will have been initialized to zero.
624 : // @pre data_size <= size().
625 : uint8* AllocateData(size_t data_size);
626 :
627 : // Makes a copy of data, returns a pointer to the copy.
628 : // @pre data_size <= size().
629 : uint8* CopyData(size_t data_size, const void* data);
630 :
631 : // Resizes data to new_size by truncating or zero-extending the current data.
632 : // @pre new_size <= size().
633 : const uint8* ResizeData(size_t new_size);
634 :
635 : // Returns a mutable copy of the block's data. If the block doesn't own
636 : // the data on entry, it'll be copied and the copy returned to the caller.
637 : uint8* GetMutableData();
638 :
639 : // The data bytes the block refers to.
640 E : const uint8* data() const { return data_; }
641 :
642 : // The data size may be smaller than the block size (see size()),
643 : // when the block e.g. refers to data that's all or part
644 : // zero-initialized by the linker/loader.
645 E : size_t data_size() const { return data_size_; }
646 :
647 E : const ReferenceMap& references() const { return references_; }
648 E : const ReferrerSet& referrers() const { return referrers_; }
649 E : const SourceRanges& source_ranges() const { return source_ranges_; }
650 E : SourceRanges& source_ranges() { return source_ranges_; }
651 E : const LabelMap& labels() const { return labels_; }
652 :
653 : // Returns true if there are any other blocks holding a reference to this one.
654 : bool HasExternalReferrers() const;
655 :
656 : // Set the reference at @p offset to @p ref.
657 : // If there's a pre-existing reference at @p offset, this overrides it.
658 : // @param offset offset of the reference into this block.
659 : // @param ref the reference to add.
660 : // @returns true iff this inserts a new reference.
661 : bool SetReference(Offset offset, const Reference& ref);
662 :
663 : // Retrieve the reference at @p offset if one exists.
664 : // @param reference on success returns the reference @p offset.
665 : // @returns true iff there was a reference at @p offset.
666 : bool GetReference(Offset offset, Reference* reference) const;
667 :
668 : // Remove the reference at @p offset.
669 : // @returns true iff there was a reference at @p offset.
670 : bool RemoveReference(Offset offset);
671 :
672 : // Remove all references from this block. This is handy when removing a block
673 : // from the block graph.
674 : bool RemoveAllReferences();
675 :
676 : // Set a label to @p offset.
677 : // A label in code marks the location of the start of an instruction -
678 : // e.g. a location where disassembly can usefully commence. Labels
679 : // appear to be inserted by the VS tool chain where e.g. a switch
680 : // statement is implemented with a jump table, to note the location
681 : // of the jump destinations.
682 : // @param offset the offset of the label to set.
683 : // @param name the name of the label.
684 : // @param attributes the attributes of the label.
685 : // @returns true iff a new label is inserted.
686 : // @note that only one label can exist at each offset, and the first
687 : // label set at any offset will stay there.
688 : // @{
689 : bool SetLabel(Offset offset, const Label& label);
690 : bool SetLabel(Offset offset,
691 : const base::StringPiece& name,
692 E : LabelAttributes attributes) {
693 E : return SetLabel(offset, Label(name, attributes));
694 E : }
695 : // @}
696 :
697 : // Gets the label at the given @p offset.
698 : // @param offset the offset of the label to get.
699 : // @param label the string to receive the label.
700 : // @return true if the label exists, false otherwise.
701 : bool GetLabel(Offset offset, Label* label) const;
702 :
703 : // Removes the label at the given @p offset.
704 : // @param offset the offset of the label to remove.
705 : // @return true if the label existed and was removed, false it it did not
706 : // exist.
707 : bool RemoveLabel(Offset offset);
708 :
709 : // Returns true iff the block has a label at @p offset.
710 : // @param offset the offset of the label to search for.
711 : bool HasLabel(Offset offset);
712 :
713 : // Change all references to this block to refer to @p new_block instead,
714 : // while offsetting each reference by @p offset.
715 : // @note this fails if any of the transferred references end up with offsets
716 : // less than zero, or greater than new_block->size().
717 : // @returns true iff all references were transferred successfully.
718 : bool TransferReferrers(Offset offset, Block* new_block);
719 :
720 : // Returns true if this block contains the given range of bytes.
721 : bool Contains(RelativeAddress address, size_t size) const;
722 :
723 : protected:
724 : // Give BlockGraph access to our innards for serialization.
725 : friend class BlockGraph;
726 : // Give BlockGraphSerializer access to our innards for serialization.
727 : friend class BlockGraphSerializer;
728 :
729 : // Allocates and returns a new data buffer of the given size. The returned
730 : // data buffer will not have been initialized in any way.
731 : uint8* AllocateRawData(size_t size);
732 :
733 : BlockId id_;
734 : BlockType type_;
735 : Size size_;
736 : Size alignment_;
737 : std::string name_;
738 : RelativeAddress addr_;
739 :
740 : SectionId section_;
741 : BlockAttributes attributes_;
742 :
743 : ReferenceMap references_;
744 : ReferrerSet referrers_;
745 : SourceRanges source_ranges_;
746 : LabelMap labels_;
747 :
748 : // True iff data_ is ours to deallocate with delete [].
749 : // If this is false, data_ must be guaranteed to outlive the block.
750 : bool owns_data_;
751 : // A pointer to the code or data we represent.
752 : const uint8* data_;
753 : // Size of the above.
754 : size_t data_size_;
755 : };
756 :
757 : // A graph address space endows a graph with a non-overlapping ordering
758 : // on blocks, where each block occupies zero or one address ranges in the
759 : // address space. No two blocks may overlap in an address space.
760 : class BlockGraph::AddressSpace {
761 : public:
762 : typedef core::AddressSpace<RelativeAddress, BlockGraph::Size, Block*>
763 : AddressSpaceImpl;
764 : typedef AddressSpaceImpl::Range Range;
765 : typedef AddressSpaceImpl::RangeMap RangeMap;
766 : typedef AddressSpaceImpl::RangeMapIter RangeMapIter;
767 : typedef AddressSpaceImpl::RangeMapConstIter RangeMapConstIter;
768 : typedef AddressSpaceImpl::RangeMapIterPair RangeMapIterPair;
769 : typedef AddressSpaceImpl::RangeMapConstIterPair RangeMapConstIterPair;
770 :
771 : // Constructs a new empty address space.
772 : // @p start to @p start + @p size on @p graph.
773 : explicit AddressSpace(BlockGraph* graph);
774 :
775 : // Add a block of type @p type and @p size at @p address to our associated
776 : // graph, and return the new block.
777 : // @returns the new block, or NULL if the new block would overlap
778 : // an existing block.
779 : Block* AddBlock(BlockType type,
780 : RelativeAddress addr,
781 : Size size,
782 : const base::StringPiece& name);
783 :
784 : // Merges all blocks that intersect @p range into a single block.
785 : // Moves labels and references from the intersecting blocks to the
786 : // merged block, and changes referring blocks to refer to the new,
787 : // merged block. Removes the original blocks from the BlockGraph.
788 : // @returns the new, merged block if there was at least one intersecting
789 : // block in @p range, or NULL otherwise.
790 : Block* MergeIntersectingBlocks(const Range& range);
791 :
792 : // Insert existing block @p block at @p address.
793 : // @returns true on success, or false if the @p block would overlap
794 : // an existing block.
795 : bool InsertBlock(RelativeAddress addr, Block* block);
796 :
797 : // Returns a pointer to the block containing address, or NULL
798 : // if no block contains address.
799 : Block* GetBlockByAddress(RelativeAddress addr) const;
800 :
801 : // Returns a pointer to the block containing the address range
802 : // [address, address + size), or NULL if no block contains that
803 : // range.
804 : Block* GetContainingBlock(RelativeAddress addr, Size size) const;
805 :
806 : // Finds the first block, if any that intersects
807 : // [@p address, @p address + @p size).
808 : Block* GetFirstIntersectingBlock(RelativeAddress address, Size size);
809 :
810 : // Check whether the address space contains @p block.
811 : // @param block the block in question.
812 : // @returns true if the block is in the address space, false otherwise.
813 : bool ContainsBlock(const Block* block);
814 :
815 : // Locates all blocks that intersect [@p address, @p address + @p size).
816 : // @returns a pair of iterators that iterate over the found blocks.
817 : RangeMapConstIterPair GetIntersectingBlocks(RelativeAddress address,
818 : Size size) const;
819 : RangeMapIterPair GetIntersectingBlocks(RelativeAddress address, Size size);
820 :
821 : // Retrieve the address off @p block.
822 : // @param block the block in question.
823 : // @param addr on success, returns the address of @p block in this
824 : // address space.
825 : // @returns true on success, false if @p block is not in this
826 : // address space.
827 : bool GetAddressOf(const Block* block, RelativeAddress* addr) const;
828 :
829 : // Accessor.
830 E : BlockGraph* graph() { return graph_; }
831 E : const BlockGraph* graph() const { return graph_; }
832 :
833 E : RangeMapConstIter begin() const {
834 E : return address_space_.ranges().begin();
835 E : }
836 :
837 E : RangeMapConstIter end() const {
838 E : return address_space_.ranges().end();
839 E : }
840 :
841 E : size_t size() const {
842 E : return address_space_.ranges().size();
843 E : }
844 :
845 E : const AddressSpaceImpl& address_space_impl() const {
846 E : return address_space_;
847 E : }
848 :
849 : private:
850 : bool InsertImpl(RelativeAddress addr, Block* block);
851 :
852 : typedef stdext::hash_map<const Block*, RelativeAddress> BlockAddressMap;
853 :
854 : AddressSpaceImpl address_space_;
855 : BlockAddressMap block_addresses_;
856 : BlockGraph* graph_;
857 : };
858 :
859 : // Represents a reference from one block to another. References may be offset.
860 : // That is, they may refer to an object at a given location, but actually point
861 : // to a location that is some fixed distance away from that object. This allows,
862 : // for example, non-zero based indexing into a table. The object that is
863 : // intended to be dereferenced is called the 'base' of the offset.
864 : //
865 : // BlockGraph references are from a location (offset) in one block, to some
866 : // location in another block. The referenced block itself plays the role of the
867 : // 'base' of the reference, with the offset of the reference being stored as
868 : // an integer from the beginning of the block. However, basic block
869 : // decomposition requires breaking the block into smaller pieces and thus we
870 : // need to carry around an explicit base value, indicating which byte in the
871 : // block is intended to be referenced.
872 : //
873 : // A direct reference to a location will have the same value for 'base' and
874 : // 'offset'.
875 : //
876 : // Here is an example:
877 : //
878 : // /----------\
879 : // +---------------------------+
880 : // O | B | <--- Referenced block
881 : // +---------------------------+ B = base
882 : // \-----/ O = offset
883 : //
884 : class BlockGraph::Reference {
885 : public:
886 : Reference() :
887 E : type_(RELATIVE_REF), size_(0), referenced_(NULL), offset_(0), base_(0) {
888 E : }
889 :
890 : // @param type type of reference.
891 : // @param size size of reference.
892 : // @param referenced the referenced block.
893 : // @param offset offset from the beginning of the block of the location to be
894 : // explicitly referred to.
895 : // @param base offset into the block of the location actually being
896 : // referenced. This must be strictly within @p referenced.
897 : Reference(ReferenceType type,
898 : Size size,
899 : Block* referenced,
900 : Offset offset,
901 : Offset base)
902 : : type_(type),
903 : size_(size),
904 : referenced_(referenced),
905 : offset_(offset),
906 E : base_(base) {
907 E : DCHECK(IsValid());
908 E : }
909 :
910 : // Copy constructor.
911 : Reference(const Reference& other)
912 : : type_(other.type_),
913 : size_(other.size_),
914 : referenced_(other.referenced_),
915 : offset_(other.offset_),
916 E : base_(other.base_) {
917 E : }
918 :
919 : // Accessors.
920 E : ReferenceType type() const { return type_; }
921 E : Size size() const { return size_; }
922 E : Block* referenced() const { return referenced_; }
923 E : Offset offset() const { return offset_; }
924 E : Offset base() const { return base_; }
925 :
926 : // Determines if this is a direct reference. That is, if the actual location
927 : // being referenced (offset) and the intended location being referenced (base)
928 : // are the same.
929 : //
930 : // @returns true if the reference is direct, false otherwise.
931 E : bool IsDirect() const { return base_ == offset_; }
932 :
933 : // Determines if this is a valid reference, by imposing size constraints on
934 : // reference types, and determining if the base address of the reference is
935 : // strictly contained within the referenced block.
936 : //
937 : // @returns true if valid, false otherwise.
938 : bool IsValid() const;
939 :
940 E : bool operator==(const Reference& other) const {
941 : return type_ == other.type_ &&
942 : size_ == other.size_ &&
943 : referenced_ == other.referenced_ &&
944 : offset_ == other.offset_ &&
945 E : base_ == other.base_;
946 E : }
947 :
948 : // The maximum size that a reference may have. This needs to be kept in sync
949 : // with the expectations of IsValid().
950 : static const size_t kMaximumSize = 4;
951 :
952 : // Returns true if the given reference type and size combination is valid.
953 : static bool IsValidTypeSize(ReferenceType type, Size size);
954 :
955 : private:
956 : // Type of this reference.
957 : ReferenceType type_;
958 :
959 : // Size of this reference.
960 : // Absolute references are always pointer wide, but PC-relative
961 : // references can be 1, 2 or 4 bytes wide, which affects their range.
962 : Size size_;
963 :
964 : // The block referenced.
965 : Block* referenced_;
966 :
967 : // Offset into the referenced block.
968 : Offset offset_;
969 :
970 : // The base of the reference, as in offset in the block. This must be a
971 : // location strictly within the block.
972 : Offset base_;
973 : };
974 :
975 : // Commonly used container types.
976 : typedef std::vector<BlockGraph::Block*> BlockVector;
977 : typedef std::vector<const BlockGraph::Block*> ConstBlockVector;
978 :
979 : } // namespace block_graph
980 :
981 : #endif // SYZYGY_BLOCK_GRAPH_BLOCK_GRAPH_H_
|