Release 1.2-rc6.
[wine/gsoc-2012-control.git] / tools / winedump / pe.c
blobc06db317acb7f8f2dd283f0e716ac1720d6cbc56
1 /*
2 * PE dumping utility
4 * Copyright 2001 Eric Pouech
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <time.h>
31 #ifdef HAVE_SYS_TYPES_H
32 # include <sys/types.h>
33 #endif
34 #ifdef HAVE_SYS_STAT_H
35 # include <sys/stat.h>
36 #endif
37 #ifdef HAVE_SYS_MMAN_H
38 #include <sys/mman.h>
39 #endif
40 #include <fcntl.h>
42 #define NONAMELESSUNION
43 #define NONAMELESSSTRUCT
44 #include "windef.h"
45 #include "winbase.h"
46 #include "winedump.h"
48 static const IMAGE_NT_HEADERS32* PE_nt_headers;
50 const char *get_machine_str(int mach)
52 switch (mach)
54 case IMAGE_FILE_MACHINE_UNKNOWN: return "Unknown";
55 case IMAGE_FILE_MACHINE_I860: return "i860";
56 case IMAGE_FILE_MACHINE_I386: return "i386";
57 case IMAGE_FILE_MACHINE_R3000: return "R3000";
58 case IMAGE_FILE_MACHINE_R4000: return "R4000";
59 case IMAGE_FILE_MACHINE_R10000: return "R10000";
60 case IMAGE_FILE_MACHINE_ALPHA: return "Alpha";
61 case IMAGE_FILE_MACHINE_POWERPC: return "PowerPC";
62 case IMAGE_FILE_MACHINE_AMD64: return "AMD64";
63 case IMAGE_FILE_MACHINE_IA64: return "IA64";
64 case IMAGE_FILE_MACHINE_ARM: return "ARM";
66 return "???";
69 static const void* RVA(unsigned long rva, unsigned long len)
71 IMAGE_SECTION_HEADER* sectHead;
72 int i;
74 if (rva == 0) return NULL;
76 sectHead = IMAGE_FIRST_SECTION(PE_nt_headers);
77 for (i = PE_nt_headers->FileHeader.NumberOfSections - 1; i >= 0; i--)
79 if (sectHead[i].VirtualAddress <= rva &&
80 rva + len <= (DWORD)sectHead[i].VirtualAddress + sectHead[i].SizeOfRawData)
82 /* return image import directory offset */
83 return PRD(sectHead[i].PointerToRawData + rva - sectHead[i].VirtualAddress, len);
87 return NULL;
90 static const IMAGE_NT_HEADERS32 *get_nt_header( void )
92 const IMAGE_DOS_HEADER *dos;
93 dos = PRD(0, sizeof(*dos));
94 if (!dos) return NULL;
95 return PRD(dos->e_lfanew, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER));
98 static int is_fake_dll( void )
100 static const char fakedll_signature[] = "Wine placeholder DLL";
101 const IMAGE_DOS_HEADER *dos;
103 dos = PRD(0, sizeof(*dos) + sizeof(fakedll_signature));
105 if (dos && dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
106 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
107 return FALSE;
110 static const void *get_dir_and_size(unsigned int idx, unsigned int *size)
112 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
114 const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
115 if (idx >= opt->NumberOfRvaAndSizes)
116 return NULL;
117 if(size)
118 *size = opt->DataDirectory[idx].Size;
119 return RVA(opt->DataDirectory[idx].VirtualAddress,
120 opt->DataDirectory[idx].Size);
122 else
124 const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
125 if (idx >= opt->NumberOfRvaAndSizes)
126 return NULL;
127 if(size)
128 *size = opt->DataDirectory[idx].Size;
129 return RVA(opt->DataDirectory[idx].VirtualAddress,
130 opt->DataDirectory[idx].Size);
134 static const void* get_dir(unsigned idx)
136 return get_dir_and_size(idx, 0);
139 static const char * const DirectoryNames[16] = {
140 "EXPORT", "IMPORT", "RESOURCE", "EXCEPTION",
141 "SECURITY", "BASERELOC", "DEBUG", "ARCHITECTURE",
142 "GLOBALPTR", "TLS", "LOAD_CONFIG", "Bound IAT",
143 "IAT", "Delay IAT", "CLR Header", ""
146 static const char *get_magic_type(WORD magic)
148 switch(magic) {
149 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
150 return "32bit";
151 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
152 return "64bit";
153 case IMAGE_ROM_OPTIONAL_HDR_MAGIC:
154 return "ROM";
156 return "???";
159 static inline void print_word(const char *title, WORD value)
161 printf(" %-34s 0x%-4X %u\n", title, value, value);
164 static inline void print_dword(const char *title, DWORD value)
166 printf(" %-34s 0x%-8x %u\n", title, value, value);
169 static inline void print_longlong(const char *title, ULONGLONG value)
171 printf(" %-34s 0x", title);
172 if(value >> 32)
173 printf("%lx%08lx\n", (unsigned long)(value >> 32), (unsigned long)value);
174 else
175 printf("%lx\n", (unsigned long)value);
178 static inline void print_ver(const char *title, BYTE major, BYTE minor)
180 printf(" %-34s %u.%02u\n", title, major, minor);
183 static inline void print_subsys(const char *title, WORD value)
185 const char *str;
186 switch (value)
188 default:
189 case IMAGE_SUBSYSTEM_UNKNOWN: str = "Unknown"; break;
190 case IMAGE_SUBSYSTEM_NATIVE: str = "Native"; break;
191 case IMAGE_SUBSYSTEM_WINDOWS_GUI: str = "Windows GUI"; break;
192 case IMAGE_SUBSYSTEM_WINDOWS_CUI: str = "Windows CUI"; break;
193 case IMAGE_SUBSYSTEM_OS2_CUI: str = "OS/2 CUI"; break;
194 case IMAGE_SUBSYSTEM_POSIX_CUI: str = "Posix CUI"; break;
196 printf(" %-34s 0x%X (%s)\n", title, value, str);
199 static inline void print_dllflags(const char *title, WORD value)
201 printf(" %-34s 0x%X\n", title, value);
202 #define X(f,s) if (value & f) printf(" %s\n", s)
203 X(IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE, "DYNAMIC_BASE");
204 X(IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY, "FORCE_INTEGRITY");
205 X(IMAGE_DLLCHARACTERISTICS_NX_COMPAT, "NX_COMPAT");
206 X(IMAGE_DLLCHARACTERISTICS_NO_ISOLATION, "NO_ISOLATION");
207 X(IMAGE_DLLCHARACTERISTICS_NO_SEH, "NO_SEH");
208 X(IMAGE_DLLCHARACTERISTICS_NO_BIND, "NO_BIND");
209 X(IMAGE_DLLCHARACTERISTICS_WDM_DRIVER, "WDM_DRIVER");
210 X(IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE, "TERMINAL_SERVER_AWARE");
211 #undef X
214 static inline void print_datadirectory(DWORD n, const IMAGE_DATA_DIRECTORY *directory)
216 unsigned i;
217 printf("Data Directory\n");
219 for (i = 0; i < n && i < 16; i++)
221 printf(" %-12s rva: 0x%-8x size: 0x%-8x\n",
222 DirectoryNames[i], directory[i].VirtualAddress,
223 directory[i].Size);
227 static void dump_optional_header32(const IMAGE_OPTIONAL_HEADER32 *image_oh, UINT header_size)
229 IMAGE_OPTIONAL_HEADER32 oh;
230 const IMAGE_OPTIONAL_HEADER32 *optionalHeader;
232 /* in case optional header is missing or partial */
233 memset(&oh, 0, sizeof(oh));
234 memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
235 optionalHeader = &oh;
237 print_word("Magic", optionalHeader->Magic);
238 print_ver("linker version",
239 optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
240 print_dword("size of code", optionalHeader->SizeOfCode);
241 print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
242 print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
243 print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
244 print_dword("base of code", optionalHeader->BaseOfCode);
245 print_dword("base of data", optionalHeader->BaseOfData);
246 print_dword("image base", optionalHeader->ImageBase);
247 print_dword("section align", optionalHeader->SectionAlignment);
248 print_dword("file align", optionalHeader->FileAlignment);
249 print_ver("required OS version",
250 optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
251 print_ver("image version",
252 optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
253 print_ver("subsystem version",
254 optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
255 print_dword("Win32 Version", optionalHeader->Win32VersionValue);
256 print_dword("size of image", optionalHeader->SizeOfImage);
257 print_dword("size of headers", optionalHeader->SizeOfHeaders);
258 print_dword("checksum", optionalHeader->CheckSum);
259 print_subsys("Subsystem", optionalHeader->Subsystem);
260 print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
261 print_dword("stack reserve size", optionalHeader->SizeOfStackReserve);
262 print_dword("stack commit size", optionalHeader->SizeOfStackCommit);
263 print_dword("heap reserve size", optionalHeader->SizeOfHeapReserve);
264 print_dword("heap commit size", optionalHeader->SizeOfHeapCommit);
265 print_dword("loader flags", optionalHeader->LoaderFlags);
266 print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
267 printf("\n");
268 print_datadirectory(optionalHeader->NumberOfRvaAndSizes, optionalHeader->DataDirectory);
269 printf("\n");
272 static void dump_optional_header64(const IMAGE_OPTIONAL_HEADER64 *image_oh, UINT header_size)
274 IMAGE_OPTIONAL_HEADER64 oh;
275 const IMAGE_OPTIONAL_HEADER64 *optionalHeader;
277 /* in case optional header is missing or partial */
278 memset(&oh, 0, sizeof(oh));
279 memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
280 optionalHeader = &oh;
282 print_word("Magic", optionalHeader->Magic);
283 print_ver("linker version",
284 optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
285 print_dword("size of code", optionalHeader->SizeOfCode);
286 print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
287 print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
288 print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
289 print_dword("base of code", optionalHeader->BaseOfCode);
290 print_longlong("image base", optionalHeader->ImageBase);
291 print_dword("section align", optionalHeader->SectionAlignment);
292 print_dword("file align", optionalHeader->FileAlignment);
293 print_ver("required OS version",
294 optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
295 print_ver("image version",
296 optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
297 print_ver("subsystem version",
298 optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
299 print_dword("Win32 Version", optionalHeader->Win32VersionValue);
300 print_dword("size of image", optionalHeader->SizeOfImage);
301 print_dword("size of headers", optionalHeader->SizeOfHeaders);
302 print_dword("checksum", optionalHeader->CheckSum);
303 print_subsys("Subsystem", optionalHeader->Subsystem);
304 print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
305 print_longlong("stack reserve size", optionalHeader->SizeOfStackReserve);
306 print_longlong("stack commit size", optionalHeader->SizeOfStackCommit);
307 print_longlong("heap reserve size", optionalHeader->SizeOfHeapReserve);
308 print_longlong("heap commit size", optionalHeader->SizeOfHeapCommit);
309 print_dword("loader flags", optionalHeader->LoaderFlags);
310 print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
311 printf("\n");
312 print_datadirectory(optionalHeader->NumberOfRvaAndSizes, optionalHeader->DataDirectory);
313 printf("\n");
316 void dump_optional_header(const IMAGE_OPTIONAL_HEADER32 *optionalHeader, UINT header_size)
318 printf("Optional Header (%s)\n", get_magic_type(optionalHeader->Magic));
320 switch(optionalHeader->Magic) {
321 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
322 dump_optional_header32(optionalHeader, header_size);
323 break;
324 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
325 dump_optional_header64((const IMAGE_OPTIONAL_HEADER64 *)optionalHeader, header_size);
326 break;
327 default:
328 printf(" Unknown optional header magic: 0x%-4X\n", optionalHeader->Magic);
329 break;
333 void dump_file_header(const IMAGE_FILE_HEADER *fileHeader)
335 printf("File Header\n");
337 printf(" Machine: %04X (%s)\n",
338 fileHeader->Machine, get_machine_str(fileHeader->Machine));
339 printf(" Number of Sections: %d\n", fileHeader->NumberOfSections);
340 printf(" TimeDateStamp: %08X (%s) offset %lu\n",
341 fileHeader->TimeDateStamp, get_time_str(fileHeader->TimeDateStamp),
342 Offset(&(fileHeader->TimeDateStamp)));
343 printf(" PointerToSymbolTable: %08X\n", fileHeader->PointerToSymbolTable);
344 printf(" NumberOfSymbols: %08X\n", fileHeader->NumberOfSymbols);
345 printf(" SizeOfOptionalHeader: %04X\n", fileHeader->SizeOfOptionalHeader);
346 printf(" Characteristics: %04X\n", fileHeader->Characteristics);
347 #define X(f,s) if (fileHeader->Characteristics & f) printf(" %s\n", s)
348 X(IMAGE_FILE_RELOCS_STRIPPED, "RELOCS_STRIPPED");
349 X(IMAGE_FILE_EXECUTABLE_IMAGE, "EXECUTABLE_IMAGE");
350 X(IMAGE_FILE_LINE_NUMS_STRIPPED, "LINE_NUMS_STRIPPED");
351 X(IMAGE_FILE_LOCAL_SYMS_STRIPPED, "LOCAL_SYMS_STRIPPED");
352 X(IMAGE_FILE_AGGRESIVE_WS_TRIM, "AGGRESIVE_WS_TRIM");
353 X(IMAGE_FILE_LARGE_ADDRESS_AWARE, "LARGE_ADDRESS_AWARE");
354 X(IMAGE_FILE_16BIT_MACHINE, "16BIT_MACHINE");
355 X(IMAGE_FILE_BYTES_REVERSED_LO, "BYTES_REVERSED_LO");
356 X(IMAGE_FILE_32BIT_MACHINE, "32BIT_MACHINE");
357 X(IMAGE_FILE_DEBUG_STRIPPED, "DEBUG_STRIPPED");
358 X(IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "REMOVABLE_RUN_FROM_SWAP");
359 X(IMAGE_FILE_NET_RUN_FROM_SWAP, "NET_RUN_FROM_SWAP");
360 X(IMAGE_FILE_SYSTEM, "SYSTEM");
361 X(IMAGE_FILE_DLL, "DLL");
362 X(IMAGE_FILE_UP_SYSTEM_ONLY, "UP_SYSTEM_ONLY");
363 X(IMAGE_FILE_BYTES_REVERSED_HI, "BYTES_REVERSED_HI");
364 #undef X
365 printf("\n");
368 static void dump_pe_header(void)
370 dump_file_header(&PE_nt_headers->FileHeader);
371 dump_optional_header((const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader, PE_nt_headers->FileHeader.SizeOfOptionalHeader);
374 void dump_section(const IMAGE_SECTION_HEADER *sectHead, const char* strtable)
376 unsigned offset;
378 /* long section name ? */
379 if (strtable && sectHead->Name[0] == '/' &&
380 ((offset = atoi((const char*)sectHead->Name + 1)) < *(const DWORD*)strtable))
381 printf(" %.8s (%s)", sectHead->Name, strtable + offset);
382 else
383 printf(" %-8.8s", sectHead->Name);
384 printf(" VirtSize: 0x%08x VirtAddr: 0x%08x\n",
385 sectHead->Misc.VirtualSize, sectHead->VirtualAddress);
386 printf(" raw data offs: 0x%08x raw data size: 0x%08x\n",
387 sectHead->PointerToRawData, sectHead->SizeOfRawData);
388 printf(" relocation offs: 0x%08x relocations: 0x%08x\n",
389 sectHead->PointerToRelocations, sectHead->NumberOfRelocations);
390 printf(" line # offs: %-8u line #'s: %-8u\n",
391 sectHead->PointerToLinenumbers, sectHead->NumberOfLinenumbers);
392 printf(" characteristics: 0x%08x\n", sectHead->Characteristics);
393 printf(" ");
394 #define X(b,s) if (sectHead->Characteristics & b) printf(" " s)
395 /* #define IMAGE_SCN_TYPE_REG 0x00000000 - Reserved */
396 /* #define IMAGE_SCN_TYPE_DSECT 0x00000001 - Reserved */
397 /* #define IMAGE_SCN_TYPE_NOLOAD 0x00000002 - Reserved */
398 /* #define IMAGE_SCN_TYPE_GROUP 0x00000004 - Reserved */
399 /* #define IMAGE_SCN_TYPE_NO_PAD 0x00000008 - Reserved */
400 /* #define IMAGE_SCN_TYPE_COPY 0x00000010 - Reserved */
402 X(IMAGE_SCN_CNT_CODE, "CODE");
403 X(IMAGE_SCN_CNT_INITIALIZED_DATA, "INITIALIZED_DATA");
404 X(IMAGE_SCN_CNT_UNINITIALIZED_DATA, "UNINITIALIZED_DATA");
406 X(IMAGE_SCN_LNK_OTHER, "LNK_OTHER");
407 X(IMAGE_SCN_LNK_INFO, "LNK_INFO");
408 /* #define IMAGE_SCN_TYPE_OVER 0x00000400 - Reserved */
409 X(IMAGE_SCN_LNK_REMOVE, "LNK_REMOVE");
410 X(IMAGE_SCN_LNK_COMDAT, "LNK_COMDAT");
412 /* 0x00002000 - Reserved */
413 /* #define IMAGE_SCN_MEM_PROTECTED 0x00004000 - Obsolete */
414 X(IMAGE_SCN_MEM_FARDATA, "MEM_FARDATA");
416 /* #define IMAGE_SCN_MEM_SYSHEAP 0x00010000 - Obsolete */
417 X(IMAGE_SCN_MEM_PURGEABLE, "MEM_PURGEABLE");
418 X(IMAGE_SCN_MEM_16BIT, "MEM_16BIT");
419 X(IMAGE_SCN_MEM_LOCKED, "MEM_LOCKED");
420 X(IMAGE_SCN_MEM_PRELOAD, "MEM_PRELOAD");
422 switch (sectHead->Characteristics & IMAGE_SCN_ALIGN_MASK)
424 #define X2(b,s) case b: printf(" " s); break
425 X2(IMAGE_SCN_ALIGN_1BYTES, "ALIGN_1BYTES");
426 X2(IMAGE_SCN_ALIGN_2BYTES, "ALIGN_2BYTES");
427 X2(IMAGE_SCN_ALIGN_4BYTES, "ALIGN_4BYTES");
428 X2(IMAGE_SCN_ALIGN_8BYTES, "ALIGN_8BYTES");
429 X2(IMAGE_SCN_ALIGN_16BYTES, "ALIGN_16BYTES");
430 X2(IMAGE_SCN_ALIGN_32BYTES, "ALIGN_32BYTES");
431 X2(IMAGE_SCN_ALIGN_64BYTES, "ALIGN_64BYTES");
432 X2(IMAGE_SCN_ALIGN_128BYTES, "ALIGN_128BYTES");
433 X2(IMAGE_SCN_ALIGN_256BYTES, "ALIGN_256BYTES");
434 X2(IMAGE_SCN_ALIGN_512BYTES, "ALIGN_512BYTES");
435 X2(IMAGE_SCN_ALIGN_1024BYTES, "ALIGN_1024BYTES");
436 X2(IMAGE_SCN_ALIGN_2048BYTES, "ALIGN_2048BYTES");
437 X2(IMAGE_SCN_ALIGN_4096BYTES, "ALIGN_4096BYTES");
438 X2(IMAGE_SCN_ALIGN_8192BYTES, "ALIGN_8192BYTES");
439 #undef X2
442 X(IMAGE_SCN_LNK_NRELOC_OVFL, "LNK_NRELOC_OVFL");
444 X(IMAGE_SCN_MEM_DISCARDABLE, "MEM_DISCARDABLE");
445 X(IMAGE_SCN_MEM_NOT_CACHED, "MEM_NOT_CACHED");
446 X(IMAGE_SCN_MEM_NOT_PAGED, "MEM_NOT_PAGED");
447 X(IMAGE_SCN_MEM_SHARED, "MEM_SHARED");
448 X(IMAGE_SCN_MEM_EXECUTE, "MEM_EXECUTE");
449 X(IMAGE_SCN_MEM_READ, "MEM_READ");
450 X(IMAGE_SCN_MEM_WRITE, "MEM_WRITE");
451 #undef X
452 printf("\n\n");
455 static void dump_sections(const void *base, const void* addr, unsigned num_sect)
457 const IMAGE_SECTION_HEADER* sectHead = addr;
458 unsigned i;
459 const char* strtable;
461 if (PE_nt_headers->FileHeader.PointerToSymbolTable && PE_nt_headers->FileHeader.NumberOfSymbols)
463 strtable = (const char*)base +
464 PE_nt_headers->FileHeader.PointerToSymbolTable +
465 PE_nt_headers->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL);
467 else strtable = NULL;
469 printf("Section Table\n");
470 for (i = 0; i < num_sect; i++, sectHead++)
472 dump_section(sectHead, strtable);
474 if (globals.do_dump_rawdata)
476 dump_data((const unsigned char *)base + sectHead->PointerToRawData, sectHead->SizeOfRawData, " " );
477 printf("\n");
482 static void dump_dir_exported_functions(void)
484 unsigned int size = 0;
485 const IMAGE_EXPORT_DIRECTORY*exportDir = get_dir_and_size(IMAGE_FILE_EXPORT_DIRECTORY, &size);
486 unsigned int i;
487 const DWORD* pFunc;
488 const DWORD* pName;
489 const WORD* pOrdl;
490 DWORD* funcs;
492 if (!exportDir) return;
494 printf("Exports table:\n");
495 printf("\n");
496 printf(" Name: %s\n", (const char*)RVA(exportDir->Name, sizeof(DWORD)));
497 printf(" Characteristics: %08x\n", exportDir->Characteristics);
498 printf(" TimeDateStamp: %08X %s\n",
499 exportDir->TimeDateStamp, get_time_str(exportDir->TimeDateStamp));
500 printf(" Version: %u.%02u\n", exportDir->MajorVersion, exportDir->MinorVersion);
501 printf(" Ordinal base: %u\n", exportDir->Base);
502 printf(" # of functions: %u\n", exportDir->NumberOfFunctions);
503 printf(" # of Names: %u\n", exportDir->NumberOfNames);
504 printf("Addresses of functions: %08X\n", exportDir->AddressOfFunctions);
505 printf("Addresses of name ordinals: %08X\n", exportDir->AddressOfNameOrdinals);
506 printf("Addresses of names: %08X\n", exportDir->AddressOfNames);
507 printf("\n");
508 printf(" Entry Pt Ordn Name\n");
510 pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
511 if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
512 pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
513 pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
515 funcs = calloc( exportDir->NumberOfFunctions, sizeof(*funcs) );
516 if (!funcs) fatal("no memory");
518 for (i = 0; i < exportDir->NumberOfNames; i++) funcs[pOrdl[i]] = pName[i];
520 for (i = 0; i < exportDir->NumberOfFunctions; i++)
522 if (!pFunc[i]) continue;
523 printf(" %08X %5u ", pFunc[i], exportDir->Base + i);
524 if (funcs[i])
525 printf("%s", get_symbol_str((const char*)RVA(funcs[i], sizeof(DWORD))));
526 else
527 printf("<by ordinal>");
529 /* check for forwarded function */
530 if ((const char *)RVA(pFunc[i],1) >= (const char *)exportDir &&
531 (const char *)RVA(pFunc[i],1) < (const char *)exportDir + size)
532 printf(" (-> %s)", (const char *)RVA(pFunc[i],1));
533 printf("\n");
535 free(funcs);
536 printf("\n");
540 struct runtime_function
542 DWORD BeginAddress;
543 DWORD EndAddress;
544 DWORD UnwindData;
547 union handler_data
549 struct runtime_function chain;
550 DWORD handler;
553 struct opcode
555 BYTE offset;
556 BYTE code : 4;
557 BYTE info : 4;
560 struct unwind_info
562 BYTE version : 3;
563 BYTE flags : 5;
564 BYTE prolog;
565 BYTE count;
566 BYTE frame_reg : 4;
567 BYTE frame_offset : 4;
568 struct opcode opcodes[1]; /* count entries */
569 /* followed by union handler_data */
572 #define UWOP_PUSH_NONVOL 0
573 #define UWOP_ALLOC_LARGE 1
574 #define UWOP_ALLOC_SMALL 2
575 #define UWOP_SET_FPREG 3
576 #define UWOP_SAVE_NONVOL 4
577 #define UWOP_SAVE_NONVOL_FAR 5
578 #define UWOP_SAVE_XMM128 8
579 #define UWOP_SAVE_XMM128_FAR 9
580 #define UWOP_PUSH_MACHFRAME 10
582 #define UNW_FLAG_EHANDLER 1
583 #define UNW_FLAG_UHANDLER 2
584 #define UNW_FLAG_CHAININFO 4
586 static void dump_x86_64_unwind_info( const struct runtime_function *function )
588 static const char * const reg_names[16] =
589 { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
590 "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" };
592 const union handler_data *handler_data;
593 const struct unwind_info *info;
594 unsigned int i, count;
596 printf( "\nFunction %08x-%08x:\n", function->BeginAddress, function->EndAddress );
597 if (function->UnwindData & 1)
599 const struct runtime_function *next = RVA( function->UnwindData & ~1, sizeof(*next) );
600 printf( " -> function %08x-%08x\n", next->BeginAddress, next->EndAddress );
601 return;
603 info = RVA( function->UnwindData, sizeof(*info) );
605 printf( " unwind info at %08x\n", function->UnwindData );
606 if (info->version != 1)
608 printf( " *** unknown version %u\n", info->version );
609 return;
611 printf( " flags %x", info->flags );
612 if (info->flags & UNW_FLAG_EHANDLER) printf( " EHANDLER" );
613 if (info->flags & UNW_FLAG_UHANDLER) printf( " UHANDLER" );
614 if (info->flags & UNW_FLAG_CHAININFO) printf( " CHAININFO" );
615 printf( "\n prolog 0x%x bytes\n", info->prolog );
617 if (info->frame_reg)
618 printf( " frame register %s offset 0x%x(%%rsp)\n",
619 reg_names[info->frame_reg], info->frame_offset * 16 );
621 for (i = 0; i < info->count; i++)
623 printf( " 0x%02x: ", info->opcodes[i].offset );
624 switch (info->opcodes[i].code)
626 case UWOP_PUSH_NONVOL:
627 printf( "push %%%s\n", reg_names[info->opcodes[i].info] );
628 break;
629 case UWOP_ALLOC_LARGE:
630 if (info->opcodes[i].info)
632 count = *(const DWORD *)&info->opcodes[i+1];
633 i += 2;
635 else
637 count = *(const USHORT *)&info->opcodes[i+1] * 8;
638 i++;
640 printf( "sub $0x%x,%%rsp\n", count );
641 break;
642 case UWOP_ALLOC_SMALL:
643 count = (info->opcodes[i].info + 1) * 8;
644 printf( "sub $0x%x,%%rsp\n", count );
645 break;
646 case UWOP_SET_FPREG:
647 printf( "lea 0x%x(%%rsp),%s\n",
648 info->frame_offset * 16, reg_names[info->frame_reg] );
649 break;
650 case UWOP_SAVE_NONVOL:
651 count = *(const USHORT *)&info->opcodes[i+1] * 8;
652 printf( "mov %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
653 i++;
654 break;
655 case UWOP_SAVE_NONVOL_FAR:
656 count = *(const DWORD *)&info->opcodes[i+1];
657 printf( "mov %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
658 i += 2;
659 break;
660 case UWOP_SAVE_XMM128:
661 count = *(const USHORT *)&info->opcodes[i+1] * 16;
662 printf( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
663 i++;
664 break;
665 case UWOP_SAVE_XMM128_FAR:
666 count = *(const DWORD *)&info->opcodes[i+1];
667 printf( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
668 i += 2;
669 break;
670 case UWOP_PUSH_MACHFRAME:
671 printf( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
672 break;
673 default:
674 printf( "*** unknown code %u\n", info->opcodes[i].code );
675 break;
679 handler_data = (const union handler_data *)&info->opcodes[(info->count + 1) & ~1];
680 if (info->flags & UNW_FLAG_CHAININFO)
682 printf( " -> function %08x-%08x\n",
683 handler_data->chain.BeginAddress, handler_data->chain.EndAddress );
684 return;
686 if (info->flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER))
687 printf( " handler %08x data at %08x\n", handler_data->handler,
688 (ULONG)(function->UnwindData + (const char *)(&handler_data->handler + 1) - (const char *)info ));
691 static void dump_dir_exceptions(void)
693 unsigned int i, size = 0;
694 const struct runtime_function *funcs = get_dir_and_size(IMAGE_FILE_EXCEPTION_DIRECTORY, &size);
695 const IMAGE_FILE_HEADER *file_header = &PE_nt_headers->FileHeader;
697 if (!funcs) return;
699 if (file_header->Machine == IMAGE_FILE_MACHINE_AMD64)
701 size /= sizeof(*funcs);
702 printf( "Exception info (%u functions):\n", size );
703 for (i = 0; i < size; i++) dump_x86_64_unwind_info( funcs + i );
705 else printf( "Exception information not supported for %s binaries\n",
706 get_machine_str(file_header->Machine));
710 static void dump_image_thunk_data64(const IMAGE_THUNK_DATA64 *il)
712 /* FIXME: This does not properly handle large images */
713 const IMAGE_IMPORT_BY_NAME* iibn;
714 for (; il->u1.Ordinal; il++)
716 if (IMAGE_SNAP_BY_ORDINAL64(il->u1.Ordinal))
717 printf(" %4u <by ordinal>\n", (DWORD)IMAGE_ORDINAL64(il->u1.Ordinal));
718 else
720 iibn = RVA((DWORD)il->u1.AddressOfData, sizeof(DWORD));
721 if (!iibn)
722 printf("Can't grab import by name info, skipping to next ordinal\n");
723 else
724 printf(" %4u %s %x\n", iibn->Hint, iibn->Name, (DWORD)il->u1.AddressOfData);
729 static void dump_image_thunk_data32(const IMAGE_THUNK_DATA32 *il, int offset)
731 const IMAGE_IMPORT_BY_NAME* iibn;
732 for (; il->u1.Ordinal; il++)
734 if (IMAGE_SNAP_BY_ORDINAL32(il->u1.Ordinal))
735 printf(" %4u <by ordinal>\n", IMAGE_ORDINAL32(il->u1.Ordinal));
736 else
738 iibn = RVA((DWORD)il->u1.AddressOfData - offset, sizeof(DWORD));
739 if (!iibn)
740 printf("Can't grab import by name info, skipping to next ordinal\n");
741 else
742 printf(" %4u %s %x\n", iibn->Hint, iibn->Name, (DWORD)il->u1.AddressOfData);
747 static void dump_dir_imported_functions(void)
749 const IMAGE_IMPORT_DESCRIPTOR *importDesc = get_dir(IMAGE_FILE_IMPORT_DIRECTORY);
750 DWORD directorySize;
752 if (!importDesc) return;
753 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
755 const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
756 directorySize = opt->DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY].Size;
758 else
760 const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
761 directorySize = opt->DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY].Size;
764 printf("Import Table size: %08x\n", directorySize);/* FIXME */
766 for (;;)
768 const IMAGE_THUNK_DATA32* il;
770 if (!importDesc->Name || !importDesc->FirstThunk) break;
772 printf(" offset %08lx %s\n", Offset(importDesc), (const char*)RVA(importDesc->Name, sizeof(DWORD)));
773 printf(" Hint/Name Table: %08X\n", (DWORD)importDesc->u.OriginalFirstThunk);
774 printf(" TimeDateStamp: %08X (%s)\n",
775 importDesc->TimeDateStamp, get_time_str(importDesc->TimeDateStamp));
776 printf(" ForwarderChain: %08X\n", importDesc->ForwarderChain);
777 printf(" First thunk RVA: %08X\n", (DWORD)importDesc->FirstThunk);
779 printf(" Ordn Name\n");
781 il = (importDesc->u.OriginalFirstThunk != 0) ?
782 RVA((DWORD)importDesc->u.OriginalFirstThunk, sizeof(DWORD)) :
783 RVA((DWORD)importDesc->FirstThunk, sizeof(DWORD));
785 if (!il)
786 printf("Can't grab thunk data, going to next imported DLL\n");
787 else
789 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
790 dump_image_thunk_data64((const IMAGE_THUNK_DATA64*)il);
791 else
792 dump_image_thunk_data32(il, 0);
793 printf("\n");
795 importDesc++;
797 printf("\n");
800 static void dump_dir_delay_imported_functions(void)
802 const struct ImgDelayDescr
804 DWORD grAttrs;
805 DWORD szName;
806 DWORD phmod;
807 DWORD pIAT;
808 DWORD pINT;
809 DWORD pBoundIAT;
810 DWORD pUnloadIAT;
811 DWORD dwTimeStamp;
812 } *importDesc = get_dir(IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT);
813 DWORD directorySize;
815 if (!importDesc) return;
816 if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
818 const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64 *)&PE_nt_headers->OptionalHeader;
819 directorySize = opt->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
821 else
823 const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32 *)&PE_nt_headers->OptionalHeader;
824 directorySize = opt->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
827 printf("Delay Import Table size: %08x\n", directorySize); /* FIXME */
829 for (;;)
831 const IMAGE_THUNK_DATA32* il;
832 int offset = (importDesc->grAttrs & 1) ? 0 : PE_nt_headers->OptionalHeader.ImageBase;
834 if (!importDesc->szName || !importDesc->pIAT || !importDesc->pINT) break;
836 printf(" grAttrs %08x offset %08lx %s\n", importDesc->grAttrs, Offset(importDesc),
837 (const char *)RVA(importDesc->szName - offset, sizeof(DWORD)));
838 printf(" Hint/Name Table: %08x\n", importDesc->pINT);
839 printf(" TimeDateStamp: %08X (%s)\n",
840 importDesc->dwTimeStamp, get_time_str(importDesc->dwTimeStamp));
842 printf(" Ordn Name\n");
844 il = RVA(importDesc->pINT - offset, sizeof(DWORD));
846 if (!il)
847 printf("Can't grab thunk data, going to next imported DLL\n");
848 else
850 if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
851 dump_image_thunk_data64((const IMAGE_THUNK_DATA64 *)il);
852 else
853 dump_image_thunk_data32(il, offset);
854 printf("\n");
856 importDesc++;
858 printf("\n");
861 static void dump_dir_debug_dir(const IMAGE_DEBUG_DIRECTORY* idd, int idx)
863 const char* str;
865 printf("Directory %02u\n", idx + 1);
866 printf(" Characteristics: %08X\n", idd->Characteristics);
867 printf(" TimeDateStamp: %08X %s\n",
868 idd->TimeDateStamp, get_time_str(idd->TimeDateStamp));
869 printf(" Version %u.%02u\n", idd->MajorVersion, idd->MinorVersion);
870 switch (idd->Type)
872 default:
873 case IMAGE_DEBUG_TYPE_UNKNOWN: str = "UNKNOWN"; break;
874 case IMAGE_DEBUG_TYPE_COFF: str = "COFF"; break;
875 case IMAGE_DEBUG_TYPE_CODEVIEW: str = "CODEVIEW"; break;
876 case IMAGE_DEBUG_TYPE_FPO: str = "FPO"; break;
877 case IMAGE_DEBUG_TYPE_MISC: str = "MISC"; break;
878 case IMAGE_DEBUG_TYPE_EXCEPTION: str = "EXCEPTION"; break;
879 case IMAGE_DEBUG_TYPE_FIXUP: str = "FIXUP"; break;
880 case IMAGE_DEBUG_TYPE_OMAP_TO_SRC: str = "OMAP_TO_SRC"; break;
881 case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:str = "OMAP_FROM_SRC"; break;
882 case IMAGE_DEBUG_TYPE_BORLAND: str = "BORLAND"; break;
883 case IMAGE_DEBUG_TYPE_RESERVED10: str = "RESERVED10"; break;
885 printf(" Type: %u (%s)\n", idd->Type, str);
886 printf(" SizeOfData: %u\n", idd->SizeOfData);
887 printf(" AddressOfRawData: %08X\n", idd->AddressOfRawData);
888 printf(" PointerToRawData: %08X\n", idd->PointerToRawData);
890 switch (idd->Type)
892 case IMAGE_DEBUG_TYPE_UNKNOWN:
893 break;
894 case IMAGE_DEBUG_TYPE_COFF:
895 dump_coff(idd->PointerToRawData, idd->SizeOfData,
896 (const char*)PE_nt_headers + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader);
897 break;
898 case IMAGE_DEBUG_TYPE_CODEVIEW:
899 dump_codeview(idd->PointerToRawData, idd->SizeOfData);
900 break;
901 case IMAGE_DEBUG_TYPE_FPO:
902 dump_frame_pointer_omission(idd->PointerToRawData, idd->SizeOfData);
903 break;
904 case IMAGE_DEBUG_TYPE_MISC:
906 const IMAGE_DEBUG_MISC* misc = PRD(idd->PointerToRawData, idd->SizeOfData);
907 if (!misc) {printf("Can't get misc debug information\n"); break;}
908 printf(" DataType: %u (%s)\n",
909 misc->DataType,
910 (misc->DataType == IMAGE_DEBUG_MISC_EXENAME) ? "Exe name" : "Unknown");
911 printf(" Length: %u\n", misc->Length);
912 printf(" Unicode: %s\n", misc->Unicode ? "Yes" : "No");
913 printf(" Data: %s\n", misc->Data);
915 break;
916 case IMAGE_DEBUG_TYPE_EXCEPTION:
917 break;
918 case IMAGE_DEBUG_TYPE_FIXUP:
919 break;
920 case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:
921 break;
922 case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:
923 break;
924 case IMAGE_DEBUG_TYPE_BORLAND:
925 break;
926 case IMAGE_DEBUG_TYPE_RESERVED10:
927 break;
929 printf("\n");
932 static void dump_dir_debug(void)
934 const IMAGE_DEBUG_DIRECTORY*debugDir = get_dir(IMAGE_FILE_DEBUG_DIRECTORY);
935 unsigned nb_dbg, i;
937 if (!debugDir) return;
938 nb_dbg = PE_nt_headers->OptionalHeader.DataDirectory[IMAGE_FILE_DEBUG_DIRECTORY].Size /
939 sizeof(*debugDir);
940 if (!nb_dbg) return;
942 printf("Debug Table (%u directories)\n", nb_dbg);
944 for (i = 0; i < nb_dbg; i++)
946 dump_dir_debug_dir(debugDir, i);
947 debugDir++;
949 printf("\n");
952 static inline void print_clrflags(const char *title, WORD value)
954 printf(" %-34s 0x%X\n", title, value);
955 #define X(f,s) if (value & f) printf(" %s\n", s)
956 X(COMIMAGE_FLAGS_ILONLY, "ILONLY");
957 X(COMIMAGE_FLAGS_32BITREQUIRED, "32BITREQUIRED");
958 X(COMIMAGE_FLAGS_IL_LIBRARY, "IL_LIBRARY");
959 X(COMIMAGE_FLAGS_STRONGNAMESIGNED, "STRONGNAMESIGNED");
960 X(COMIMAGE_FLAGS_TRACKDEBUGDATA, "TRACKDEBUGDATA");
961 #undef X
964 static inline void print_clrdirectory(const char *title, const IMAGE_DATA_DIRECTORY *dir)
966 printf(" %-23s rva: 0x%-8x size: 0x%-8x\n", title, dir->VirtualAddress, dir->Size);
969 static void dump_dir_clr_header(void)
971 unsigned int size = 0;
972 const IMAGE_COR20_HEADER *dir = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &size);
974 if (!dir) return;
976 printf( "CLR Header\n" );
977 print_dword( "Header Size", dir->cb );
978 print_ver( "Required runtime version", dir->MajorRuntimeVersion, dir->MinorRuntimeVersion );
979 print_clrflags( "Flags", dir->Flags );
980 print_dword( "EntryPointToken", dir->EntryPointToken );
981 printf("\n");
982 printf( "CLR Data Directory\n" );
983 print_clrdirectory( "MetaData", &dir->MetaData );
984 print_clrdirectory( "Resources", &dir->Resources );
985 print_clrdirectory( "StrongNameSignature", &dir->StrongNameSignature );
986 print_clrdirectory( "CodeManagerTable", &dir->CodeManagerTable );
987 print_clrdirectory( "VTableFixups", &dir->VTableFixups );
988 print_clrdirectory( "ExportAddressTableJumps", &dir->ExportAddressTableJumps );
989 print_clrdirectory( "ManagedNativeHeader", &dir->ManagedNativeHeader );
990 printf("\n");
993 static void dump_dir_reloc(void)
995 unsigned int i, size = 0;
996 const USHORT *relocs;
997 const IMAGE_BASE_RELOCATION *rel = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_BASERELOC, &size);
998 const IMAGE_BASE_RELOCATION *end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + size);
999 static const char * const names[] =
1001 "BASED_ABSOLUTE",
1002 "BASED_HIGH",
1003 "BASED_LOW",
1004 "BASED_HIGHLOW",
1005 "BASED_HIGHADJ",
1006 "BASED_MIPS_JMPADDR",
1007 "BASED_SECTION",
1008 "BASED_REL",
1009 "unknown 8",
1010 "BASED_IA64_IMM64",
1011 "BASED_DIR64",
1012 "BASED_HIGH3ADJ",
1013 "unknown 12",
1014 "unknown 13",
1015 "unknown 14",
1016 "unknown 15"
1019 if (!rel) return;
1021 printf( "Relocations\n" );
1022 while (rel < end - 1 && rel->SizeOfBlock)
1024 printf( " Page %x\n", rel->VirtualAddress );
1025 relocs = (const USHORT *)(rel + 1);
1026 i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT);
1027 while (i--)
1029 USHORT offset = *relocs & 0xfff;
1030 int type = *relocs >> 12;
1031 printf( " off %04x type %s\n", offset, names[type] );
1032 relocs++;
1034 rel = (const IMAGE_BASE_RELOCATION *)relocs;
1036 printf("\n");
1039 static void dump_dir_tls(void)
1041 IMAGE_TLS_DIRECTORY64 dir;
1042 const DWORD *callbacks;
1043 const IMAGE_TLS_DIRECTORY32 *pdir = get_dir(IMAGE_FILE_THREAD_LOCAL_STORAGE);
1045 if (!pdir) return;
1047 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1048 memcpy(&dir, pdir, sizeof(dir));
1049 else
1051 dir.StartAddressOfRawData = pdir->StartAddressOfRawData;
1052 dir.EndAddressOfRawData = pdir->EndAddressOfRawData;
1053 dir.AddressOfIndex = pdir->AddressOfIndex;
1054 dir.AddressOfCallBacks = pdir->AddressOfCallBacks;
1055 dir.SizeOfZeroFill = pdir->SizeOfZeroFill;
1056 dir.Characteristics = pdir->Characteristics;
1059 /* FIXME: This does not properly handle large images */
1060 printf( "Thread Local Storage\n" );
1061 printf( " Raw data %08x-%08x (data size %x zero fill size %x)\n",
1062 (DWORD)dir.StartAddressOfRawData, (DWORD)dir.EndAddressOfRawData,
1063 (DWORD)(dir.EndAddressOfRawData - dir.StartAddressOfRawData),
1064 (DWORD)dir.SizeOfZeroFill );
1065 printf( " Index address %08x\n", (DWORD)dir.AddressOfIndex );
1066 printf( " Characteristics %08x\n", dir.Characteristics );
1067 printf( " Callbacks %08x -> {", (DWORD)dir.AddressOfCallBacks );
1068 if (dir.AddressOfCallBacks)
1070 DWORD addr = (DWORD)dir.AddressOfCallBacks - PE_nt_headers->OptionalHeader.ImageBase;
1071 while ((callbacks = RVA(addr, sizeof(DWORD))) && *callbacks)
1073 printf( " %08x", *callbacks );
1074 addr += sizeof(DWORD);
1077 printf(" }\n\n");
1080 enum FileSig get_kind_dbg(void)
1082 const WORD* pw;
1084 pw = PRD(0, sizeof(WORD));
1085 if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}
1087 if (*pw == 0x4944 /* "DI" */) return SIG_DBG;
1088 return SIG_UNKNOWN;
1091 void dbg_dump(void)
1093 const IMAGE_SEPARATE_DEBUG_HEADER* separateDebugHead;
1094 unsigned nb_dbg;
1095 unsigned i;
1096 const IMAGE_DEBUG_DIRECTORY* debugDir;
1098 separateDebugHead = PRD(0, sizeof(*separateDebugHead));
1099 if (!separateDebugHead) {printf("Can't grab the separate header, aborting\n"); return;}
1101 printf ("Signature: %.2s (0x%4X)\n",
1102 (const char*)&separateDebugHead->Signature, separateDebugHead->Signature);
1103 printf ("Flags: 0x%04X\n", separateDebugHead->Flags);
1104 printf ("Machine: 0x%04X (%s)\n",
1105 separateDebugHead->Machine, get_machine_str(separateDebugHead->Machine));
1106 printf ("Characteristics: 0x%04X\n", separateDebugHead->Characteristics);
1107 printf ("TimeDateStamp: 0x%08X (%s)\n",
1108 separateDebugHead->TimeDateStamp, get_time_str(separateDebugHead->TimeDateStamp));
1109 printf ("CheckSum: 0x%08X\n", separateDebugHead->CheckSum);
1110 printf ("ImageBase: 0x%08X\n", separateDebugHead->ImageBase);
1111 printf ("SizeOfImage: 0x%08X\n", separateDebugHead->SizeOfImage);
1112 printf ("NumberOfSections: 0x%08X\n", separateDebugHead->NumberOfSections);
1113 printf ("ExportedNamesSize: 0x%08X\n", separateDebugHead->ExportedNamesSize);
1114 printf ("DebugDirectorySize: 0x%08X\n", separateDebugHead->DebugDirectorySize);
1116 if (!PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER),
1117 separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER)))
1118 {printf("Can't get the sections, aborting\n"); return;}
1120 dump_sections(separateDebugHead, separateDebugHead + 1, separateDebugHead->NumberOfSections);
1122 nb_dbg = separateDebugHead->DebugDirectorySize / sizeof(IMAGE_DEBUG_DIRECTORY);
1123 debugDir = PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER) +
1124 separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
1125 separateDebugHead->ExportedNamesSize,
1126 nb_dbg * sizeof(IMAGE_DEBUG_DIRECTORY));
1127 if (!debugDir) {printf("Couldn't get the debug directory info, aborting\n");return;}
1129 printf("Debug Table (%u directories)\n", nb_dbg);
1131 for (i = 0; i < nb_dbg; i++)
1133 dump_dir_debug_dir(debugDir, i);
1134 debugDir++;
1138 static const char *get_resource_type( unsigned int id )
1140 static const char * const types[] =
1142 NULL,
1143 "CURSOR",
1144 "BITMAP",
1145 "ICON",
1146 "MENU",
1147 "DIALOG",
1148 "STRING",
1149 "FONTDIR",
1150 "FONT",
1151 "ACCELERATOR",
1152 "RCDATA",
1153 "MESSAGETABLE",
1154 "GROUP_CURSOR",
1155 NULL,
1156 "GROUP_ICON",
1157 NULL,
1158 "VERSION",
1159 "DLGINCLUDE",
1160 NULL,
1161 "PLUGPLAY",
1162 "VXD",
1163 "ANICURSOR",
1164 "ANIICON",
1165 "HTML",
1166 "RT_MANIFEST"
1169 if ((size_t)id < sizeof(types)/sizeof(types[0])) return types[id];
1170 return NULL;
1173 /* dump an ASCII string with proper escaping */
1174 static int dump_strA( const unsigned char *str, size_t len )
1176 static const char escapes[32] = ".......abtnvfr.............e....";
1177 char buffer[256];
1178 char *pos = buffer;
1179 int count = 0;
1181 for (; len; str++, len--)
1183 if (pos > buffer + sizeof(buffer) - 8)
1185 fwrite( buffer, pos - buffer, 1, stdout );
1186 count += pos - buffer;
1187 pos = buffer;
1189 if (*str > 127) /* hex escape */
1191 pos += sprintf( pos, "\\x%02x", *str );
1192 continue;
1194 if (*str < 32) /* octal or C escape */
1196 if (!*str && len == 1) continue; /* do not output terminating NULL */
1197 if (escapes[*str] != '.')
1198 pos += sprintf( pos, "\\%c", escapes[*str] );
1199 else if (len > 1 && str[1] >= '0' && str[1] <= '7')
1200 pos += sprintf( pos, "\\%03o", *str );
1201 else
1202 pos += sprintf( pos, "\\%o", *str );
1203 continue;
1205 if (*str == '\\') *pos++ = '\\';
1206 *pos++ = *str;
1208 fwrite( buffer, pos - buffer, 1, stdout );
1209 count += pos - buffer;
1210 return count;
1213 /* dump a Unicode string with proper escaping */
1214 static int dump_strW( const WCHAR *str, size_t len )
1216 static const char escapes[32] = ".......abtnvfr.............e....";
1217 char buffer[256];
1218 char *pos = buffer;
1219 int count = 0;
1221 for (; len; str++, len--)
1223 if (pos > buffer + sizeof(buffer) - 8)
1225 fwrite( buffer, pos - buffer, 1, stdout );
1226 count += pos - buffer;
1227 pos = buffer;
1229 if (*str > 127) /* hex escape */
1231 if (len > 1 && str[1] < 128 && isxdigit((char)str[1]))
1232 pos += sprintf( pos, "\\x%04x", *str );
1233 else
1234 pos += sprintf( pos, "\\x%x", *str );
1235 continue;
1237 if (*str < 32) /* octal or C escape */
1239 if (!*str && len == 1) continue; /* do not output terminating NULL */
1240 if (escapes[*str] != '.')
1241 pos += sprintf( pos, "\\%c", escapes[*str] );
1242 else if (len > 1 && str[1] >= '0' && str[1] <= '7')
1243 pos += sprintf( pos, "\\%03o", *str );
1244 else
1245 pos += sprintf( pos, "\\%o", *str );
1246 continue;
1248 if (*str == '\\') *pos++ = '\\';
1249 *pos++ = *str;
1251 fwrite( buffer, pos - buffer, 1, stdout );
1252 count += pos - buffer;
1253 return count;
1256 /* dump data for a STRING resource */
1257 static void dump_string_data( const WCHAR *ptr, unsigned int size, unsigned int id, const char *prefix )
1259 int i;
1261 for (i = 0; i < 16 && size; i++)
1263 unsigned len = *ptr++;
1265 if (len >= size)
1267 len = size;
1268 size = 0;
1270 else size -= len + 1;
1272 if (len)
1274 printf( "%s%04x \"", prefix, (id - 1) * 16 + i );
1275 dump_strW( ptr, len );
1276 printf( "\"\n" );
1277 ptr += len;
1282 /* dump data for a MESSAGETABLE resource */
1283 static void dump_msgtable_data( const void *ptr, unsigned int size, unsigned int id, const char *prefix )
1285 const MESSAGE_RESOURCE_DATA *data = ptr;
1286 const MESSAGE_RESOURCE_BLOCK *block = data->Blocks;
1287 unsigned i, j;
1289 for (i = 0; i < data->NumberOfBlocks; i++, block++)
1291 const MESSAGE_RESOURCE_ENTRY *entry;
1293 entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)data + block->OffsetToEntries);
1294 for (j = block->LowId; j <= block->HighId; j++)
1296 if (entry->Flags & MESSAGE_RESOURCE_UNICODE)
1298 const WCHAR *str = (const WCHAR *)entry->Text;
1299 printf( "%s%08x L\"", prefix, j );
1300 dump_strW( str, strlenW(str) );
1301 printf( "\"\n" );
1303 else
1305 const char *str = (const char *) entry->Text;
1306 printf( "%s%08x \"", prefix, j );
1307 dump_strA( entry->Text, strlen(str) );
1308 printf( "\"\n" );
1310 entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)entry + entry->Length);
1315 static void dump_dir_resource(void)
1317 const IMAGE_RESOURCE_DIRECTORY *root = get_dir(IMAGE_FILE_RESOURCE_DIRECTORY);
1318 const IMAGE_RESOURCE_DIRECTORY *namedir;
1319 const IMAGE_RESOURCE_DIRECTORY *langdir;
1320 const IMAGE_RESOURCE_DIRECTORY_ENTRY *e1, *e2, *e3;
1321 const IMAGE_RESOURCE_DIR_STRING_U *string;
1322 const IMAGE_RESOURCE_DATA_ENTRY *data;
1323 int i, j, k;
1325 if (!root) return;
1327 printf( "Resources:" );
1329 for (i = 0; i< root->NumberOfNamedEntries + root->NumberOfIdEntries; i++)
1331 e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
1332 namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s3.OffsetToDirectory);
1333 for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
1335 e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
1336 langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s3.OffsetToDirectory);
1337 for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
1339 e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
1341 printf( "\n " );
1342 if (e1->u1.s1.NameIsString)
1344 string = (const IMAGE_RESOURCE_DIR_STRING_U*)((const char *)root + e1->u1.s1.NameOffset);
1345 dump_unicode_str( string->NameString, string->Length );
1347 else
1349 const char *type = get_resource_type( e1->u1.s2.Id );
1350 if (type) printf( "%s", type );
1351 else printf( "%04x", e1->u1.s2.Id );
1354 printf( " Name=" );
1355 if (e2->u1.s1.NameIsString)
1357 string = (const IMAGE_RESOURCE_DIR_STRING_U*) ((const char *)root + e2->u1.s1.NameOffset);
1358 dump_unicode_str( string->NameString, string->Length );
1360 else
1361 printf( "%04x", e2->u1.s2.Id );
1363 printf( " Language=%04x:\n", e3->u1.s2.Id );
1364 data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
1365 if (e1->u1.s1.NameIsString)
1367 dump_data( RVA( data->OffsetToData, data->Size ), data->Size, " " );
1369 else switch(e1->u1.s2.Id)
1371 case 6:
1372 dump_string_data( RVA( data->OffsetToData, data->Size ), data->Size,
1373 e2->u1.s2.Id, " " );
1374 break;
1375 case 11:
1376 dump_msgtable_data( RVA( data->OffsetToData, data->Size ), data->Size,
1377 e2->u1.s2.Id, " " );
1378 break;
1379 default:
1380 dump_data( RVA( data->OffsetToData, data->Size ), data->Size, " " );
1381 break;
1386 printf( "\n\n" );
1389 static void dump_debug(void)
1391 const char* stabs = NULL;
1392 unsigned szstabs = 0;
1393 const char* stabstr = NULL;
1394 unsigned szstr = 0;
1395 unsigned i;
1396 const IMAGE_SECTION_HEADER* sectHead;
1398 sectHead = (const IMAGE_SECTION_HEADER*)
1399 ((const char*)PE_nt_headers + sizeof(DWORD) +
1400 sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader);
1402 for (i = 0; i < PE_nt_headers->FileHeader.NumberOfSections; i++, sectHead++)
1404 if (!strcmp((const char *)sectHead->Name, ".stab"))
1406 stabs = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize);
1407 szstabs = sectHead->Misc.VirtualSize;
1409 if (!strncmp((const char *)sectHead->Name, ".stabstr", 8))
1411 stabstr = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize);
1412 szstr = sectHead->Misc.VirtualSize;
1415 if (stabs && stabstr)
1416 dump_stabs(stabs, szstabs, stabstr, szstr);
1419 static void dump_symbol_table(void)
1421 const IMAGE_SYMBOL* sym;
1422 int numsym;
1424 numsym = PE_nt_headers->FileHeader.NumberOfSymbols;
1425 if (!PE_nt_headers->FileHeader.PointerToSymbolTable || !numsym)
1426 return;
1427 sym = PRD(PE_nt_headers->FileHeader.PointerToSymbolTable,
1428 sizeof(*sym) * numsym);
1429 if (!sym) return;
1431 dump_coff_symbol_table(sym, numsym, IMAGE_FIRST_SECTION(PE_nt_headers));
1434 enum FileSig get_kind_exec(void)
1436 const WORD* pw;
1437 const DWORD* pdw;
1438 const IMAGE_DOS_HEADER* dh;
1440 pw = PRD(0, sizeof(WORD));
1441 if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}
1443 if (*pw != IMAGE_DOS_SIGNATURE) return SIG_UNKNOWN;
1445 if ((dh = PRD(0, sizeof(IMAGE_DOS_HEADER))))
1447 /* the signature is the first DWORD */
1448 pdw = PRD(dh->e_lfanew, sizeof(DWORD));
1449 if (pdw)
1451 if (*pdw == IMAGE_NT_SIGNATURE) return SIG_PE;
1452 if (*(const WORD *)pdw == IMAGE_OS2_SIGNATURE) return SIG_NE;
1453 if (*(const WORD *)pdw == IMAGE_VXD_SIGNATURE) return SIG_LE;
1454 return SIG_DOS;
1457 return 0;
1460 void pe_dump(void)
1462 int all = (globals.dumpsect != NULL) && strcmp(globals.dumpsect, "ALL") == 0;
1464 PE_nt_headers = get_nt_header();
1465 if (is_fake_dll()) printf( "*** This is a Wine fake DLL ***\n\n" );
1467 if (globals.do_dumpheader)
1469 dump_pe_header();
1470 /* FIXME: should check ptr */
1471 dump_sections(PRD(0, 1), (const char*)PE_nt_headers + sizeof(DWORD) +
1472 sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader,
1473 PE_nt_headers->FileHeader.NumberOfSections);
1475 else if (!globals.dumpsect)
1477 /* show at least something here */
1478 dump_pe_header();
1481 if (globals.dumpsect)
1483 if (all || !strcmp(globals.dumpsect, "import"))
1485 dump_dir_imported_functions();
1486 dump_dir_delay_imported_functions();
1488 if (all || !strcmp(globals.dumpsect, "export"))
1489 dump_dir_exported_functions();
1490 if (all || !strcmp(globals.dumpsect, "debug"))
1491 dump_dir_debug();
1492 if (all || !strcmp(globals.dumpsect, "resource"))
1493 dump_dir_resource();
1494 if (all || !strcmp(globals.dumpsect, "tls"))
1495 dump_dir_tls();
1496 if (all || !strcmp(globals.dumpsect, "clr"))
1497 dump_dir_clr_header();
1498 if (all || !strcmp(globals.dumpsect, "reloc"))
1499 dump_dir_reloc();
1500 if (all || !strcmp(globals.dumpsect, "except"))
1501 dump_dir_exceptions();
1503 if (globals.do_symbol_table)
1504 dump_symbol_table();
1505 if (globals.do_debug)
1506 dump_debug();
1509 typedef struct _dll_symbol {
1510 size_t ordinal;
1511 char *symbol;
1512 } dll_symbol;
1514 static dll_symbol *dll_symbols = NULL;
1515 static dll_symbol *dll_current_symbol = NULL;
1517 /* Compare symbols by ordinal for qsort */
1518 static int symbol_cmp(const void *left, const void *right)
1520 return ((const dll_symbol *)left)->ordinal > ((const dll_symbol *)right)->ordinal;
1523 /*******************************************************************
1524 * dll_close
1526 * Free resources used by DLL
1528 /* FIXME: Not used yet
1529 static void dll_close (void)
1531 dll_symbol* ds;
1533 if (!dll_symbols) {
1534 fatal("No symbols");
1536 for (ds = dll_symbols; ds->symbol; ds++)
1537 free(ds->symbol);
1538 free (dll_symbols);
1539 dll_symbols = NULL;
1543 static void do_grab_sym( void )
1545 const IMAGE_EXPORT_DIRECTORY*exportDir;
1546 unsigned i, j;
1547 const DWORD* pName;
1548 const DWORD* pFunc;
1549 const WORD* pOrdl;
1550 const char* ptr;
1551 DWORD* map;
1553 PE_nt_headers = get_nt_header();
1554 if (!(exportDir = get_dir(IMAGE_FILE_EXPORT_DIRECTORY))) return;
1556 pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
1557 if (!pName) {printf("Can't grab functions' name table\n"); return;}
1558 pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
1559 if (!pOrdl) {printf("Can't grab functions' ordinal table\n"); return;}
1560 pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
1561 if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
1563 /* dll_close(); */
1565 if (!(dll_symbols = malloc((exportDir->NumberOfFunctions + 1) * sizeof(dll_symbol))))
1566 fatal ("Out of memory");
1568 /* bit map of used funcs */
1569 map = calloc(((exportDir->NumberOfFunctions + 31) & ~31) / 32, sizeof(DWORD));
1570 if (!map) fatal("no memory");
1572 for (j = 0; j < exportDir->NumberOfNames; j++, pOrdl++)
1574 map[*pOrdl / 32] |= 1 << (*pOrdl % 32);
1575 ptr = RVA(*pName++, sizeof(DWORD));
1576 if (!ptr) ptr = "cant_get_function";
1577 dll_symbols[j].symbol = strdup(ptr);
1578 dll_symbols[j].ordinal = exportDir->Base + *pOrdl;
1579 assert(dll_symbols[j].symbol);
1582 for (i = 0; i < exportDir->NumberOfFunctions; i++)
1584 if (pFunc[i] && !(map[i / 32] & (1 << (i % 32))))
1586 char ordinal_text[256];
1587 /* Ordinal only entry */
1588 snprintf (ordinal_text, sizeof(ordinal_text), "%s_%u",
1589 globals.forward_dll ? globals.forward_dll : OUTPUT_UC_DLL_NAME,
1590 exportDir->Base + i);
1591 str_toupper(ordinal_text);
1592 dll_symbols[j].symbol = strdup(ordinal_text);
1593 assert(dll_symbols[j].symbol);
1594 dll_symbols[j].ordinal = exportDir->Base + i;
1595 j++;
1596 assert(j <= exportDir->NumberOfFunctions);
1599 free(map);
1601 if (NORMAL)
1602 printf("%u named symbols in DLL, %u total, %d unique (ordinal base = %d)\n",
1603 exportDir->NumberOfNames, exportDir->NumberOfFunctions, j, exportDir->Base);
1605 qsort( dll_symbols, j, sizeof(dll_symbol), symbol_cmp );
1607 dll_symbols[j].symbol = NULL;
1609 dll_current_symbol = dll_symbols;
1612 /*******************************************************************
1613 * dll_open
1615 * Open a DLL and read in exported symbols
1617 int dll_open (const char *dll_name)
1619 return dump_analysis(dll_name, do_grab_sym, SIG_PE);
1622 /*******************************************************************
1623 * dll_next_symbol
1625 * Get next exported symbol from dll
1627 int dll_next_symbol (parsed_symbol * sym)
1629 if (!dll_current_symbol || !dll_current_symbol->symbol)
1630 return 1;
1631 assert (dll_symbols);
1632 sym->symbol = strdup (dll_current_symbol->symbol);
1633 sym->ordinal = dll_current_symbol->ordinal;
1634 dll_current_symbol++;
1635 return 0;