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