Convert sync_unit_tests to run exclusively on Swarming
[chromium-blink-merge.git] / courgette / disassembler_win32_x64.cc
blob667b4e14afa99507d92dfc860fc5f35998ddc38a
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "courgette/disassembler_win32_x64.h"
7 #include <algorithm>
8 #include <string>
9 #include <vector>
11 #include "base/basictypes.h"
12 #include "base/logging.h"
13 #include "base/numerics/safe_conversions.h"
15 #include "courgette/assembly_program.h"
16 #include "courgette/courgette.h"
17 #include "courgette/encoded_program.h"
19 namespace courgette {
21 DisassemblerWin32X64::DisassemblerWin32X64(const void* start, size_t length)
22 : Disassembler(start, length),
23 incomplete_disassembly_(false),
24 is_PE32_plus_(false),
25 optional_header_(NULL),
26 size_of_optional_header_(0),
27 offset_of_data_directories_(0),
28 machine_type_(0),
29 number_of_sections_(0),
30 sections_(NULL),
31 has_text_section_(false),
32 size_of_code_(0),
33 size_of_initialized_data_(0),
34 size_of_uninitialized_data_(0),
35 base_of_code_(0),
36 base_of_data_(0),
37 image_base_(0),
38 size_of_image_(0),
39 number_of_data_directories_(0) {
42 // ParseHeader attempts to match up the buffer with the Windows data
43 // structures that exist within a Windows 'Portable Executable' format file.
44 // Returns 'true' if the buffer matches, and 'false' if the data looks
45 // suspicious. Rather than try to 'map' the buffer to the numerous windows
46 // structures, we extract the information we need into the courgette::PEInfo
47 // structure.
49 bool DisassemblerWin32X64::ParseHeader() {
50 if (length() < kOffsetOfFileAddressOfNewExeHeader + 4 /*size*/)
51 return Bad("Too small");
53 // Have 'MZ' magic for a DOS header?
54 if (start()[0] != 'M' || start()[1] != 'Z')
55 return Bad("Not MZ");
57 // offset from DOS header to PE header is stored in DOS header.
58 uint32 offset = ReadU32(start(),
59 kOffsetOfFileAddressOfNewExeHeader);
61 if (offset >= length())
62 return Bad("Bad offset to PE header");
64 const uint8* const pe_header = OffsetToPointer(offset);
65 const size_t kMinPEHeaderSize = 4 /*signature*/ + kSizeOfCoffHeader;
66 if (pe_header <= start() ||
67 pe_header >= end() - kMinPEHeaderSize)
68 return Bad("Bad offset to PE header");
70 if (offset % 8 != 0)
71 return Bad("Misaligned PE header");
73 // The 'PE' header is an IMAGE_NT_HEADERS structure as defined in WINNT.H.
74 // See http://msdn.microsoft.com/en-us/library/ms680336(VS.85).aspx
76 // The first field of the IMAGE_NT_HEADERS is the signature.
77 if (!(pe_header[0] == 'P' &&
78 pe_header[1] == 'E' &&
79 pe_header[2] == 0 &&
80 pe_header[3] == 0))
81 return Bad("no PE signature");
83 // The second field of the IMAGE_NT_HEADERS is the COFF header.
84 // The COFF header is also called an IMAGE_FILE_HEADER
85 // http://msdn.microsoft.com/en-us/library/ms680313(VS.85).aspx
86 const uint8* const coff_header = pe_header + 4;
87 machine_type_ = ReadU16(coff_header, 0);
88 number_of_sections_ = ReadU16(coff_header, 2);
89 size_of_optional_header_ = ReadU16(coff_header, 16);
91 // The rest of the IMAGE_NT_HEADERS is the IMAGE_OPTIONAL_HEADER(32|64)
92 const uint8* const optional_header = coff_header + kSizeOfCoffHeader;
93 optional_header_ = optional_header;
95 if (optional_header + size_of_optional_header_ >= end())
96 return Bad("optional header past end of file");
98 // Check we can read the magic.
99 if (size_of_optional_header_ < 2)
100 return Bad("optional header no magic");
102 uint16 magic = ReadU16(optional_header, 0);
104 if (magic == kImageNtOptionalHdr32Magic) {
105 is_PE32_plus_ = false;
106 offset_of_data_directories_ =
107 kOffsetOfDataDirectoryFromImageOptionalHeader32;
108 } else if (magic == kImageNtOptionalHdr64Magic) {
109 is_PE32_plus_ = true;
110 offset_of_data_directories_ =
111 kOffsetOfDataDirectoryFromImageOptionalHeader64;
112 } else {
113 return Bad("unrecognized magic");
116 // Check that we can read the rest of the the fixed fields. Data directories
117 // directly follow the fixed fields of the IMAGE_OPTIONAL_HEADER.
118 if (size_of_optional_header_ < offset_of_data_directories_)
119 return Bad("optional header too short");
121 // The optional header is either an IMAGE_OPTIONAL_HEADER32 or
122 // IMAGE_OPTIONAL_HEADER64
123 // http://msdn.microsoft.com/en-us/library/ms680339(VS.85).aspx
125 // Copy the fields we care about.
126 size_of_code_ = ReadU32(optional_header, 4);
127 size_of_initialized_data_ = ReadU32(optional_header, 8);
128 size_of_uninitialized_data_ = ReadU32(optional_header, 12);
129 base_of_code_ = ReadU32(optional_header, 20);
130 if (is_PE32_plus_) {
131 base_of_data_ = 0;
132 image_base_ = ReadU64(optional_header, 24);
133 } else {
134 base_of_data_ = ReadU32(optional_header, 24);
135 image_base_ = ReadU32(optional_header, 28);
137 size_of_image_ = ReadU32(optional_header, 56);
138 number_of_data_directories_ =
139 ReadU32(optional_header, (is_PE32_plus_ ? 108 : 92));
141 if (size_of_code_ >= length() ||
142 size_of_initialized_data_ >= length() ||
143 size_of_code_ + size_of_initialized_data_ >= length()) {
144 // This validation fires on some perfectly fine executables.
145 // return Bad("code or initialized data too big");
148 // TODO(sra): we can probably get rid of most of the data directories.
149 bool b = true;
150 // 'b &= ...' could be short circuit 'b = b && ...' but it is not necessary
151 // for correctness and it compiles smaller this way.
152 b &= ReadDataDirectory(0, &export_table_);
153 b &= ReadDataDirectory(1, &import_table_);
154 b &= ReadDataDirectory(2, &resource_table_);
155 b &= ReadDataDirectory(3, &exception_table_);
156 b &= ReadDataDirectory(5, &base_relocation_table_);
157 b &= ReadDataDirectory(11, &bound_import_table_);
158 b &= ReadDataDirectory(12, &import_address_table_);
159 b &= ReadDataDirectory(13, &delay_import_descriptor_);
160 b &= ReadDataDirectory(14, &clr_runtime_header_);
161 if (!b) {
162 return Bad("malformed data directory");
165 // Sections follow the optional header.
166 sections_ =
167 reinterpret_cast<const Section*>(optional_header +
168 size_of_optional_header_);
169 size_t detected_length = 0;
171 for (int i = 0; i < number_of_sections_; ++i) {
172 const Section* section = &sections_[i];
174 // TODO(sra): consider using the 'characteristics' field of the section
175 // header to see if the section contains instructions.
176 if (memcmp(section->name, ".text", 6) == 0)
177 has_text_section_ = true;
179 uint32 section_end =
180 section->file_offset_of_raw_data + section->size_of_raw_data;
181 if (section_end > detected_length)
182 detected_length = section_end;
185 // Pretend our in-memory copy is only as long as our detected length.
186 ReduceLength(detected_length);
188 if (is_32bit()) {
189 return Bad("32 bit executables are not supported by this disassembler");
192 if (!has_text_section()) {
193 return Bad("Resource-only executables are not yet supported");
196 return Good();
199 bool DisassemblerWin32X64::Disassemble(AssemblyProgram* target) {
200 if (!ok())
201 return false;
203 target->set_image_base(image_base());
205 if (!ParseAbs32Relocs())
206 return false;
208 ParseRel32RelocsFromSections();
210 if (!ParseFile(target))
211 return false;
213 target->DefaultAssignIndexes();
215 return true;
218 ////////////////////////////////////////////////////////////////////////////////
220 bool DisassemblerWin32X64::ParseRelocs(std::vector<RVA> *relocs) {
221 relocs->clear();
223 size_t relocs_size = base_relocation_table_.size_;
224 if (relocs_size == 0)
225 return true;
227 // The format of the base relocation table is a sequence of variable sized
228 // IMAGE_BASE_RELOCATION blocks. Search for
229 // "The format of the base relocation data is somewhat quirky"
230 // at http://msdn.microsoft.com/en-us/library/ms809762.aspx
232 const uint8* relocs_start = RVAToPointer(base_relocation_table_.address_);
233 const uint8* relocs_end = relocs_start + relocs_size;
235 // Make sure entire base relocation table is within the buffer.
236 if (relocs_start < start() ||
237 relocs_start >= end() ||
238 relocs_end <= start() ||
239 relocs_end > end()) {
240 return Bad(".relocs outside image");
243 const uint8* block = relocs_start;
245 // Walk the variable sized blocks.
246 while (block + 8 < relocs_end) {
247 RVA page_rva = ReadU32(block, 0);
248 uint32 size = ReadU32(block, 4);
249 if (size < 8 || // Size includes header ...
250 size % 4 != 0) // ... and is word aligned.
251 return Bad("unreasonable relocs block");
253 const uint8* end_entries = block + size;
255 if (end_entries <= block ||
256 end_entries <= start() ||
257 end_entries > end())
258 return Bad(".relocs block outside image");
260 // Walk through the two-byte entries.
261 for (const uint8* p = block + 8; p < end_entries; p += 2) {
262 uint16 entry = ReadU16(p, 0);
263 int type = entry >> 12;
264 int offset = entry & 0xFFF;
266 RVA rva = page_rva + offset;
267 if (type == 10) { // IMAGE_REL_BASED_DIR64
268 relocs->push_back(rva);
269 } else if (type == 0) { // IMAGE_REL_BASED_ABSOLUTE
270 // Ignore, used as padding.
271 } else {
272 // Does not occur in Windows x64 executables.
273 return Bad("unknown type of reloc");
277 block += size;
280 std::sort(relocs->begin(), relocs->end());
282 return true;
285 const Section* DisassemblerWin32X64::RVAToSection(RVA rva) const {
286 for (int i = 0; i < number_of_sections_; i++) {
287 const Section* section = &sections_[i];
288 uint32 offset = rva - section->virtual_address;
289 if (offset < section->virtual_size) {
290 return section;
293 return NULL;
296 int DisassemblerWin32X64::RVAToFileOffset(RVA rva) const {
297 const Section* section = RVAToSection(rva);
298 if (section) {
299 uint32 offset = rva - section->virtual_address;
300 if (offset < section->size_of_raw_data) {
301 return section->file_offset_of_raw_data + offset;
302 } else {
303 return kNoOffset; // In section but not in file (e.g. uninit data).
307 // Small RVA values point into the file header in the loaded image.
308 // RVA 0 is the module load address which Windows uses as the module handle.
309 // RVA 2 sometimes occurs, I'm not sure what it is, but it would map into the
310 // DOS header.
311 if (rva == 0 || rva == 2)
312 return rva;
314 NOTREACHED();
315 return kNoOffset;
318 const uint8* DisassemblerWin32X64::RVAToPointer(RVA rva) const {
319 int file_offset = RVAToFileOffset(rva);
320 if (file_offset == kNoOffset)
321 return NULL;
322 else
323 return OffsetToPointer(file_offset);
326 std::string DisassemblerWin32X64::SectionName(const Section* section) {
327 if (section == NULL)
328 return "<none>";
329 char name[9];
330 memcpy(name, section->name, 8);
331 name[8] = '\0'; // Ensure termination.
332 return name;
335 CheckBool DisassemblerWin32X64::ParseFile(AssemblyProgram* program) {
336 // Walk all the bytes in the file, whether or not in a section.
337 uint32 file_offset = 0;
338 while (file_offset < length()) {
339 const Section* section = FindNextSection(file_offset);
340 if (section == NULL) {
341 // No more sections. There should not be extra stuff following last
342 // section.
343 // ParseNonSectionFileRegion(file_offset, pe_info().length(), program);
344 break;
346 if (file_offset < section->file_offset_of_raw_data) {
347 uint32 section_start_offset = section->file_offset_of_raw_data;
348 if(!ParseNonSectionFileRegion(file_offset, section_start_offset,
349 program))
350 return false;
352 file_offset = section_start_offset;
354 uint32 end = file_offset + section->size_of_raw_data;
355 if (!ParseFileRegion(section, file_offset, end, program))
356 return false;
357 file_offset = end;
360 #if COURGETTE_HISTOGRAM_TARGETS
361 HistogramTargets("abs32 relocs", abs32_target_rvas_);
362 HistogramTargets("rel32 relocs", rel32_target_rvas_);
363 #endif
365 return true;
368 bool DisassemblerWin32X64::ParseAbs32Relocs() {
369 abs32_locations_.clear();
370 if (!ParseRelocs(&abs32_locations_))
371 return false;
373 std::sort(abs32_locations_.begin(), abs32_locations_.end());
375 #if COURGETTE_HISTOGRAM_TARGETS
376 for (size_t i = 0; i < abs32_locations_.size(); ++i) {
377 RVA rva = abs32_locations_[i];
378 // The 4 bytes at the relocation are a reference to some address.
379 uint32 target_address = Read32LittleEndian(RVAToPointer(rva));
380 ++abs32_target_rvas_[target_address - image_base()];
382 #endif
383 return true;
386 void DisassemblerWin32X64::ParseRel32RelocsFromSections() {
387 uint32 file_offset = 0;
388 while (file_offset < length()) {
389 const Section* section = FindNextSection(file_offset);
390 if (section == NULL)
391 break;
392 if (file_offset < section->file_offset_of_raw_data)
393 file_offset = section->file_offset_of_raw_data;
394 ParseRel32RelocsFromSection(section);
395 file_offset += section->size_of_raw_data;
397 std::sort(rel32_locations_.begin(), rel32_locations_.end());
399 #if COURGETTE_HISTOGRAM_TARGETS
400 VLOG(1) << "abs32_locations_ " << abs32_locations_.size()
401 << "\nrel32_locations_ " << rel32_locations_.size()
402 << "\nabs32_target_rvas_ " << abs32_target_rvas_.size()
403 << "\nrel32_target_rvas_ " << rel32_target_rvas_.size();
405 int common = 0;
406 std::map<RVA, int>::iterator abs32_iter = abs32_target_rvas_.begin();
407 std::map<RVA, int>::iterator rel32_iter = rel32_target_rvas_.begin();
408 while (abs32_iter != abs32_target_rvas_.end() &&
409 rel32_iter != rel32_target_rvas_.end()) {
410 if (abs32_iter->first < rel32_iter->first)
411 ++abs32_iter;
412 else if (rel32_iter->first < abs32_iter->first)
413 ++rel32_iter;
414 else {
415 ++common;
416 ++abs32_iter;
417 ++rel32_iter;
420 VLOG(1) << "common " << common;
421 #endif
424 void DisassemblerWin32X64::ParseRel32RelocsFromSection(const Section* section) {
425 // TODO(sra): use characteristic.
426 bool isCode = strcmp(section->name, ".text") == 0;
427 if (!isCode)
428 return;
430 uint32 start_file_offset = section->file_offset_of_raw_data;
431 uint32 end_file_offset = start_file_offset + section->size_of_raw_data;
432 RVA relocs_start_rva = base_relocation_table().address_;
434 const uint8* start_pointer = OffsetToPointer(start_file_offset);
435 const uint8* end_pointer = OffsetToPointer(end_file_offset);
437 RVA start_rva = FileOffsetToRVA(start_file_offset);
438 RVA end_rva = start_rva + section->virtual_size;
440 // Quick way to convert from Pointer to RVA within a single Section is to
441 // subtract 'pointer_to_rva'.
442 const uint8* const adjust_pointer_to_rva = start_pointer - start_rva;
444 std::vector<RVA>::iterator abs32_pos = abs32_locations_.begin();
446 // Find the rel32 relocations.
447 const uint8* p = start_pointer;
448 while (p < end_pointer) {
449 RVA current_rva = static_cast<RVA>(p - adjust_pointer_to_rva);
450 if (current_rva == relocs_start_rva) {
451 uint32 relocs_size = base_relocation_table().size_;
452 if (relocs_size) {
453 p += relocs_size;
454 continue;
458 //while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva)
459 // ++abs32_pos;
461 // Heuristic discovery of rel32 locations in instruction stream: are the
462 // next few bytes the start of an instruction containing a rel32
463 // addressing mode?
464 const uint8* rel32 = NULL;
465 bool is_rip_relative = false;
467 if (p + 5 <= end_pointer) {
468 if (*p == 0xE8 || *p == 0xE9) // jmp rel32 and call rel32
469 rel32 = p + 1;
471 if (p + 6 <= end_pointer) {
472 if (*p == 0x0F && (*(p + 1) & 0xF0) == 0x80) { // Jcc long form
473 if (p[1] != 0x8A && p[1] != 0x8B) // JPE/JPO unlikely
474 rel32 = p + 2;
475 } else if (*p == 0xFF && (*(p + 1) == 0x15 || *(p + 1) == 0x25)) {
476 // rip relative call/jmp
477 rel32 = p + 2;
478 is_rip_relative = true;
481 if (p + 7 <= end_pointer) {
482 if ((*p & 0xFB) == 0x48 && *(p + 1) == 0x8D &&
483 (*(p + 2) & 0xC7) == 0x05) {
484 // rip relative lea
485 rel32 = p + 3;
486 is_rip_relative = true;
487 } else if ((*p & 0xFB) == 0x48 && *(p + 1) == 0x8B &&
488 (*(p + 2) & 0xC7) == 0x05) {
489 // rip relative mov
490 rel32 = p + 3;
491 is_rip_relative = true;
495 if (rel32) {
496 RVA rel32_rva = static_cast<RVA>(rel32 - adjust_pointer_to_rva);
498 // Is there an abs32 reloc overlapping the candidate?
499 while (abs32_pos != abs32_locations_.end() && *abs32_pos < rel32_rva - 3)
500 ++abs32_pos;
501 // Now: (*abs32_pos > rel32_rva - 4) i.e. the lowest addressed 4-byte
502 // region that could overlap rel32_rva.
503 if (abs32_pos != abs32_locations_.end()) {
504 if (*abs32_pos < rel32_rva + 4) {
505 // Beginning of abs32 reloc is before end of rel32 reloc so they
506 // overlap. Skip four bytes past the abs32 reloc.
507 p += (*abs32_pos + 4) - current_rva;
508 continue;
512 RVA target_rva = rel32_rva + 4 + Read32LittleEndian(rel32);
513 // To be valid, rel32 target must be within image, and within this
514 // section.
515 if (IsValidRVA(target_rva) &&
516 (is_rip_relative ||
517 (start_rva <= target_rva && target_rva < end_rva))) {
518 rel32_locations_.push_back(rel32_rva);
519 #if COURGETTE_HISTOGRAM_TARGETS
520 ++rel32_target_rvas_[target_rva];
521 #endif
522 p = rel32 + 4;
523 continue;
526 p += 1;
530 CheckBool DisassemblerWin32X64::ParseNonSectionFileRegion(
531 uint32 start_file_offset,
532 uint32 end_file_offset,
533 AssemblyProgram* program) {
534 if (incomplete_disassembly_)
535 return true;
537 if (end_file_offset > start_file_offset) {
538 if (!program->EmitBytesInstruction(OffsetToPointer(start_file_offset),
539 end_file_offset - start_file_offset)) {
540 return false;
544 return true;
547 CheckBool DisassemblerWin32X64::ParseFileRegion(
548 const Section* section,
549 uint32 start_file_offset, uint32 end_file_offset,
550 AssemblyProgram* program) {
551 RVA relocs_start_rva = base_relocation_table().address_;
553 const uint8* start_pointer = OffsetToPointer(start_file_offset);
554 const uint8* end_pointer = OffsetToPointer(end_file_offset);
556 RVA start_rva = FileOffsetToRVA(start_file_offset);
557 RVA end_rva = start_rva + section->virtual_size;
559 // Quick way to convert from Pointer to RVA within a single Section is to
560 // subtract 'pointer_to_rva'.
561 const uint8* const adjust_pointer_to_rva = start_pointer - start_rva;
563 std::vector<RVA>::iterator rel32_pos = rel32_locations_.begin();
564 std::vector<RVA>::iterator abs32_pos = abs32_locations_.begin();
566 if (!program->EmitOriginInstruction(start_rva))
567 return false;
569 const uint8* p = start_pointer;
571 while (p < end_pointer) {
572 RVA current_rva = static_cast<RVA>(p - adjust_pointer_to_rva);
574 // The base relocation table is usually in the .relocs section, but it could
575 // actually be anywhere. Make sure we skip it because we will regenerate it
576 // during assembly.
577 if (current_rva == relocs_start_rva) {
578 if (!program->EmitPeRelocsInstruction())
579 return false;
580 uint32 relocs_size = base_relocation_table().size_;
581 if (relocs_size) {
582 p += relocs_size;
583 continue;
587 while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva)
588 ++abs32_pos;
590 if (abs32_pos != abs32_locations_.end() && *abs32_pos == current_rva) {
591 uint64 target_address = Read64LittleEndian(p);
592 RVA target_rva = base::checked_cast<RVA>(target_address - image_base());
593 // TODO(sra): target could be Label+offset. It is not clear how to guess
594 // which it might be. We assume offset==0.
595 if (!program->EmitAbs64(program->FindOrMakeAbs32Label(target_rva)))
596 return false;
597 p += 8;
598 continue;
601 while (rel32_pos != rel32_locations_.end() && *rel32_pos < current_rva)
602 ++rel32_pos;
604 if (rel32_pos != rel32_locations_.end() && *rel32_pos == current_rva) {
605 RVA target_rva = current_rva + 4 + Read32LittleEndian(p);
606 if (!program->EmitRel32(program->FindOrMakeRel32Label(target_rva)))
607 return false;
608 p += 4;
609 continue;
612 if (incomplete_disassembly_) {
613 if ((abs32_pos == abs32_locations_.end() || end_rva <= *abs32_pos) &&
614 (rel32_pos == rel32_locations_.end() || end_rva <= *rel32_pos) &&
615 (end_rva <= relocs_start_rva || current_rva >= relocs_start_rva)) {
616 // No more relocs in this section, don't bother encoding bytes.
617 break;
621 if (!program->EmitByteInstruction(*p))
622 return false;
623 p += 1;
626 return true;
629 #if COURGETTE_HISTOGRAM_TARGETS
630 // Histogram is printed to std::cout. It is purely for debugging the algorithm
631 // and is only enabled manually in 'exploration' builds. I don't want to add
632 // command-line configuration for this feature because this code has to be
633 // small, which means compiled-out.
634 void DisassemblerWin32X64::HistogramTargets(const char* kind,
635 const std::map<RVA, int>& map) {
636 int total = 0;
637 std::map<int, std::vector<RVA> > h;
638 for (std::map<RVA, int>::const_iterator p = map.begin();
639 p != map.end();
640 ++p) {
641 h[p->second].push_back(p->first);
642 total += p->second;
645 std::cout << total << " " << kind << " to "
646 << map.size() << " unique targets" << std::endl;
648 std::cout << "indegree: #targets-with-indegree (example)" << std::endl;
649 const int kFirstN = 15;
650 bool someSkipped = false;
651 int index = 0;
652 for (std::map<int, std::vector<RVA> >::reverse_iterator p = h.rbegin();
653 p != h.rend();
654 ++p) {
655 ++index;
656 if (index <= kFirstN || p->first <= 3) {
657 if (someSkipped) {
658 std::cout << "..." << std::endl;
660 size_t count = p->second.size();
661 std::cout << std::dec << p->first << ": " << count;
662 if (count <= 2) {
663 for (size_t i = 0; i < count; ++i)
664 std::cout << " " << DescribeRVA(p->second[i]);
666 std::cout << std::endl;
667 someSkipped = false;
668 } else {
669 someSkipped = true;
673 #endif // COURGETTE_HISTOGRAM_TARGETS
676 // DescribeRVA is for debugging only. I would put it under #ifdef DEBUG except
677 // that during development I'm finding I need to call it when compiled in
678 // Release mode. Hence:
679 // TODO(sra): make this compile only for debug mode.
680 std::string DisassemblerWin32X64::DescribeRVA(RVA rva) const {
681 const Section* section = RVAToSection(rva);
682 std::ostringstream s;
683 s << std::hex << rva;
684 if (section) {
685 s << " (";
686 s << SectionName(section) << "+"
687 << std::hex << (rva - section->virtual_address)
688 << ")";
690 return s.str();
693 const Section* DisassemblerWin32X64::FindNextSection(uint32 fileOffset) const {
694 const Section* best = 0;
695 for (int i = 0; i < number_of_sections_; i++) {
696 const Section* section = &sections_[i];
697 if (section->size_of_raw_data > 0) { // i.e. has data in file.
698 if (fileOffset <= section->file_offset_of_raw_data) {
699 if (best == 0 ||
700 section->file_offset_of_raw_data < best->file_offset_of_raw_data) {
701 best = section;
706 return best;
709 RVA DisassemblerWin32X64::FileOffsetToRVA(uint32 file_offset) const {
710 for (int i = 0; i < number_of_sections_; i++) {
711 const Section* section = &sections_[i];
712 uint32 offset = file_offset - section->file_offset_of_raw_data;
713 if (offset < section->size_of_raw_data) {
714 return section->virtual_address + offset;
717 return 0;
720 bool DisassemblerWin32X64::ReadDataDirectory(
721 int index,
722 ImageDataDirectory* directory) {
724 if (index < number_of_data_directories_) {
725 size_t offset = index * 8 + offset_of_data_directories_;
726 if (offset >= size_of_optional_header_)
727 return Bad("number of data directories inconsistent");
728 const uint8* data_directory = optional_header_ + offset;
729 if (data_directory < start() ||
730 data_directory + 8 >= end())
731 return Bad("data directory outside image");
732 RVA rva = ReadU32(data_directory, 0);
733 size_t size = ReadU32(data_directory, 4);
734 if (size > size_of_image_)
735 return Bad("data directory size too big");
737 // TODO(sra): validate RVA.
738 directory->address_ = rva;
739 directory->size_ = static_cast<uint32>(size);
740 return true;
741 } else {
742 directory->address_ = 0;
743 directory->size_ = 0;
744 return true;
748 } // namespace courgette