Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(148)

Side by Side Diff: courgette/disassembler_win32_x86.cc

Issue 8166013: Further refactoring, move ImageInfo into Disassembler/DisassemblerWin32X86. (Closed) Base URL: http://git.chromium.org/git/chromium.git@trunk
Patch Set: Rebase over other changes, fix nit. Created 9 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « courgette/disassembler_win32_x86.h ('k') | courgette/disassembler_win32_x86_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "courgette/disassembler_win32_x86.h" 5 #include "courgette/disassembler_win32_x86.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <string> 8 #include <string>
9 #include <vector> 9 #include <vector>
10 10
11 #include "base/basictypes.h" 11 #include "base/basictypes.h"
12 #include "base/logging.h" 12 #include "base/logging.h"
13 13
14 #include "courgette/assembly_program.h" 14 #include "courgette/assembly_program.h"
15 #include "courgette/courgette.h" 15 #include "courgette/courgette.h"
16 #include "courgette/encoded_program.h" 16 #include "courgette/encoded_program.h"
17 #include "courgette/image_info.h"
18 17
19 // COURGETTE_HISTOGRAM_TARGETS prints out a histogram of how frequently 18 // COURGETTE_HISTOGRAM_TARGETS prints out a histogram of how frequently
20 // different target addresses are referenced. Purely for debugging. 19 // different target addresses are referenced. Purely for debugging.
21 #define COURGETTE_HISTOGRAM_TARGETS 0 20 #define COURGETTE_HISTOGRAM_TARGETS 0
22 21
23 namespace courgette { 22 namespace courgette {
24 23
25 DisassemblerWin32X86::DisassemblerWin32X86(PEInfo* pe_info) 24 DisassemblerWin32X86::DisassemblerWin32X86(const void* start, size_t length)
26 : pe_info_(pe_info), 25 : Disassembler(start, length),
27 incomplete_disassembly_(false) { 26 incomplete_disassembly_(false),
27 is_PE32_plus_(false),
28 optional_header_(NULL),
29 size_of_optional_header_(0),
30 offset_of_data_directories_(0),
31 machine_type_(0),
32 number_of_sections_(0),
33 sections_(NULL),
34 has_text_section_(false),
35 size_of_code_(0),
36 size_of_initialized_data_(0),
37 size_of_uninitialized_data_(0),
38 base_of_code_(0),
39 base_of_data_(0),
40 image_base_(0),
41 size_of_image_(0),
42 number_of_data_directories_(0) {
43 }
44
45 // ParseHeader attempts to match up the buffer with the Windows data
46 // structures that exist within a Windows 'Portable Executable' format file.
47 // Returns 'true' if the buffer matches, and 'false' if the data looks
48 // suspicious. Rather than try to 'map' the buffer to the numerous windows
49 // structures, we extract the information we need into the courgette::PEInfo
50 // structure.
51 //
52 bool DisassemblerWin32X86::ParseHeader() {
53 if (length() < kOffsetOfFileAddressOfNewExeHeader + 4 /*size*/)
54 return Bad("Too small");
55
56 // Have 'MZ' magic for a DOS header?
57 if (start()[0] != 'M' || start()[1] != 'Z')
58 return Bad("Not MZ");
59
60 // offset from DOS header to PE header is stored in DOS header.
61 uint32 offset = ReadU32(start(),
62 kOffsetOfFileAddressOfNewExeHeader);
63
64 if (offset >= length())
65 return Bad("Bad offset to PE header");
66
67 const uint8* const pe_header = OffsetToPointer(offset);
68 const size_t kMinPEHeaderSize = 4 /*signature*/ + kSizeOfCoffHeader;
69 if (pe_header <= start() ||
70 pe_header >= end() - kMinPEHeaderSize)
71 return Bad("Bad offset to PE header");
72
73 if (offset % 8 != 0)
74 return Bad("Misaligned PE header");
75
76 // The 'PE' header is an IMAGE_NT_HEADERS structure as defined in WINNT.H.
77 // See http://msdn.microsoft.com/en-us/library/ms680336(VS.85).aspx
78 //
79 // The first field of the IMAGE_NT_HEADERS is the signature.
80 if (!(pe_header[0] == 'P' &&
81 pe_header[1] == 'E' &&
82 pe_header[2] == 0 &&
83 pe_header[3] == 0))
84 return Bad("no PE signature");
85
86 // The second field of the IMAGE_NT_HEADERS is the COFF header.
87 // The COFF header is also called an IMAGE_FILE_HEADER
88 // http://msdn.microsoft.com/en-us/library/ms680313(VS.85).aspx
89 const uint8* const coff_header = pe_header + 4;
90 machine_type_ = ReadU16(coff_header, 0);
91 number_of_sections_ = ReadU16(coff_header, 2);
92 size_of_optional_header_ = ReadU16(coff_header, 16);
93
94 // The rest of the IMAGE_NT_HEADERS is the IMAGE_OPTIONAL_HEADER(32|64)
95 const uint8* const optional_header = coff_header + kSizeOfCoffHeader;
96 optional_header_ = optional_header;
97
98 if (optional_header + size_of_optional_header_ >= end())
99 return Bad("optional header past end of file");
100
101 // Check we can read the magic.
102 if (size_of_optional_header_ < 2)
103 return Bad("optional header no magic");
104
105 uint16 magic = ReadU16(optional_header, 0);
106
107 if (magic == kImageNtOptionalHdr32Magic) {
108 is_PE32_plus_ = false;
109 offset_of_data_directories_ =
110 kOffsetOfDataDirectoryFromImageOptionalHeader32;
111 } else if (magic == kImageNtOptionalHdr64Magic) {
112 is_PE32_plus_ = true;
113 offset_of_data_directories_ =
114 kOffsetOfDataDirectoryFromImageOptionalHeader64;
115 } else {
116 return Bad("unrecognized magic");
117 }
118
119 // Check that we can read the rest of the the fixed fields. Data directories
120 // directly follow the fixed fields of the IMAGE_OPTIONAL_HEADER.
121 if (size_of_optional_header_ < offset_of_data_directories_)
122 return Bad("optional header too short");
123
124 // The optional header is either an IMAGE_OPTIONAL_HEADER32 or
125 // IMAGE_OPTIONAL_HEADER64
126 // http://msdn.microsoft.com/en-us/library/ms680339(VS.85).aspx
127 //
128 // Copy the fields we care about.
129 size_of_code_ = ReadU32(optional_header, 4);
130 size_of_initialized_data_ = ReadU32(optional_header, 8);
131 size_of_uninitialized_data_ = ReadU32(optional_header, 12);
132 base_of_code_ = ReadU32(optional_header, 20);
133 if (is_PE32_plus_) {
134 base_of_data_ = 0;
135 image_base_ = ReadU64(optional_header, 24);
136 } else {
137 base_of_data_ = ReadU32(optional_header, 24);
138 image_base_ = ReadU32(optional_header, 28);
139 }
140 size_of_image_ = ReadU32(optional_header, 56);
141 number_of_data_directories_ =
142 ReadU32(optional_header, (is_PE32_plus_ ? 108 : 92));
143
144 if (size_of_code_ >= length() ||
145 size_of_initialized_data_ >= length() ||
146 size_of_code_ + size_of_initialized_data_ >= length()) {
147 // This validation fires on some perfectly fine executables.
148 // return Bad("code or initialized data too big");
149 }
150
151 // TODO(sra): we can probably get rid of most of the data directories.
152 bool b = true;
153 // 'b &= ...' could be short circuit 'b = b && ...' but it is not necessary
154 // for correctness and it compiles smaller this way.
155 b &= ReadDataDirectory(0, &export_table_);
156 b &= ReadDataDirectory(1, &import_table_);
157 b &= ReadDataDirectory(2, &resource_table_);
158 b &= ReadDataDirectory(3, &exception_table_);
159 b &= ReadDataDirectory(5, &base_relocation_table_);
160 b &= ReadDataDirectory(11, &bound_import_table_);
161 b &= ReadDataDirectory(12, &import_address_table_);
162 b &= ReadDataDirectory(13, &delay_import_descriptor_);
163 b &= ReadDataDirectory(14, &clr_runtime_header_);
164 if (!b) {
165 return Bad("malformed data directory");
166 }
167
168 // Sections follow the optional header.
169 sections_ =
170 reinterpret_cast<const Section*>(optional_header +
171 size_of_optional_header_);
172 size_t detected_length = 0;
173
174 for (int i = 0; i < number_of_sections_; ++i) {
175 const Section* section = &sections_[i];
176
177 // TODO(sra): consider using the 'characteristics' field of the section
178 // header to see if the section contains instructions.
179 if (memcmp(section->name, ".text", 6) == 0)
180 has_text_section_ = true;
181
182 uint32 section_end =
183 section->file_offset_of_raw_data + section->size_of_raw_data;
184 if (section_end > detected_length)
185 detected_length = section_end;
186 }
187
188 // Pretend our in-memory copy is only as long as our detected length.
189 ReduceLength(detected_length);
190
191 if (!is_32bit()) {
192 return Bad("64 bit executables are not yet supported");
193 }
194
195 if (!has_text_section()) {
196 return Bad("Resource-only executables are not yet supported");
197 }
198
199 return Good();
28 } 200 }
29 201
30 bool DisassemblerWin32X86::Disassemble(AssemblyProgram* target) { 202 bool DisassemblerWin32X86::Disassemble(AssemblyProgram* target) {
31 if (!pe_info().ok()) 203 if (!ok())
32 return false; 204 return false;
33 205
34 target->set_image_base(pe_info().image_base()); 206 target->set_image_base(image_base());
35 207
36 if (!ParseAbs32Relocs()) 208 if (!ParseAbs32Relocs())
37 return false; 209 return false;
38 210
39 ParseRel32RelocsFromSections(); 211 ParseRel32RelocsFromSections();
40 212
41 if (!ParseFile(target)) 213 if (!ParseFile(target))
42 return false; 214 return false;
43 215
44 target->DefaultAssignIndexes(); 216 target->DefaultAssignIndexes();
45 217
46 return true; 218 return true;
47 } 219 }
48 220
49 static uint32 Read32LittleEndian(const void* address) { 221 ////////////////////////////////////////////////////////////////////////////////
50 return *reinterpret_cast<const uint32*>(address); 222
223 bool DisassemblerWin32X86::ParseRelocs(std::vector<RVA> *relocs) {
224 relocs->clear();
225
226 size_t relocs_size = base_relocation_table_.size_;
227 if (relocs_size == 0)
228 return true;
229
230 // The format of the base relocation table is a sequence of variable sized
231 // IMAGE_BASE_RELOCATION blocks. Search for
232 // "The format of the base relocation data is somewhat quirky"
233 // at http://msdn.microsoft.com/en-us/library/ms809762.aspx
234
235 const uint8* relocs_start = RVAToPointer(base_relocation_table_.address_);
236 const uint8* relocs_end = relocs_start + relocs_size;
237
238 // Make sure entire base relocation table is within the buffer.
239 if (relocs_start < start() ||
240 relocs_start >= end() ||
241 relocs_end <= start() ||
242 relocs_end > end()) {
243 return Bad(".relocs outside image");
244 }
245
246 const uint8* block = relocs_start;
247
248 // Walk the variable sized blocks.
249 while (block + 8 < relocs_end) {
250 RVA page_rva = ReadU32(block, 0);
251 uint32 size = ReadU32(block, 4);
252 if (size < 8 || // Size includes header ...
253 size % 4 != 0) // ... and is word aligned.
254 return Bad("unreasonable relocs block");
255
256 const uint8* end_entries = block + size;
257
258 if (end_entries <= block ||
259 end_entries <= start() ||
260 end_entries > end())
261 return Bad(".relocs block outside image");
262
263 // Walk through the two-byte entries.
264 for (const uint8* p = block + 8; p < end_entries; p += 2) {
265 uint16 entry = ReadU16(p, 0);
266 int type = entry >> 12;
267 int offset = entry & 0xFFF;
268
269 RVA rva = page_rva + offset;
270 if (type == 3) { // IMAGE_REL_BASED_HIGHLOW
271 relocs->push_back(rva);
272 } else if (type == 0) { // IMAGE_REL_BASED_ABSOLUTE
273 // Ignore, used as padding.
274 } else {
275 // Does not occur in Windows x86 executables.
276 return Bad("unknown type of reloc");
277 }
278 }
279
280 block += size;
281 }
282
283 std::sort(relocs->begin(), relocs->end());
284
285 return true;
286 }
287
288 const Section* DisassemblerWin32X86::RVAToSection(RVA rva) const {
289 for (int i = 0; i < number_of_sections_; i++) {
290 const Section* section = &sections_[i];
291 uint32 offset = rva - section->virtual_address;
292 if (offset < section->virtual_size) {
293 return section;
294 }
295 }
296 return NULL;
297 }
298
299 int DisassemblerWin32X86::RVAToFileOffset(RVA rva) const {
300 const Section* section = RVAToSection(rva);
301 if (section) {
302 uint32 offset = rva - section->virtual_address;
303 if (offset < section->size_of_raw_data) {
304 return section->file_offset_of_raw_data + offset;
305 } else {
306 return kNoOffset; // In section but not in file (e.g. uninit data).
307 }
308 }
309
310 // Small RVA values point into the file header in the loaded image.
311 // RVA 0 is the module load address which Windows uses as the module handle.
312 // RVA 2 sometimes occurs, I'm not sure what it is, but it would map into the
313 // DOS header.
314 if (rva == 0 || rva == 2)
315 return rva;
316
317 NOTREACHED();
318 return kNoOffset;
319 }
320
321 const uint8* DisassemblerWin32X86::RVAToPointer(RVA rva) const {
322 int file_offset = RVAToFileOffset(rva);
323 if (file_offset == kNoOffset)
324 return NULL;
325 else
326 return OffsetToPointer(file_offset);
327 }
328
329 std::string DisassemblerWin32X86::SectionName(const Section* section) {
330 if (section == NULL)
331 return "<none>";
332 char name[9];
333 memcpy(name, section->name, 8);
334 name[8] = '\0'; // Ensure termination.
335 return name;
336 }
337
338 CheckBool DisassemblerWin32X86::ParseFile(AssemblyProgram* program) {
339 bool ok = true;
340 // Walk all the bytes in the file, whether or not in a section.
341 uint32 file_offset = 0;
342 while (ok && file_offset < length()) {
343 const Section* section = FindNextSection(file_offset);
344 if (section == NULL) {
345 // No more sections. There should not be extra stuff following last
346 // section.
347 // ParseNonSectionFileRegion(file_offset, pe_info().length(), program);
348 break;
349 }
350 if (file_offset < section->file_offset_of_raw_data) {
351 uint32 section_start_offset = section->file_offset_of_raw_data;
352 ok = ParseNonSectionFileRegion(file_offset, section_start_offset,
353 program);
354 file_offset = section_start_offset;
355 }
356 if (ok) {
357 uint32 end = file_offset + section->size_of_raw_data;
358 ok = ParseFileRegion(section, file_offset, end, program);
359 file_offset = end;
360 }
361 }
362
363 #if COURGETTE_HISTOGRAM_TARGETS
364 HistogramTargets("abs32 relocs", abs32_target_rvas_);
365 HistogramTargets("rel32 relocs", rel32_target_rvas_);
366 #endif
367
368 return ok;
51 } 369 }
52 370
53 bool DisassemblerWin32X86::ParseAbs32Relocs() { 371 bool DisassemblerWin32X86::ParseAbs32Relocs() {
54 abs32_locations_.clear(); 372 abs32_locations_.clear();
55 if (!pe_info().ParseRelocs(&abs32_locations_)) 373 if (!ParseRelocs(&abs32_locations_))
56 return false; 374 return false;
57 375
58 std::sort(abs32_locations_.begin(), abs32_locations_.end()); 376 std::sort(abs32_locations_.begin(), abs32_locations_.end());
59 377
60 #if COURGETTE_HISTOGRAM_TARGETS 378 #if COURGETTE_HISTOGRAM_TARGETS
61 for (size_t i = 0; i < abs32_locations_.size(); ++i) { 379 for (size_t i = 0; i < abs32_locations_.size(); ++i) {
62 RVA rva = abs32_locations_[i]; 380 RVA rva = abs32_locations_[i];
63 // The 4 bytes at the relocation are a reference to some address. 381 // The 4 bytes at the relocation are a reference to some address.
64 uint32 target_address = Read32LittleEndian(pe_info().RVAToPointer(rva)); 382 uint32 target_address = Read32LittleEndian(RVAToPointer(rva));
65 ++abs32_target_rvas_[target_address - pe_info().image_base()]; 383 ++abs32_target_rvas_[target_address - image_base()];
66 } 384 }
67 #endif 385 #endif
68 return true; 386 return true;
69 } 387 }
70 388
71 void DisassemblerWin32X86::ParseRel32RelocsFromSections() { 389 void DisassemblerWin32X86::ParseRel32RelocsFromSections() {
72 uint32 file_offset = 0; 390 uint32 file_offset = 0;
73 while (file_offset < pe_info().length()) { 391 while (file_offset < length()) {
74 const Section* section = pe_info().FindNextSection(file_offset); 392 const Section* section = FindNextSection(file_offset);
75 if (section == NULL) 393 if (section == NULL)
76 break; 394 break;
77 if (file_offset < section->file_offset_of_raw_data) 395 if (file_offset < section->file_offset_of_raw_data)
78 file_offset = section->file_offset_of_raw_data; 396 file_offset = section->file_offset_of_raw_data;
79 ParseRel32RelocsFromSection(section); 397 ParseRel32RelocsFromSection(section);
80 file_offset += section->size_of_raw_data; 398 file_offset += section->size_of_raw_data;
81 } 399 }
82 std::sort(rel32_locations_.begin(), rel32_locations_.end()); 400 std::sort(rel32_locations_.begin(), rel32_locations_.end());
83 401
84 #if COURGETTE_HISTOGRAM_TARGETS 402 #if COURGETTE_HISTOGRAM_TARGETS
(...skipping 22 matching lines...) Expand all
107 } 425 }
108 426
109 void DisassemblerWin32X86::ParseRel32RelocsFromSection(const Section* section) { 427 void DisassemblerWin32X86::ParseRel32RelocsFromSection(const Section* section) {
110 // TODO(sra): use characteristic. 428 // TODO(sra): use characteristic.
111 bool isCode = strcmp(section->name, ".text") == 0; 429 bool isCode = strcmp(section->name, ".text") == 0;
112 if (!isCode) 430 if (!isCode)
113 return; 431 return;
114 432
115 uint32 start_file_offset = section->file_offset_of_raw_data; 433 uint32 start_file_offset = section->file_offset_of_raw_data;
116 uint32 end_file_offset = start_file_offset + section->size_of_raw_data; 434 uint32 end_file_offset = start_file_offset + section->size_of_raw_data;
117 RVA relocs_start_rva = pe_info().base_relocation_table().address_; 435 RVA relocs_start_rva = base_relocation_table().address_;
118 436
119 const uint8* start_pointer = pe_info().FileOffsetToPointer(start_file_offset); 437 const uint8* start_pointer = OffsetToPointer(start_file_offset);
120 const uint8* end_pointer = pe_info().FileOffsetToPointer(end_file_offset); 438 const uint8* end_pointer = OffsetToPointer(end_file_offset);
121 439
122 RVA start_rva = pe_info().FileOffsetToRVA(start_file_offset); 440 RVA start_rva = FileOffsetToRVA(start_file_offset);
123 RVA end_rva = start_rva + section->virtual_size; 441 RVA end_rva = start_rva + section->virtual_size;
124 442
125 // Quick way to convert from Pointer to RVA within a single Section is to 443 // Quick way to convert from Pointer to RVA within a single Section is to
126 // subtract 'pointer_to_rva'. 444 // subtract 'pointer_to_rva'.
127 const uint8* const adjust_pointer_to_rva = start_pointer - start_rva; 445 const uint8* const adjust_pointer_to_rva = start_pointer - start_rva;
128 446
129 std::vector<RVA>::iterator abs32_pos = abs32_locations_.begin(); 447 std::vector<RVA>::iterator abs32_pos = abs32_locations_.begin();
130 448
131 // Find the rel32 relocations. 449 // Find the rel32 relocations.
132 const uint8* p = start_pointer; 450 const uint8* p = start_pointer;
133 while (p < end_pointer) { 451 while (p < end_pointer) {
134 RVA current_rva = static_cast<RVA>(p - adjust_pointer_to_rva); 452 RVA current_rva = static_cast<RVA>(p - adjust_pointer_to_rva);
135 if (current_rva == relocs_start_rva) { 453 if (current_rva == relocs_start_rva) {
136 uint32 relocs_size = pe_info().base_relocation_table().size_; 454 uint32 relocs_size = base_relocation_table().size_;
137 if (relocs_size) { 455 if (relocs_size) {
138 p += relocs_size; 456 p += relocs_size;
139 continue; 457 continue;
140 } 458 }
141 } 459 }
142 460
143 //while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva) 461 //while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva)
144 // ++abs32_pos; 462 // ++abs32_pos;
145 463
146 // Heuristic discovery of rel32 locations in instruction stream: are the 464 // Heuristic discovery of rel32 locations in instruction stream: are the
(...skipping 25 matching lines...) Expand all
172 // Beginning of abs32 reloc is before end of rel32 reloc so they 490 // Beginning of abs32 reloc is before end of rel32 reloc so they
173 // overlap. Skip four bytes past the abs32 reloc. 491 // overlap. Skip four bytes past the abs32 reloc.
174 p += (*abs32_pos + 4) - current_rva; 492 p += (*abs32_pos + 4) - current_rva;
175 continue; 493 continue;
176 } 494 }
177 } 495 }
178 496
179 RVA target_rva = rel32_rva + 4 + Read32LittleEndian(rel32); 497 RVA target_rva = rel32_rva + 4 + Read32LittleEndian(rel32);
180 // To be valid, rel32 target must be within image, and within this 498 // To be valid, rel32 target must be within image, and within this
181 // section. 499 // section.
182 if (pe_info().IsValidRVA(target_rva) && 500 if (IsValidRVA(target_rva) &&
183 start_rva <= target_rva && target_rva < end_rva) { 501 start_rva <= target_rva && target_rva < end_rva) {
184 rel32_locations_.push_back(rel32_rva); 502 rel32_locations_.push_back(rel32_rva);
185 #if COURGETTE_HISTOGRAM_TARGETS 503 #if COURGETTE_HISTOGRAM_TARGETS
186 ++rel32_target_rvas_[target_rva]; 504 ++rel32_target_rvas_[target_rva];
187 #endif 505 #endif
188 p += 4; 506 p += 4;
189 continue; 507 continue;
190 } 508 }
191 } 509 }
192 p += 1; 510 p += 1;
193 } 511 }
194 } 512 }
195 513
196 CheckBool DisassemblerWin32X86::ParseFile(AssemblyProgram* program) {
197 bool ok = true;
198 // Walk all the bytes in the file, whether or not in a section.
199 uint32 file_offset = 0;
200 while (ok && file_offset < pe_info().length()) {
201 const Section* section = pe_info().FindNextSection(file_offset);
202 if (section == NULL) {
203 // No more sections. There should not be extra stuff following last
204 // section.
205 // ParseNonSectionFileRegion(file_offset, pe_info().length(), program);
206 break;
207 }
208 if (file_offset < section->file_offset_of_raw_data) {
209 uint32 section_start_offset = section->file_offset_of_raw_data;
210 ok = ParseNonSectionFileRegion(file_offset, section_start_offset,
211 program);
212 file_offset = section_start_offset;
213 }
214 if (ok) {
215 uint32 end = file_offset + section->size_of_raw_data;
216 ok = ParseFileRegion(section, file_offset, end, program);
217 file_offset = end;
218 }
219 }
220
221 #if COURGETTE_HISTOGRAM_TARGETS
222 HistogramTargets("abs32 relocs", abs32_target_rvas_);
223 HistogramTargets("rel32 relocs", rel32_target_rvas_);
224 #endif
225
226 return ok;
227 }
228
229 CheckBool DisassemblerWin32X86::ParseNonSectionFileRegion( 514 CheckBool DisassemblerWin32X86::ParseNonSectionFileRegion(
230 uint32 start_file_offset, 515 uint32 start_file_offset,
231 uint32 end_file_offset, 516 uint32 end_file_offset,
232 AssemblyProgram* program) { 517 AssemblyProgram* program) {
233 if (incomplete_disassembly_) 518 if (incomplete_disassembly_)
234 return true; 519 return true;
235 520
236 const uint8* start = pe_info().FileOffsetToPointer(start_file_offset); 521 const uint8* start = OffsetToPointer(start_file_offset);
237 const uint8* end = pe_info().FileOffsetToPointer(end_file_offset); 522 const uint8* end = OffsetToPointer(end_file_offset);
238 523
239 const uint8* p = start; 524 const uint8* p = start;
240 525
241 bool ok = true; 526 bool ok = true;
242 while (p < end && ok) { 527 while (p < end && ok) {
243 ok = program->EmitByteInstruction(*p); 528 ok = program->EmitByteInstruction(*p);
244 ++p; 529 ++p;
245 } 530 }
246 531
247 return ok; 532 return ok;
248 } 533 }
249 534
250 CheckBool DisassemblerWin32X86::ParseFileRegion( 535 CheckBool DisassemblerWin32X86::ParseFileRegion(
251 const Section* section, 536 const Section* section,
252 uint32 start_file_offset, uint32 end_file_offset, 537 uint32 start_file_offset, uint32 end_file_offset,
253 AssemblyProgram* program) { 538 AssemblyProgram* program) {
254 RVA relocs_start_rva = pe_info().base_relocation_table().address_; 539 RVA relocs_start_rva = base_relocation_table().address_;
255 540
256 const uint8* start_pointer = pe_info().FileOffsetToPointer(start_file_offset); 541 const uint8* start_pointer = OffsetToPointer(start_file_offset);
257 const uint8* end_pointer = pe_info().FileOffsetToPointer(end_file_offset); 542 const uint8* end_pointer = OffsetToPointer(end_file_offset);
258 543
259 RVA start_rva = pe_info().FileOffsetToRVA(start_file_offset); 544 RVA start_rva = FileOffsetToRVA(start_file_offset);
260 RVA end_rva = start_rva + section->virtual_size; 545 RVA end_rva = start_rva + section->virtual_size;
261 546
262 // Quick way to convert from Pointer to RVA within a single Section is to 547 // Quick way to convert from Pointer to RVA within a single Section is to
263 // subtract 'pointer_to_rva'. 548 // subtract 'pointer_to_rva'.
264 const uint8* const adjust_pointer_to_rva = start_pointer - start_rva; 549 const uint8* const adjust_pointer_to_rva = start_pointer - start_rva;
265 550
266 std::vector<RVA>::iterator rel32_pos = rel32_locations_.begin(); 551 std::vector<RVA>::iterator rel32_pos = rel32_locations_.begin();
267 std::vector<RVA>::iterator abs32_pos = abs32_locations_.begin(); 552 std::vector<RVA>::iterator abs32_pos = abs32_locations_.begin();
268 553
269 bool ok = program->EmitOriginInstruction(start_rva); 554 bool ok = program->EmitOriginInstruction(start_rva);
270 555
271 const uint8* p = start_pointer; 556 const uint8* p = start_pointer;
272 557
273 while (ok && p < end_pointer) { 558 while (ok && p < end_pointer) {
274 RVA current_rva = static_cast<RVA>(p - adjust_pointer_to_rva); 559 RVA current_rva = static_cast<RVA>(p - adjust_pointer_to_rva);
275 560
276 // The base relocation table is usually in the .relocs section, but it could 561 // The base relocation table is usually in the .relocs section, but it could
277 // actually be anywhere. Make sure we skip it because we will regenerate it 562 // actually be anywhere. Make sure we skip it because we will regenerate it
278 // during assembly. 563 // during assembly.
279 if (current_rva == relocs_start_rva) { 564 if (current_rva == relocs_start_rva) {
280 ok = program->EmitMakeRelocsInstruction(); 565 ok = program->EmitMakeRelocsInstruction();
281 if (!ok) 566 if (!ok)
282 break; 567 break;
283 uint32 relocs_size = pe_info().base_relocation_table().size_; 568 uint32 relocs_size = base_relocation_table().size_;
284 if (relocs_size) { 569 if (relocs_size) {
285 p += relocs_size; 570 p += relocs_size;
286 continue; 571 continue;
287 } 572 }
288 } 573 }
289 574
290 while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva) 575 while (abs32_pos != abs32_locations_.end() && *abs32_pos < current_rva)
291 ++abs32_pos; 576 ++abs32_pos;
292 577
293 if (abs32_pos != abs32_locations_.end() && *abs32_pos == current_rva) { 578 if (abs32_pos != abs32_locations_.end() && *abs32_pos == current_rva) {
294 uint32 target_address = Read32LittleEndian(p); 579 uint32 target_address = Read32LittleEndian(p);
295 RVA target_rva = target_address - pe_info().image_base(); 580 RVA target_rva = target_address - image_base();
296 // TODO(sra): target could be Label+offset. It is not clear how to guess 581 // TODO(sra): target could be Label+offset. It is not clear how to guess
297 // which it might be. We assume offset==0. 582 // which it might be. We assume offset==0.
298 ok = program->EmitAbs32(program->FindOrMakeAbs32Label(target_rva)); 583 ok = program->EmitAbs32(program->FindOrMakeAbs32Label(target_rva));
299 if (!ok) 584 if (!ok)
300 break; 585 break;
301 p += 4; 586 p += 4;
302 continue; 587 continue;
303 } 588 }
304 589
305 while (rel32_pos != rel32_locations_.end() && *rel32_pos < current_rva) 590 while (rel32_pos != rel32_locations_.end() && *rel32_pos < current_rva)
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
356 ++p) { 641 ++p) {
357 ++index; 642 ++index;
358 if (index <= kFirstN || p->first <= 3) { 643 if (index <= kFirstN || p->first <= 3) {
359 if (someSkipped) { 644 if (someSkipped) {
360 std::cout << "..." << std::endl; 645 std::cout << "..." << std::endl;
361 } 646 }
362 size_t count = p->second.size(); 647 size_t count = p->second.size();
363 std::cout << std::dec << p->first << ": " << count; 648 std::cout << std::dec << p->first << ": " << count;
364 if (count <= 2) { 649 if (count <= 2) {
365 for (size_t i = 0; i < count; ++i) 650 for (size_t i = 0; i < count; ++i)
366 std::cout << " " << pe_info().DescribeRVA(p->second[i]); 651 std::cout << " " << DescribeRVA(p->second[i]);
367 } 652 }
368 std::cout << std::endl; 653 std::cout << std::endl;
369 someSkipped = false; 654 someSkipped = false;
370 } else { 655 } else {
371 someSkipped = true; 656 someSkipped = true;
372 } 657 }
373 } 658 }
374 } 659 }
375 #endif // COURGETTE_HISTOGRAM_TARGETS 660 #endif // COURGETTE_HISTOGRAM_TARGETS
376 661
662
663 // DescribeRVA is for debugging only. I would put it under #ifdef DEBUG except
664 // that during development I'm finding I need to call it when compiled in
665 // Release mode. Hence:
666 // TODO(sra): make this compile only for debug mode.
667 std::string DisassemblerWin32X86::DescribeRVA(RVA rva) const {
668 const Section* section = RVAToSection(rva);
669 std::ostringstream s;
670 s << std::hex << rva;
671 if (section) {
672 s << " (";
673 s << SectionName(section) << "+"
674 << std::hex << (rva - section->virtual_address)
675 << ")";
676 }
677 return s.str();
678 }
679
680 const Section* DisassemblerWin32X86::FindNextSection(uint32 fileOffset) const {
681 const Section* best = 0;
682 for (int i = 0; i < number_of_sections_; i++) {
683 const Section* section = &sections_[i];
684 if (section->size_of_raw_data > 0) { // i.e. has data in file.
685 if (fileOffset <= section->file_offset_of_raw_data) {
686 if (best == 0 ||
687 section->file_offset_of_raw_data < best->file_offset_of_raw_data) {
688 best = section;
689 }
690 }
691 }
692 }
693 return best;
694 }
695
696 RVA DisassemblerWin32X86::FileOffsetToRVA(uint32 file_offset) const {
697 for (int i = 0; i < number_of_sections_; i++) {
698 const Section* section = &sections_[i];
699 uint32 offset = file_offset - section->file_offset_of_raw_data;
700 if (offset < section->size_of_raw_data) {
701 return section->virtual_address + offset;
702 }
703 }
704 return 0;
705 }
706
707 bool DisassemblerWin32X86::ReadDataDirectory(
708 int index,
709 ImageDataDirectory* directory) {
710
711 if (index < number_of_data_directories_) {
712 size_t offset = index * 8 + offset_of_data_directories_;
713 if (offset >= size_of_optional_header_)
714 return Bad("number of data directories inconsistent");
715 const uint8* data_directory = optional_header_ + offset;
716 if (data_directory < start() ||
717 data_directory + 8 >= end())
718 return Bad("data directory outside image");
719 RVA rva = ReadU32(data_directory, 0);
720 size_t size = ReadU32(data_directory, 4);
721 if (size > size_of_image_)
722 return Bad("data directory size too big");
723
724 // TODO(sra): validate RVA.
725 directory->address_ = rva;
726 directory->size_ = static_cast<uint32>(size);
727 return true;
728 } else {
729 directory->address_ = 0;
730 directory->size_ = 0;
731 return true;
732 }
733 }
734
377 } // namespace courgette 735 } // namespace courgette
OLDNEW
« no previous file with comments | « courgette/disassembler_win32_x86.h ('k') | courgette/disassembler_win32_x86_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698