disassembler_win32.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. // Copyright 2016 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.
  4. #include "courgette/disassembler_win32.h"
  5. #include <algorithm>
  6. #include "base/bind.h"
  7. #include "base/logging.h"
  8. #include "courgette/assembly_program.h"
  9. #include "courgette/courgette.h"
  10. #if COURGETTE_HISTOGRAM_TARGETS
  11. #include <iostream>
  12. #endif
  13. namespace courgette {
  14. DisassemblerWin32::DisassemblerWin32(const uint8_t* start, size_t length)
  15. : Disassembler(start, length) {}
  16. RVA DisassemblerWin32::FileOffsetToRVA(FileOffset file_offset) const {
  17. for (int i = 0; i < number_of_sections_; ++i) {
  18. const Section* section = &sections_[i];
  19. if (file_offset >= section->file_offset_of_raw_data) {
  20. FileOffset offset_in_section =
  21. file_offset - section->file_offset_of_raw_data;
  22. if (offset_in_section < section->size_of_raw_data)
  23. return static_cast<RVA>(section->virtual_address + offset_in_section);
  24. }
  25. }
  26. NOTREACHED();
  27. return kNoRVA;
  28. }
  29. FileOffset DisassemblerWin32::RVAToFileOffset(RVA rva) const {
  30. const Section* section = RVAToSection(rva);
  31. if (section != nullptr) {
  32. FileOffset offset_in_section = rva - section->virtual_address;
  33. // Need this extra check, since an |rva| may be valid for a section, but is
  34. // non-existent in an image (e.g. uninit data).
  35. if (offset_in_section >= section->size_of_raw_data)
  36. return kNoFileOffset;
  37. return static_cast<FileOffset>(section->file_offset_of_raw_data +
  38. offset_in_section);
  39. }
  40. // Small RVA values point into the file header in the loaded image.
  41. // RVA 0 is the module load address which Windows uses as the module handle.
  42. // RVA 2 sometimes occurs, I'm not sure what it is, but it would map into the
  43. // DOS header.
  44. if (rva == 0 || rva == 2)
  45. return static_cast<FileOffset>(rva);
  46. NOTREACHED();
  47. return kNoFileOffset;
  48. }
  49. // ParseHeader attempts to match up the buffer with the Windows data
  50. // structures that exist within a Windows 'Portable Executable' format file.
  51. // Returns 'true' if the buffer matches, and 'false' if the data looks
  52. // suspicious. Rather than try to 'map' the buffer to the numerous windows
  53. // structures, we extract the information we need into the courgette::PEInfo
  54. // structure.
  55. //
  56. bool DisassemblerWin32::ParseHeader() {
  57. if (!IsRangeInBounds(kOffsetOfFileAddressOfNewExeHeader, 4))
  58. return Bad("Too small");
  59. // Have 'MZ' magic for a DOS header?
  60. if (start()[0] != 'M' || start()[1] != 'Z')
  61. return Bad("Not MZ");
  62. // offset from DOS header to PE header is stored in DOS header.
  63. FileOffset pe_header_offset = static_cast<FileOffset>(
  64. ReadU32(start(), kOffsetOfFileAddressOfNewExeHeader));
  65. if (pe_header_offset % 8 != 0)
  66. return Bad("Misaligned PE header");
  67. if (pe_header_offset < kOffsetOfFileAddressOfNewExeHeader + 4)
  68. return Bad("PE header pathological overlap");
  69. if (!IsRangeInBounds(pe_header_offset, kMinPeHeaderSize))
  70. return Bad("PE header past end of file");
  71. const uint8_t* const pe_header = FileOffsetToPointer(pe_header_offset);
  72. // The 'PE' header is an IMAGE_NT_HEADERS structure as defined in WINNT.H.
  73. // See http://msdn.microsoft.com/en-us/library/ms680336(VS.85).aspx
  74. //
  75. // The first field of the IMAGE_NT_HEADERS is the signature.
  76. if (!(pe_header[0] == 'P' && pe_header[1] == 'E' && pe_header[2] == 0 &&
  77. pe_header[3] == 0)) {
  78. return Bad("No PE signature");
  79. }
  80. // The second field of the IMAGE_NT_HEADERS is the COFF header.
  81. // The COFF header is also called an IMAGE_FILE_HEADER
  82. // http://msdn.microsoft.com/en-us/library/ms680313(VS.85).aspx
  83. FileOffset coff_header_offset = pe_header_offset + 4;
  84. if (!IsRangeInBounds(coff_header_offset, kSizeOfCoffHeader))
  85. return Bad("COFF header past end of file");
  86. const uint8_t* const coff_header = start() + coff_header_offset;
  87. machine_type_ = ReadU16(coff_header, 0);
  88. number_of_sections_ = ReadU16(coff_header, 2);
  89. size_of_optional_header_ = ReadU16(coff_header, 16);
  90. // Check we can read the magic.
  91. if (size_of_optional_header_ < 2)
  92. return Bad("Optional header no magic");
  93. // Check that we can read the rest of the the fixed fields. Data directories
  94. // directly follow the fixed fields of the IMAGE_OPTIONAL_HEADER.
  95. if (size_of_optional_header_ < RelativeOffsetOfDataDirectories())
  96. return Bad("Optional header too short");
  97. // The rest of the IMAGE_NT_HEADERS is the IMAGE_OPTIONAL_HEADER(32|64)
  98. FileOffset optional_header_offset = pe_header_offset + kMinPeHeaderSize;
  99. if (!IsRangeInBounds(optional_header_offset, size_of_optional_header_))
  100. return Bad("Optional header past end of file");
  101. optional_header_ = start() + optional_header_offset;
  102. uint16_t magic = ReadU16(optional_header_, 0);
  103. switch (kind()) {
  104. case EXE_WIN_32_X86:
  105. if (magic != kImageNtOptionalHdr32Magic)
  106. return Bad("64 bit executables are not supported by this disassembler");
  107. break;
  108. case EXE_WIN_32_X64:
  109. if (magic != kImageNtOptionalHdr64Magic)
  110. return Bad("32 bit executables are not supported by this disassembler");
  111. break;
  112. default:
  113. return Bad("Unrecognized magic");
  114. }
  115. // The optional header is either an IMAGE_OPTIONAL_HEADER32 or
  116. // IMAGE_OPTIONAL_HEADER64
  117. // http://msdn.microsoft.com/en-us/library/ms680339(VS.85).aspx
  118. //
  119. // Copy the fields we care about.
  120. size_of_code_ = ReadU32(optional_header_, 4);
  121. size_of_initialized_data_ = ReadU32(optional_header_, 8);
  122. size_of_uninitialized_data_ = ReadU32(optional_header_, 12);
  123. base_of_code_ = ReadU32(optional_header_, 20);
  124. switch (kind()) {
  125. case EXE_WIN_32_X86:
  126. base_of_data_ = ReadU32(optional_header_, 24);
  127. image_base_ = ReadU32(optional_header_, 28);
  128. size_of_image_ = ReadU32(optional_header_, 56);
  129. number_of_data_directories_ = ReadU32(optional_header_, 92);
  130. break;
  131. case EXE_WIN_32_X64:
  132. base_of_data_ = 0;
  133. image_base_ = ReadU64(optional_header_, 24);
  134. size_of_image_ = ReadU32(optional_header_, 56);
  135. number_of_data_directories_ = ReadU32(optional_header_, 108);
  136. break;
  137. default:
  138. NOTREACHED();
  139. }
  140. if (size_of_image_ >= 0x80000000U)
  141. return Bad("Invalid SizeOfImage");
  142. if (size_of_code_ >= length() || 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");
  146. }
  147. // TODO(sra): we can probably get rid of most of the data directories.
  148. bool b = true;
  149. // 'b &= ...' could be short circuit 'b = b && ...' but it is not necessary
  150. // for correctness and it compiles smaller this way.
  151. b &= ReadDataDirectory(0, &export_table_);
  152. b &= ReadDataDirectory(1, &import_table_);
  153. b &= ReadDataDirectory(2, &resource_table_);
  154. b &= ReadDataDirectory(3, &exception_table_);
  155. b &= ReadDataDirectory(5, &base_relocation_table_);
  156. b &= ReadDataDirectory(11, &bound_import_table_);
  157. b &= ReadDataDirectory(12, &import_address_table_);
  158. b &= ReadDataDirectory(13, &delay_import_descriptor_);
  159. b &= ReadDataDirectory(14, &clr_runtime_header_);
  160. if (!b)
  161. return Bad("Malformed data directory");
  162. // Sections follow the optional header.
  163. FileOffset sections_offset =
  164. optional_header_offset + size_of_optional_header_;
  165. if (!IsArrayInBounds(sections_offset, number_of_sections_, sizeof(Section)))
  166. return Bad("Sections past end of file");
  167. sections_ = reinterpret_cast<const Section*>(start() + sections_offset);
  168. if (!CheckSectionRanges())
  169. return Bad("Out of bound section");
  170. size_t detected_length = 0;
  171. for (int i = 0; i < number_of_sections_; ++i) {
  172. const Section* section = &sections_[i];
  173. // TODO(sra): consider using the 'characteristics' field of the section
  174. // header to see if the section contains instructions.
  175. if (memcmp(section->name, ".text", 6) == 0)
  176. has_text_section_ = true;
  177. uint32_t section_end =
  178. section->file_offset_of_raw_data + section->size_of_raw_data;
  179. if (section_end > detected_length)
  180. detected_length = section_end;
  181. }
  182. // Pretend our in-memory copy is only as long as our detected length.
  183. ReduceLength(detected_length);
  184. if (!has_text_section()) {
  185. return Bad("Resource-only executables are not yet supported");
  186. }
  187. return Good();
  188. }
  189. ////////////////////////////////////////////////////////////////////////////////
  190. bool DisassemblerWin32::ParseRelocs(std::vector<RVA>* relocs) {
  191. relocs->clear();
  192. size_t relocs_size = base_relocation_table_.size_;
  193. if (relocs_size == 0)
  194. return true;
  195. // The format of the base relocation table is a sequence of variable sized
  196. // IMAGE_BASE_RELOCATION blocks. Search for
  197. // "The format of the base relocation data is somewhat quirky"
  198. // at http://msdn.microsoft.com/en-us/library/ms809762.aspx
  199. const uint8_t* relocs_start = RVAToPointer(base_relocation_table_.address_);
  200. if (relocs_start == nullptr || relocs_start < start() ||
  201. relocs_start >= end())
  202. return Bad(".relocs outside image");
  203. // Make sure entire base relocation table is within the buffer.
  204. if (relocs_size > static_cast<size_t>(end() - relocs_start))
  205. return Bad(".relocs outside image");
  206. const uint8_t* relocs_end = relocs_start + relocs_size;
  207. const uint8_t* block = relocs_start;
  208. // Walk the variable sized blocks.
  209. while (block + 8 < relocs_end) {
  210. RVA page_rva = ReadU32(block, 0);
  211. uint32_t size = ReadU32(block, 4);
  212. if (size < 8 || // Size includes header ...
  213. size % 4 != 0) // ... and is word aligned.
  214. return Bad("Unreasonable relocs block");
  215. const uint8_t* end_entries = block + size;
  216. if (end_entries <= block || end_entries <= start() || end_entries > end())
  217. return Bad(".relocs block outside image");
  218. // Walk through the two-byte entries.
  219. for (const uint8_t* p = block + 8; p < end_entries; p += 2) {
  220. uint16_t entry = ReadU16(p, 0);
  221. int type = entry >> 12;
  222. int offset = entry & 0xFFF;
  223. RVA rva = page_rva + offset;
  224. // Skip the relocs that live outside of the image. It might be the case
  225. // if a reloc is relative to a register, e.g.:
  226. // mov ecx,dword ptr [eax+044D5888h]
  227. RVA target_rva = PointerToTargetRVA(RVAToPointer(rva));
  228. if (target_rva == kNoRVA) {
  229. continue;
  230. }
  231. if (SupportsRelTableType(type)) {
  232. relocs->push_back(rva);
  233. } else if (type == 0) { // IMAGE_REL_BASED_ABSOLUTE
  234. // Ignore, used as padding.
  235. } else {
  236. // Does not occur in Windows x86/x64 executables.
  237. return Bad("Unknown type of reloc");
  238. }
  239. }
  240. block += size;
  241. }
  242. std::sort(relocs->begin(), relocs->end());
  243. DCHECK(relocs->empty() || relocs->back() != kUnassignedRVA);
  244. return true;
  245. }
  246. const Section* DisassemblerWin32::RVAToSection(RVA rva) const {
  247. for (int i = 0; i < number_of_sections_; ++i) {
  248. const Section* section = &sections_[i];
  249. if (rva >= section->virtual_address) {
  250. FileOffset offset_in_section = rva - section->virtual_address;
  251. if (offset_in_section < section->virtual_size)
  252. return section;
  253. }
  254. }
  255. return nullptr;
  256. }
  257. std::string DisassemblerWin32::SectionName(const Section* section) {
  258. if (section == nullptr)
  259. return "<none>";
  260. char name[9];
  261. memcpy(name, section->name, 8);
  262. name[8] = '\0'; // Ensure termination.
  263. return name;
  264. }
  265. // static
  266. bool DisassemblerWin32::QuickDetect(const uint8_t* start,
  267. size_t length,
  268. uint16_t magic) {
  269. if (length < kOffsetOfFileAddressOfNewExeHeader + 4)
  270. return false;
  271. // Have 'MZ' magic for a DOS header?
  272. if (start[0] != 'M' || start[1] != 'Z')
  273. return false;
  274. FileOffset pe_header_offset = static_cast<FileOffset>(
  275. ReadU32(start, kOffsetOfFileAddressOfNewExeHeader));
  276. if (pe_header_offset % 8 != 0 ||
  277. pe_header_offset < kOffsetOfFileAddressOfNewExeHeader + 4 ||
  278. pe_header_offset >= length ||
  279. length - pe_header_offset < kMinPeHeaderSize) {
  280. return false;
  281. }
  282. const uint8_t* pe_header = start + pe_header_offset;
  283. if (!(pe_header[0] == 'P' && pe_header[1] == 'E' && pe_header[2] == 0 &&
  284. pe_header[3] == 0)) {
  285. return false;
  286. }
  287. FileOffset optional_header_offset = pe_header_offset + kMinPeHeaderSize;
  288. if (optional_header_offset >= length || length - optional_header_offset < 2)
  289. return false;
  290. const uint8_t* optional_header = start + optional_header_offset;
  291. return magic == ReadU16(optional_header, 0);
  292. }
  293. bool DisassemblerWin32::IsRvaRangeInBounds(size_t start, size_t length) {
  294. return start < size_of_image_ && length <= size_of_image_ - start;
  295. }
  296. bool DisassemblerWin32::CheckSectionRanges() {
  297. for (int i = 0; i < number_of_sections_; ++i) {
  298. const Section* section = &sections_[i];
  299. if (!IsRangeInBounds(section->file_offset_of_raw_data,
  300. section->size_of_raw_data) ||
  301. !IsRvaRangeInBounds(section->virtual_address, section->virtual_size)) {
  302. return false;
  303. }
  304. }
  305. return true;
  306. }
  307. bool DisassemblerWin32::ExtractAbs32Locations() {
  308. abs32_locations_.clear();
  309. if (!ParseRelocs(&abs32_locations_))
  310. return false;
  311. #if COURGETTE_HISTOGRAM_TARGETS
  312. for (size_t i = 0; i < abs32_locations_.size(); ++i) {
  313. RVA rva = abs32_locations_[i];
  314. // The 4 bytes at the relocation are a reference to some address.
  315. ++abs32_target_rvas_[PointerToTargetRVA(RVAToPointer(rva))];
  316. }
  317. #endif
  318. return true;
  319. }
  320. bool DisassemblerWin32::ExtractRel32Locations() {
  321. FileOffset file_offset = 0;
  322. while (file_offset < length()) {
  323. const Section* section = FindNextSection(file_offset);
  324. if (section == nullptr)
  325. break;
  326. if (file_offset < section->file_offset_of_raw_data)
  327. file_offset = section->file_offset_of_raw_data;
  328. ParseRel32RelocsFromSection(section);
  329. file_offset += section->size_of_raw_data;
  330. }
  331. std::sort(rel32_locations_.begin(), rel32_locations_.end());
  332. DCHECK(rel32_locations_.empty() || rel32_locations_.back() != kUnassignedRVA);
  333. #if COURGETTE_HISTOGRAM_TARGETS
  334. VLOG(1) << "abs32_locations_ " << abs32_locations_.size()
  335. << "\nrel32_locations_ " << rel32_locations_.size()
  336. << "\nabs32_target_rvas_ " << abs32_target_rvas_.size()
  337. << "\nrel32_target_rvas_ " << rel32_target_rvas_.size();
  338. int common = 0;
  339. std::map<RVA, int>::iterator abs32_iter = abs32_target_rvas_.begin();
  340. std::map<RVA, int>::iterator rel32_iter = rel32_target_rvas_.begin();
  341. while (abs32_iter != abs32_target_rvas_.end() &&
  342. rel32_iter != rel32_target_rvas_.end()) {
  343. if (abs32_iter->first < rel32_iter->first) {
  344. ++abs32_iter;
  345. } else if (rel32_iter->first < abs32_iter->first) {
  346. ++rel32_iter;
  347. } else {
  348. ++common;
  349. ++abs32_iter;
  350. ++rel32_iter;
  351. }
  352. }
  353. VLOG(1) << "common " << common;
  354. #endif
  355. return true;
  356. }
  357. RvaVisitor* DisassemblerWin32::CreateAbs32TargetRvaVisitor() {
  358. return new RvaVisitor_Abs32(abs32_locations_, *this);
  359. }
  360. RvaVisitor* DisassemblerWin32::CreateRel32TargetRvaVisitor() {
  361. return new RvaVisitor_Rel32(rel32_locations_, *this);
  362. }
  363. void DisassemblerWin32::RemoveUnusedRel32Locations(
  364. AssemblyProgram* program) {
  365. auto cond = [this, program](RVA rva) -> bool {
  366. // + 4 since offset is relative to start of next instruction.
  367. RVA target_rva = rva + 4 + Read32LittleEndian(RVAToPointer(rva));
  368. return program->FindRel32Label(target_rva) == nullptr;
  369. };
  370. rel32_locations_.erase(
  371. std::remove_if(rel32_locations_.begin(), rel32_locations_.end(), cond),
  372. rel32_locations_.end());
  373. }
  374. InstructionGenerator DisassemblerWin32::GetInstructionGenerator(
  375. AssemblyProgram* program) {
  376. return base::BindRepeating(&DisassemblerWin32::ParseFile,
  377. base::Unretained(this), program);
  378. }
  379. CheckBool DisassemblerWin32::ParseFile(AssemblyProgram* program,
  380. InstructionReceptor* receptor) const {
  381. // Walk all the bytes in the file, whether or not in a section.
  382. FileOffset file_offset = 0;
  383. while (file_offset < length()) {
  384. const Section* section = FindNextSection(file_offset);
  385. if (section == nullptr) {
  386. // No more sections. There should not be extra stuff following last
  387. // section.
  388. // ParseNonSectionFileRegion(file_offset, pe_info().length(), receptor);
  389. break;
  390. }
  391. if (file_offset < section->file_offset_of_raw_data) {
  392. FileOffset section_start_offset = section->file_offset_of_raw_data;
  393. if (!ParseNonSectionFileRegion(file_offset, section_start_offset,
  394. receptor)) {
  395. return false;
  396. }
  397. file_offset = section_start_offset;
  398. }
  399. FileOffset end = file_offset + section->size_of_raw_data;
  400. if (!ParseFileRegion(section, file_offset, end, program, receptor))
  401. return false;
  402. file_offset = end;
  403. }
  404. #if COURGETTE_HISTOGRAM_TARGETS
  405. HistogramTargets("abs32 relocs", abs32_target_rvas_);
  406. HistogramTargets("rel32 relocs", rel32_target_rvas_);
  407. #endif
  408. return true;
  409. }
  410. CheckBool DisassemblerWin32::ParseNonSectionFileRegion(
  411. FileOffset start_file_offset,
  412. FileOffset end_file_offset,
  413. InstructionReceptor* receptor) const {
  414. if (incomplete_disassembly_)
  415. return true;
  416. if (end_file_offset > start_file_offset) {
  417. if (!receptor->EmitMultipleBytes(FileOffsetToPointer(start_file_offset),
  418. end_file_offset - start_file_offset)) {
  419. return false;
  420. }
  421. }
  422. return true;
  423. }
  424. CheckBool DisassemblerWin32::ParseFileRegion(
  425. const Section* section,
  426. FileOffset start_file_offset,
  427. FileOffset end_file_offset,
  428. AssemblyProgram* program,
  429. InstructionReceptor* receptor) const {
  430. RVA relocs_start_rva = base_relocation_table().address_;
  431. const uint8_t* start_pointer = FileOffsetToPointer(start_file_offset);
  432. const uint8_t* end_pointer = FileOffsetToPointer(end_file_offset);
  433. RVA start_rva = FileOffsetToRVA(start_file_offset);
  434. RVA end_rva = start_rva + section->virtual_size;
  435. const int kVAWidth = AbsVAWidth();
  436. // Quick way to convert from Pointer to RVA within a single Section is to
  437. // subtract 'pointer_to_rva'.
  438. const uint8_t* const adjust_pointer_to_rva = start_pointer - start_rva;
  439. std::vector<RVA>::const_iterator rel32_pos = rel32_locations_.begin();
  440. std::vector<RVA>::const_iterator abs32_pos = abs32_locations_.begin();
  441. if (!receptor->EmitOrigin(start_rva))
  442. return false;
  443. const uint8_t* p = start_pointer;
  444. while (p < end_pointer) {
  445. RVA current_rva = static_cast<RVA>(p - adjust_pointer_to_rva);
  446. // The base relocation table is usually in the .relocs section, but it could
  447. // actually be anywhere. Make sure we skip it because we will regenerate it
  448. // during assembly.
  449. if (current_rva == relocs_start_rva) {
  450. if (!receptor->EmitPeRelocs())
  451. return false;
  452. uint32_t relocs_size = base_relocation_table().size_;
  453. if (relocs_size) {
  454. p += relocs_size;
  455. continue;
  456. }
  457. }
  458. while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva)
  459. ++abs32_pos;
  460. if (abs32_pos != abs32_locations_.end() && *abs32_pos == current_rva) {
  461. RVA target_rva = PointerToTargetRVA(p);
  462. DCHECK_NE(kNoRVA, target_rva);
  463. // TODO(sra): target could be Label+offset. It is not clear how to guess
  464. // which it might be. We assume offset==0.
  465. Label* label = program->FindAbs32Label(target_rva);
  466. DCHECK(label);
  467. if (!EmitAbs(label, receptor))
  468. return false;
  469. p += kVAWidth;
  470. continue;
  471. }
  472. while (rel32_pos != rel32_locations_.end() && *rel32_pos < current_rva)
  473. ++rel32_pos;
  474. if (rel32_pos != rel32_locations_.end() && *rel32_pos == current_rva) {
  475. // + 4 since offset is relative to start of next instruction.
  476. RVA target_rva = current_rva + 4 + Read32LittleEndian(p);
  477. Label* label = program->FindRel32Label(target_rva);
  478. DCHECK(label);
  479. if (!receptor->EmitRel32(label))
  480. return false;
  481. p += 4;
  482. continue;
  483. }
  484. if (incomplete_disassembly_) {
  485. if ((abs32_pos == abs32_locations_.end() || end_rva <= *abs32_pos) &&
  486. (rel32_pos == rel32_locations_.end() || end_rva <= *rel32_pos) &&
  487. (end_rva <= relocs_start_rva || current_rva >= relocs_start_rva)) {
  488. // No more relocs in this section, don't bother encoding bytes.
  489. break;
  490. }
  491. }
  492. if (!receptor->EmitSingleByte(*p))
  493. return false;
  494. p += 1;
  495. }
  496. return true;
  497. }
  498. #if COURGETTE_HISTOGRAM_TARGETS
  499. // Histogram is printed to std::cout. It is purely for debugging the algorithm
  500. // and is only enabled manually in 'exploration' builds. I don't want to add
  501. // command-line configuration for this feature because this code has to be
  502. // small, which means compiled-out.
  503. void DisassemblerWin32::HistogramTargets(const char* kind,
  504. const std::map<RVA, int>& map) const {
  505. int total = 0;
  506. std::map<int, std::vector<RVA>> h;
  507. for (std::map<RVA, int>::const_iterator p = map.begin(); p != map.end();
  508. ++p) {
  509. h[p->second].push_back(p->first);
  510. total += p->second;
  511. }
  512. std::cout << total << " " << kind << " to " << map.size() << " unique targets"
  513. << std::endl;
  514. std::cout << "indegree: #targets-with-indegree (example)" << std::endl;
  515. const int kFirstN = 15;
  516. bool someSkipped = false;
  517. int index = 0;
  518. for (std::map<int, std::vector<RVA>>::reverse_iterator p = h.rbegin();
  519. p != h.rend(); ++p) {
  520. ++index;
  521. if (index <= kFirstN || p->first <= 3) {
  522. if (someSkipped) {
  523. std::cout << "..." << std::endl;
  524. }
  525. size_t count = p->second.size();
  526. std::cout << std::dec << p->first << ": " << count;
  527. if (count <= 2) {
  528. for (size_t i = 0; i < count; ++i)
  529. std::cout << " " << DescribeRVA(p->second[i]);
  530. }
  531. std::cout << std::endl;
  532. someSkipped = false;
  533. } else {
  534. someSkipped = true;
  535. }
  536. }
  537. }
  538. #endif // COURGETTE_HISTOGRAM_TARGETS
  539. // DescribeRVA is for debugging only. I would put it under #ifdef DEBUG except
  540. // that during development I'm finding I need to call it when compiled in
  541. // Release mode. Hence:
  542. // TODO(sra): make this compile only for debug mode.
  543. std::string DisassemblerWin32::DescribeRVA(RVA rva) const {
  544. const Section* section = RVAToSection(rva);
  545. std::ostringstream s;
  546. s << std::hex << rva;
  547. if (section) {
  548. s << " (";
  549. s << SectionName(section) << "+" << std::hex
  550. << (rva - section->virtual_address) << ")";
  551. }
  552. return s.str();
  553. }
  554. const Section* DisassemblerWin32::FindNextSection(
  555. FileOffset file_offset) const {
  556. const Section* best = nullptr;
  557. for (int i = 0; i < number_of_sections_; ++i) {
  558. const Section* section = &sections_[i];
  559. if (section->size_of_raw_data > 0) { // i.e. has data in file.
  560. if (file_offset <= section->file_offset_of_raw_data) {
  561. if (best == nullptr ||
  562. section->file_offset_of_raw_data < best->file_offset_of_raw_data) {
  563. best = section;
  564. }
  565. }
  566. }
  567. }
  568. return best;
  569. }
  570. bool DisassemblerWin32::ReadDataDirectory(int index,
  571. ImageDataDirectory* directory) {
  572. if (index < number_of_data_directories_) {
  573. FileOffset file_offset = index * 8 + RelativeOffsetOfDataDirectories();
  574. if (file_offset >= size_of_optional_header_)
  575. return Bad("Number of data directories inconsistent");
  576. const uint8_t* data_directory = optional_header_ + file_offset;
  577. if (data_directory < start() || data_directory + 8 >= end())
  578. return Bad("Data directory outside image");
  579. RVA rva = ReadU32(data_directory, 0);
  580. size_t size = ReadU32(data_directory, 4);
  581. if (size > size_of_image_)
  582. return Bad("Data directory size too big");
  583. // TODO(sra): validate RVA.
  584. directory->address_ = rva;
  585. directory->size_ = static_cast<uint32_t>(size);
  586. return true;
  587. } else {
  588. directory->address_ = 0;
  589. directory->size_ = 0;
  590. return true;
  591. }
  592. }
  593. } // namespace courgette