push 0a0aa53cd365a71ca6121b6df157ca635450378f
[wine/hacks.git] / tools / winedump / pe.c
blob5ff8a164559173ca9375b823fa604dc6e430757f
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";
65 return "???";
68 static const void* RVA(unsigned long rva, unsigned long len)
70 IMAGE_SECTION_HEADER* sectHead;
71 int i;
73 if (rva == 0) return NULL;
75 sectHead = IMAGE_FIRST_SECTION(PE_nt_headers);
76 for (i = PE_nt_headers->FileHeader.NumberOfSections - 1; i >= 0; i--)
78 if (sectHead[i].VirtualAddress <= rva &&
79 rva + len <= (DWORD)sectHead[i].VirtualAddress + sectHead[i].SizeOfRawData)
81 /* return image import directory offset */
82 return PRD(sectHead[i].PointerToRawData + rva - sectHead[i].VirtualAddress, len);
86 return NULL;
89 static const IMAGE_NT_HEADERS32 *get_nt_header( void )
91 const IMAGE_DOS_HEADER *dos;
92 dos = PRD(0, sizeof(*dos));
93 if (!dos) return NULL;
94 return PRD(dos->e_lfanew, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER));
97 static int is_fake_dll( void )
99 static const char fakedll_signature[] = "Wine placeholder DLL";
100 const IMAGE_DOS_HEADER *dos;
102 dos = PRD(0, sizeof(*dos) + sizeof(fakedll_signature));
104 if (dos && dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
105 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
106 return FALSE;
109 static const void *get_dir_and_size(unsigned int idx, unsigned int *size)
111 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
113 const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
114 if (idx >= opt->NumberOfRvaAndSizes)
115 return NULL;
116 if(size)
117 *size = opt->DataDirectory[idx].Size;
118 return RVA(opt->DataDirectory[idx].VirtualAddress,
119 opt->DataDirectory[idx].Size);
121 else
123 const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
124 if (idx >= opt->NumberOfRvaAndSizes)
125 return NULL;
126 if(size)
127 *size = opt->DataDirectory[idx].Size;
128 return RVA(opt->DataDirectory[idx].VirtualAddress,
129 opt->DataDirectory[idx].Size);
133 static const void* get_dir(unsigned idx)
135 return get_dir_and_size(idx, 0);
138 static const char * const DirectoryNames[16] = {
139 "EXPORT", "IMPORT", "RESOURCE", "EXCEPTION",
140 "SECURITY", "BASERELOC", "DEBUG", "ARCHITECTURE",
141 "GLOBALPTR", "TLS", "LOAD_CONFIG", "Bound IAT",
142 "IAT", "Delay IAT", "CLR Header", ""
145 static const char *get_magic_type(WORD magic)
147 switch(magic) {
148 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
149 return "32bit";
150 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
151 return "64bit";
152 case IMAGE_ROM_OPTIONAL_HDR_MAGIC:
153 return "ROM";
155 return "???";
158 static inline void print_word(const char *title, WORD value)
160 printf(" %-34s 0x%-4X %u\n", title, value, value);
163 static inline void print_dword(const char *title, DWORD value)
165 printf(" %-34s 0x%-8x %u\n", title, value, value);
168 static inline void print_longlong(const char *title, ULONGLONG value)
170 printf(" %-34s 0x", title);
171 if(value >> 32)
172 printf("%lx%08lx\n", (unsigned long)(value >> 32), (unsigned long)value);
173 else
174 printf("%lx\n", (unsigned long)value);
177 static inline void print_ver(const char *title, BYTE major, BYTE minor)
179 printf(" %-34s %u.%02u\n", title, major, minor);
182 static inline void print_subsys(const char *title, WORD value)
184 const char *str;
185 switch (value)
187 default:
188 case IMAGE_SUBSYSTEM_UNKNOWN: str = "Unknown"; break;
189 case IMAGE_SUBSYSTEM_NATIVE: str = "Native"; break;
190 case IMAGE_SUBSYSTEM_WINDOWS_GUI: str = "Windows GUI"; break;
191 case IMAGE_SUBSYSTEM_WINDOWS_CUI: str = "Windows CUI"; break;
192 case IMAGE_SUBSYSTEM_OS2_CUI: str = "OS/2 CUI"; break;
193 case IMAGE_SUBSYSTEM_POSIX_CUI: str = "Posix CUI"; break;
195 printf(" %-34s 0x%X (%s)\n", title, value, str);
198 static inline void print_dllflags(const char *title, WORD value)
200 printf(" %-34s 0x%X\n", title, value);
201 #define X(f,s) if (value & f) printf(" %s\n", s)
202 X(IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE, "DYNAMIC_BASE");
203 X(IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY, "FORCE_INTEGRITY");
204 X(IMAGE_DLLCHARACTERISTICS_NX_COMPAT, "NX_COMPAT");
205 X(IMAGE_DLLCHARACTERISTICS_NO_ISOLATION, "NO_ISOLATION");
206 X(IMAGE_DLLCHARACTERISTICS_NO_SEH, "NO_SEH");
207 X(IMAGE_DLLCHARACTERISTICS_NO_BIND, "NO_BIND");
208 X(IMAGE_DLLCHARACTERISTICS_WDM_DRIVER, "WDM_DRIVER");
209 X(IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE, "TERMINAL_SERVER_AWARE");
210 #undef X
213 static inline void print_datadirectory(DWORD n, const IMAGE_DATA_DIRECTORY *directory)
215 unsigned i;
216 printf("Data Directory\n");
218 for (i = 0; i < n && i < 16; i++)
220 printf(" %-12s rva: 0x%-8x size: 0x%-8x\n",
221 DirectoryNames[i], directory[i].VirtualAddress,
222 directory[i].Size);
226 static void dump_optional_header32(const IMAGE_OPTIONAL_HEADER32 *image_oh, UINT header_size)
228 IMAGE_OPTIONAL_HEADER32 oh;
229 const IMAGE_OPTIONAL_HEADER32 *optionalHeader;
231 /* in case optional header is missing or partial */
232 memset(&oh, 0, sizeof(oh));
233 memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
234 optionalHeader = &oh;
236 print_word("Magic", optionalHeader->Magic);
237 print_ver("linker version",
238 optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
239 print_dword("size of code", optionalHeader->SizeOfCode);
240 print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
241 print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
242 print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
243 print_dword("base of code", optionalHeader->BaseOfCode);
244 print_dword("base of data", optionalHeader->BaseOfData);
245 print_dword("image base", optionalHeader->ImageBase);
246 print_dword("section align", optionalHeader->SectionAlignment);
247 print_dword("file align", optionalHeader->FileAlignment);
248 print_ver("required OS version",
249 optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
250 print_ver("image version",
251 optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
252 print_ver("subsystem version",
253 optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
254 print_dword("Win32 Version", optionalHeader->Win32VersionValue);
255 print_dword("size of image", optionalHeader->SizeOfImage);
256 print_dword("size of headers", optionalHeader->SizeOfHeaders);
257 print_dword("checksum", optionalHeader->CheckSum);
258 print_subsys("Subsystem", optionalHeader->Subsystem);
259 print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
260 print_dword("stack reserve size", optionalHeader->SizeOfStackReserve);
261 print_dword("stack commit size", optionalHeader->SizeOfStackCommit);
262 print_dword("heap reserve size", optionalHeader->SizeOfHeapReserve);
263 print_dword("heap commit size", optionalHeader->SizeOfHeapCommit);
264 print_dword("loader flags", optionalHeader->LoaderFlags);
265 print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
266 printf("\n");
267 print_datadirectory(optionalHeader->NumberOfRvaAndSizes, optionalHeader->DataDirectory);
268 printf("\n");
271 static void dump_optional_header64(const IMAGE_OPTIONAL_HEADER64 *image_oh, UINT header_size)
273 IMAGE_OPTIONAL_HEADER64 oh;
274 const IMAGE_OPTIONAL_HEADER64 *optionalHeader;
276 /* in case optional header is missing or partial */
277 memset(&oh, 0, sizeof(oh));
278 memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
279 optionalHeader = &oh;
281 print_word("Magic", optionalHeader->Magic);
282 print_ver("linker version",
283 optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
284 print_dword("size of code", optionalHeader->SizeOfCode);
285 print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
286 print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
287 print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
288 print_dword("base of code", optionalHeader->BaseOfCode);
289 print_longlong("image base", optionalHeader->ImageBase);
290 print_dword("section align", optionalHeader->SectionAlignment);
291 print_dword("file align", optionalHeader->FileAlignment);
292 print_ver("required OS version",
293 optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
294 print_ver("image version",
295 optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
296 print_ver("subsystem version",
297 optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
298 print_dword("Win32 Version", optionalHeader->Win32VersionValue);
299 print_dword("size of image", optionalHeader->SizeOfImage);
300 print_dword("size of headers", optionalHeader->SizeOfHeaders);
301 print_dword("checksum", optionalHeader->CheckSum);
302 print_subsys("Subsystem", optionalHeader->Subsystem);
303 print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
304 print_longlong("stack reserve size", optionalHeader->SizeOfStackReserve);
305 print_longlong("stack commit size", optionalHeader->SizeOfStackCommit);
306 print_longlong("heap reserve size", optionalHeader->SizeOfHeapReserve);
307 print_longlong("heap commit size", optionalHeader->SizeOfHeapCommit);
308 print_dword("loader flags", optionalHeader->LoaderFlags);
309 print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
310 printf("\n");
311 print_datadirectory(optionalHeader->NumberOfRvaAndSizes, optionalHeader->DataDirectory);
312 printf("\n");
315 void dump_optional_header(const IMAGE_OPTIONAL_HEADER32 *optionalHeader, UINT header_size)
317 printf("Optional Header (%s)\n", get_magic_type(optionalHeader->Magic));
319 switch(optionalHeader->Magic) {
320 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
321 dump_optional_header32(optionalHeader, header_size);
322 break;
323 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
324 dump_optional_header64((const IMAGE_OPTIONAL_HEADER64 *)optionalHeader, header_size);
325 break;
326 default:
327 printf(" Unknown optional header magic: 0x%-4X\n", optionalHeader->Magic);
328 break;
332 void dump_file_header(const IMAGE_FILE_HEADER *fileHeader)
334 printf("File Header\n");
336 printf(" Machine: %04X (%s)\n",
337 fileHeader->Machine, get_machine_str(fileHeader->Machine));
338 printf(" Number of Sections: %d\n", fileHeader->NumberOfSections);
339 printf(" TimeDateStamp: %08X (%s) offset %lu\n",
340 fileHeader->TimeDateStamp, get_time_str(fileHeader->TimeDateStamp),
341 Offset(&(fileHeader->TimeDateStamp)));
342 printf(" PointerToSymbolTable: %08X\n", fileHeader->PointerToSymbolTable);
343 printf(" NumberOfSymbols: %08X\n", fileHeader->NumberOfSymbols);
344 printf(" SizeOfOptionalHeader: %04X\n", fileHeader->SizeOfOptionalHeader);
345 printf(" Characteristics: %04X\n", fileHeader->Characteristics);
346 #define X(f,s) if (fileHeader->Characteristics & f) printf(" %s\n", s)
347 X(IMAGE_FILE_RELOCS_STRIPPED, "RELOCS_STRIPPED");
348 X(IMAGE_FILE_EXECUTABLE_IMAGE, "EXECUTABLE_IMAGE");
349 X(IMAGE_FILE_LINE_NUMS_STRIPPED, "LINE_NUMS_STRIPPED");
350 X(IMAGE_FILE_LOCAL_SYMS_STRIPPED, "LOCAL_SYMS_STRIPPED");
351 X(IMAGE_FILE_AGGRESIVE_WS_TRIM, "AGGRESIVE_WS_TRIM");
352 X(IMAGE_FILE_LARGE_ADDRESS_AWARE, "LARGE_ADDRESS_AWARE");
353 X(IMAGE_FILE_16BIT_MACHINE, "16BIT_MACHINE");
354 X(IMAGE_FILE_BYTES_REVERSED_LO, "BYTES_REVERSED_LO");
355 X(IMAGE_FILE_32BIT_MACHINE, "32BIT_MACHINE");
356 X(IMAGE_FILE_DEBUG_STRIPPED, "DEBUG_STRIPPED");
357 X(IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "REMOVABLE_RUN_FROM_SWAP");
358 X(IMAGE_FILE_NET_RUN_FROM_SWAP, "NET_RUN_FROM_SWAP");
359 X(IMAGE_FILE_SYSTEM, "SYSTEM");
360 X(IMAGE_FILE_DLL, "DLL");
361 X(IMAGE_FILE_UP_SYSTEM_ONLY, "UP_SYSTEM_ONLY");
362 X(IMAGE_FILE_BYTES_REVERSED_HI, "BYTES_REVERSED_HI");
363 #undef X
364 printf("\n");
367 static void dump_pe_header(void)
369 dump_file_header(&PE_nt_headers->FileHeader);
370 dump_optional_header((const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader, PE_nt_headers->FileHeader.SizeOfOptionalHeader);
373 void dump_section(const IMAGE_SECTION_HEADER *sectHead)
375 printf(" %-8.8s VirtSize: 0x%08x VirtAddr: 0x%08x\n",
376 sectHead->Name, sectHead->Misc.VirtualSize, sectHead->VirtualAddress);
377 printf(" raw data offs: 0x%08x raw data size: 0x%08x\n",
378 sectHead->PointerToRawData, sectHead->SizeOfRawData);
379 printf(" relocation offs: 0x%08x relocations: 0x%08x\n",
380 sectHead->PointerToRelocations, sectHead->NumberOfRelocations);
381 printf(" line # offs: %-8u line #'s: %-8u\n",
382 sectHead->PointerToLinenumbers, sectHead->NumberOfLinenumbers);
383 printf(" characteristics: 0x%08x\n", sectHead->Characteristics);
384 printf(" ");
385 #define X(b,s) if (sectHead->Characteristics & b) printf(" " s)
386 /* #define IMAGE_SCN_TYPE_REG 0x00000000 - Reserved */
387 /* #define IMAGE_SCN_TYPE_DSECT 0x00000001 - Reserved */
388 /* #define IMAGE_SCN_TYPE_NOLOAD 0x00000002 - Reserved */
389 /* #define IMAGE_SCN_TYPE_GROUP 0x00000004 - Reserved */
390 /* #define IMAGE_SCN_TYPE_NO_PAD 0x00000008 - Reserved */
391 /* #define IMAGE_SCN_TYPE_COPY 0x00000010 - Reserved */
393 X(IMAGE_SCN_CNT_CODE, "CODE");
394 X(IMAGE_SCN_CNT_INITIALIZED_DATA, "INITIALIZED_DATA");
395 X(IMAGE_SCN_CNT_UNINITIALIZED_DATA, "UNINITIALIZED_DATA");
397 X(IMAGE_SCN_LNK_OTHER, "LNK_OTHER");
398 X(IMAGE_SCN_LNK_INFO, "LNK_INFO");
399 /* #define IMAGE_SCN_TYPE_OVER 0x00000400 - Reserved */
400 X(IMAGE_SCN_LNK_REMOVE, "LNK_REMOVE");
401 X(IMAGE_SCN_LNK_COMDAT, "LNK_COMDAT");
403 /* 0x00002000 - Reserved */
404 /* #define IMAGE_SCN_MEM_PROTECTED 0x00004000 - Obsolete */
405 X(IMAGE_SCN_MEM_FARDATA, "MEM_FARDATA");
407 /* #define IMAGE_SCN_MEM_SYSHEAP 0x00010000 - Obsolete */
408 X(IMAGE_SCN_MEM_PURGEABLE, "MEM_PURGEABLE");
409 X(IMAGE_SCN_MEM_16BIT, "MEM_16BIT");
410 X(IMAGE_SCN_MEM_LOCKED, "MEM_LOCKED");
411 X(IMAGE_SCN_MEM_PRELOAD, "MEM_PRELOAD");
413 switch (sectHead->Characteristics & IMAGE_SCN_ALIGN_MASK)
415 #define X2(b,s) case b: printf(" " s); break
416 X2(IMAGE_SCN_ALIGN_1BYTES, "ALIGN_1BYTES");
417 X2(IMAGE_SCN_ALIGN_2BYTES, "ALIGN_2BYTES");
418 X2(IMAGE_SCN_ALIGN_4BYTES, "ALIGN_4BYTES");
419 X2(IMAGE_SCN_ALIGN_8BYTES, "ALIGN_8BYTES");
420 X2(IMAGE_SCN_ALIGN_16BYTES, "ALIGN_16BYTES");
421 X2(IMAGE_SCN_ALIGN_32BYTES, "ALIGN_32BYTES");
422 X2(IMAGE_SCN_ALIGN_64BYTES, "ALIGN_64BYTES");
423 X2(IMAGE_SCN_ALIGN_128BYTES, "ALIGN_128BYTES");
424 X2(IMAGE_SCN_ALIGN_256BYTES, "ALIGN_256BYTES");
425 X2(IMAGE_SCN_ALIGN_512BYTES, "ALIGN_512BYTES");
426 X2(IMAGE_SCN_ALIGN_1024BYTES, "ALIGN_1024BYTES");
427 X2(IMAGE_SCN_ALIGN_2048BYTES, "ALIGN_2048BYTES");
428 X2(IMAGE_SCN_ALIGN_4096BYTES, "ALIGN_4096BYTES");
429 X2(IMAGE_SCN_ALIGN_8192BYTES, "ALIGN_8192BYTES");
430 #undef X2
433 X(IMAGE_SCN_LNK_NRELOC_OVFL, "LNK_NRELOC_OVFL");
435 X(IMAGE_SCN_MEM_DISCARDABLE, "MEM_DISCARDABLE");
436 X(IMAGE_SCN_MEM_NOT_CACHED, "MEM_NOT_CACHED");
437 X(IMAGE_SCN_MEM_NOT_PAGED, "MEM_NOT_PAGED");
438 X(IMAGE_SCN_MEM_SHARED, "MEM_SHARED");
439 X(IMAGE_SCN_MEM_EXECUTE, "MEM_EXECUTE");
440 X(IMAGE_SCN_MEM_READ, "MEM_READ");
441 X(IMAGE_SCN_MEM_WRITE, "MEM_WRITE");
442 #undef X
443 printf("\n\n");
446 static void dump_sections(const void *base, const void* addr, unsigned num_sect)
448 const IMAGE_SECTION_HEADER* sectHead = addr;
449 unsigned i;
451 printf("Section Table\n");
452 for (i = 0; i < num_sect; i++, sectHead++)
454 dump_section(sectHead);
456 if (globals.do_dump_rawdata)
458 dump_data((const unsigned char *)base + sectHead->PointerToRawData, sectHead->SizeOfRawData, " " );
459 printf("\n");
464 static void dump_dir_exported_functions(void)
466 unsigned int size = 0;
467 const IMAGE_EXPORT_DIRECTORY*exportDir = get_dir_and_size(IMAGE_FILE_EXPORT_DIRECTORY, &size);
468 unsigned int i;
469 const DWORD* pFunc;
470 const DWORD* pName;
471 const WORD* pOrdl;
472 DWORD* funcs;
474 if (!exportDir) return;
476 printf("Exports table:\n");
477 printf("\n");
478 printf(" Name: %s\n", (const char*)RVA(exportDir->Name, sizeof(DWORD)));
479 printf(" Characteristics: %08x\n", exportDir->Characteristics);
480 printf(" TimeDateStamp: %08X %s\n",
481 exportDir->TimeDateStamp, get_time_str(exportDir->TimeDateStamp));
482 printf(" Version: %u.%02u\n", exportDir->MajorVersion, exportDir->MinorVersion);
483 printf(" Ordinal base: %u\n", exportDir->Base);
484 printf(" # of functions: %u\n", exportDir->NumberOfFunctions);
485 printf(" # of Names: %u\n", exportDir->NumberOfNames);
486 printf("Addresses of functions: %08X\n", exportDir->AddressOfFunctions);
487 printf("Addresses of name ordinals: %08X\n", exportDir->AddressOfNameOrdinals);
488 printf("Addresses of names: %08X\n", exportDir->AddressOfNames);
489 printf("\n");
490 printf(" Entry Pt Ordn Name\n");
492 pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
493 if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
494 pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
495 if (!pName) {printf("Can't grab functions' name table\n"); return;}
496 pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
497 if (!pOrdl) {printf("Can't grab functions' ordinal table\n"); return;}
499 funcs = calloc( exportDir->NumberOfFunctions, sizeof(*funcs) );
500 if (!funcs) fatal("no memory");
502 for (i = 0; i < exportDir->NumberOfNames; i++) funcs[pOrdl[i]] = pName[i];
504 for (i = 0; i < exportDir->NumberOfFunctions; i++)
506 if (!pFunc[i]) continue;
507 printf(" %08X %5u ", pFunc[i], exportDir->Base + i);
508 if (funcs[i])
510 printf("%s", get_symbol_str((const char*)RVA(funcs[i], sizeof(DWORD))));
511 /* check for forwarded function */
512 if ((const char *)RVA(pFunc[i],1) >= (const char *)exportDir &&
513 (const char *)RVA(pFunc[i],1) < (const char *)exportDir + size)
514 printf(" (-> %s)", (const char *)RVA(pFunc[i],1));
515 printf("\n");
517 else printf("<by ordinal>\n");
519 free(funcs);
520 printf("\n");
524 struct runtime_function
526 DWORD BeginAddress;
527 DWORD EndAddress;
528 DWORD UnwindData;
531 union handler_data
533 struct runtime_function chain;
534 DWORD handler;
537 struct opcode
539 BYTE offset;
540 BYTE code : 4;
541 BYTE info : 4;
544 struct unwind_info
546 BYTE version : 3;
547 BYTE flags : 5;
548 BYTE prolog;
549 BYTE count;
550 BYTE frame_reg : 4;
551 BYTE frame_offset : 4;
552 struct opcode opcodes[1]; /* count entries */
553 /* followed by union handler_data */
556 #define UWOP_PUSH_NONVOL 0
557 #define UWOP_ALLOC_LARGE 1
558 #define UWOP_ALLOC_SMALL 2
559 #define UWOP_SET_FPREG 3
560 #define UWOP_SAVE_NONVOL 4
561 #define UWOP_SAVE_NONVOL_FAR 5
562 #define UWOP_SAVE_XMM128 8
563 #define UWOP_SAVE_XMM128_FAR 9
564 #define UWOP_PUSH_MACHFRAME 10
566 #define UNW_FLAG_EHANDLER 1
567 #define UNW_FLAG_UHANDLER 2
568 #define UNW_FLAG_CHAININFO 4
570 static void dump_x86_64_unwind_info( const struct runtime_function *function )
572 static const char * const reg_names[16] =
573 { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
574 "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" };
576 union handler_data *handler_data;
577 const struct unwind_info *info;
578 unsigned int i, count;
580 printf( "\nFunction %08x-%08x:\n", function->BeginAddress, function->EndAddress );
581 if (function->UnwindData & 1)
583 const struct runtime_function *next = RVA( function->UnwindData & ~1, sizeof(*next) );
584 printf( " -> function %08x-%08x\n", next->BeginAddress, next->EndAddress );
585 return;
587 info = RVA( function->UnwindData, sizeof(*info) );
589 printf( " unwind info at %08x\n", function->UnwindData );
590 if (info->version != 1)
592 printf( " *** unknown version %u\n", info->version );
593 return;
595 printf( " flags %x", info->flags );
596 if (info->flags & UNW_FLAG_EHANDLER) printf( " EHANDLER" );
597 if (info->flags & UNW_FLAG_UHANDLER) printf( " UHANDLER" );
598 if (info->flags & UNW_FLAG_CHAININFO) printf( " CHAININFO" );
599 printf( "\n prolog 0x%x bytes\n", info->prolog );
601 if (info->frame_reg)
602 printf( " frame register %s offset 0x%x(%%rsp)\n",
603 reg_names[info->frame_reg], info->frame_offset * 16 );
605 for (i = 0; i < info->count; i++)
607 printf( " 0x%02x: ", info->opcodes[i].offset );
608 switch (info->opcodes[i].code)
610 case UWOP_PUSH_NONVOL:
611 printf( "push %%%s\n", reg_names[info->opcodes[i].info] );
612 break;
613 case UWOP_ALLOC_LARGE:
614 if (info->opcodes[i].info)
616 count = *(DWORD *)&info->opcodes[i+1];
617 i += 2;
619 else
621 count = *(USHORT *)&info->opcodes[i+1] * 8;
622 i++;
624 printf( "sub $0x%x,%%rsp\n", count );
625 break;
626 case UWOP_ALLOC_SMALL:
627 count = (info->opcodes[i].info + 1) * 8;
628 printf( "sub $0x%x,%%rsp\n", count );
629 break;
630 case UWOP_SET_FPREG:
631 printf( "lea 0x%x(%%rsp),%s\n",
632 info->frame_offset * 16, reg_names[info->frame_reg] );
633 break;
634 case UWOP_SAVE_NONVOL:
635 count = *(USHORT *)&info->opcodes[i+1] * 8;
636 printf( "mov %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
637 i++;
638 break;
639 case UWOP_SAVE_NONVOL_FAR:
640 count = *(DWORD *)&info->opcodes[i+1];
641 printf( "mov %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
642 i += 2;
643 break;
644 case UWOP_SAVE_XMM128:
645 count = *(USHORT *)&info->opcodes[i+1] * 16;
646 printf( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
647 i++;
648 break;
649 case UWOP_SAVE_XMM128_FAR:
650 count = *(DWORD *)&info->opcodes[i+1];
651 printf( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
652 i += 2;
653 break;
654 case UWOP_PUSH_MACHFRAME:
655 printf( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
656 break;
657 default:
658 printf( "*** unknown code %u\n", info->opcodes[i].code );
659 break;
663 handler_data = (union handler_data *)&info->opcodes[(info->count + 1) & ~1];
664 if (info->flags & UNW_FLAG_CHAININFO)
666 printf( " -> function %08x-%08x\n",
667 handler_data->chain.BeginAddress, handler_data->chain.EndAddress );
668 return;
670 if (info->flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER))
671 printf( " handler %08x data at %08x\n", handler_data->handler,
672 (ULONG)(function->UnwindData + (char *)(&handler_data->handler + 1) - (char *)info ));
675 static void dump_dir_exceptions(void)
677 unsigned int i, size = 0;
678 const struct runtime_function *funcs = get_dir_and_size(IMAGE_FILE_EXCEPTION_DIRECTORY, &size);
679 const IMAGE_FILE_HEADER *file_header = &PE_nt_headers->FileHeader;
681 if (!funcs) return;
683 if (file_header->Machine == IMAGE_FILE_MACHINE_AMD64)
685 size /= sizeof(*funcs);
686 printf( "Exception info (%u functions):\n", size );
687 for (i = 0; i < size; i++) dump_x86_64_unwind_info( funcs + i );
689 else printf( "Exception information not supported for %s binaries\n",
690 get_machine_str(file_header->Machine));
694 static void dump_image_thunk_data64(const IMAGE_THUNK_DATA64 *il)
696 /* FIXME: This does not properly handle large images */
697 const IMAGE_IMPORT_BY_NAME* iibn;
698 for (; il->u1.Ordinal; il++)
700 if (IMAGE_SNAP_BY_ORDINAL64(il->u1.Ordinal))
701 printf(" %4u <by ordinal>\n", (DWORD)IMAGE_ORDINAL64(il->u1.Ordinal));
702 else
704 iibn = RVA((DWORD)il->u1.AddressOfData, sizeof(DWORD));
705 if (!iibn)
706 printf("Can't grab import by name info, skipping to next ordinal\n");
707 else
708 printf(" %4u %s %x\n", iibn->Hint, iibn->Name, (DWORD)il->u1.AddressOfData);
713 static void dump_image_thunk_data32(const IMAGE_THUNK_DATA32 *il, int offset)
715 const IMAGE_IMPORT_BY_NAME* iibn;
716 for (; il->u1.Ordinal; il++)
718 if (IMAGE_SNAP_BY_ORDINAL32(il->u1.Ordinal))
719 printf(" %4u <by ordinal>\n", IMAGE_ORDINAL32(il->u1.Ordinal));
720 else
722 iibn = RVA((DWORD)il->u1.AddressOfData - offset, sizeof(DWORD));
723 if (!iibn)
724 printf("Can't grab import by name info, skipping to next ordinal\n");
725 else
726 printf(" %4u %s %x\n", iibn->Hint, iibn->Name, (DWORD)il->u1.AddressOfData);
731 static void dump_dir_imported_functions(void)
733 const IMAGE_IMPORT_DESCRIPTOR *importDesc = get_dir(IMAGE_FILE_IMPORT_DIRECTORY);
734 DWORD directorySize;
736 if (!importDesc) return;
737 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
739 const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
740 directorySize = opt->DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY].Size;
742 else
744 const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
745 directorySize = opt->DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY].Size;
748 printf("Import Table size: %08x\n", directorySize);/* FIXME */
750 for (;;)
752 const IMAGE_THUNK_DATA32* il;
754 if (!importDesc->Name || !importDesc->FirstThunk) break;
756 printf(" offset %08lx %s\n", Offset(importDesc), (const char*)RVA(importDesc->Name, sizeof(DWORD)));
757 printf(" Hint/Name Table: %08X\n", (DWORD)importDesc->u.OriginalFirstThunk);
758 printf(" TimeDateStamp: %08X (%s)\n",
759 importDesc->TimeDateStamp, get_time_str(importDesc->TimeDateStamp));
760 printf(" ForwarderChain: %08X\n", importDesc->ForwarderChain);
761 printf(" First thunk RVA: %08X\n", (DWORD)importDesc->FirstThunk);
763 printf(" Ordn Name\n");
765 il = (importDesc->u.OriginalFirstThunk != 0) ?
766 RVA((DWORD)importDesc->u.OriginalFirstThunk, sizeof(DWORD)) :
767 RVA((DWORD)importDesc->FirstThunk, sizeof(DWORD));
769 if (!il)
770 printf("Can't grab thunk data, going to next imported DLL\n");
771 else
773 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
774 dump_image_thunk_data64((const IMAGE_THUNK_DATA64*)il);
775 else
776 dump_image_thunk_data32(il, 0);
777 printf("\n");
779 importDesc++;
781 printf("\n");
784 static void dump_dir_delay_imported_functions(void)
786 const struct ImgDelayDescr
788 DWORD grAttrs;
789 DWORD szName;
790 DWORD phmod;
791 DWORD pIAT;
792 DWORD pINT;
793 DWORD pBoundIAT;
794 DWORD pUnloadIAT;
795 DWORD dwTimeStamp;
796 } *importDesc = get_dir(IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT);
797 DWORD directorySize;
799 if (!importDesc) return;
800 if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
802 const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64 *)&PE_nt_headers->OptionalHeader;
803 directorySize = opt->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
805 else
807 const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32 *)&PE_nt_headers->OptionalHeader;
808 directorySize = opt->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
811 printf("Delay Import Table size: %08x\n", directorySize); /* FIXME */
813 for (;;)
815 const IMAGE_THUNK_DATA32* il;
816 int offset = (importDesc->grAttrs & 1) ? 0 : PE_nt_headers->OptionalHeader.ImageBase;
818 if (!importDesc->szName || !importDesc->pIAT || !importDesc->pINT) break;
820 printf(" grAttrs %08x offset %08lx %s\n", importDesc->grAttrs, Offset(importDesc),
821 (const char *)RVA(importDesc->szName - offset, sizeof(DWORD)));
822 printf(" Hint/Name Table: %08x\n", importDesc->pINT);
823 printf(" TimeDateStamp: %08X (%s)\n",
824 importDesc->dwTimeStamp, get_time_str(importDesc->dwTimeStamp));
826 printf(" Ordn Name\n");
828 il = RVA(importDesc->pINT - offset, sizeof(DWORD));
830 if (!il)
831 printf("Can't grab thunk data, going to next imported DLL\n");
832 else
834 if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
835 dump_image_thunk_data64((const IMAGE_THUNK_DATA64 *)il);
836 else
837 dump_image_thunk_data32(il, offset);
838 printf("\n");
840 importDesc++;
842 printf("\n");
845 static void dump_dir_debug_dir(const IMAGE_DEBUG_DIRECTORY* idd, int idx)
847 const char* str;
849 printf("Directory %02u\n", idx + 1);
850 printf(" Characteristics: %08X\n", idd->Characteristics);
851 printf(" TimeDateStamp: %08X %s\n",
852 idd->TimeDateStamp, get_time_str(idd->TimeDateStamp));
853 printf(" Version %u.%02u\n", idd->MajorVersion, idd->MinorVersion);
854 switch (idd->Type)
856 default:
857 case IMAGE_DEBUG_TYPE_UNKNOWN: str = "UNKNOWN"; break;
858 case IMAGE_DEBUG_TYPE_COFF: str = "COFF"; break;
859 case IMAGE_DEBUG_TYPE_CODEVIEW: str = "CODEVIEW"; break;
860 case IMAGE_DEBUG_TYPE_FPO: str = "FPO"; break;
861 case IMAGE_DEBUG_TYPE_MISC: str = "MISC"; break;
862 case IMAGE_DEBUG_TYPE_EXCEPTION: str = "EXCEPTION"; break;
863 case IMAGE_DEBUG_TYPE_FIXUP: str = "FIXUP"; break;
864 case IMAGE_DEBUG_TYPE_OMAP_TO_SRC: str = "OMAP_TO_SRC"; break;
865 case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:str = "OMAP_FROM_SRC"; break;
866 case IMAGE_DEBUG_TYPE_BORLAND: str = "BORLAND"; break;
867 case IMAGE_DEBUG_TYPE_RESERVED10: str = "RESERVED10"; break;
869 printf(" Type: %u (%s)\n", idd->Type, str);
870 printf(" SizeOfData: %u\n", idd->SizeOfData);
871 printf(" AddressOfRawData: %08X\n", idd->AddressOfRawData);
872 printf(" PointerToRawData: %08X\n", idd->PointerToRawData);
874 switch (idd->Type)
876 case IMAGE_DEBUG_TYPE_UNKNOWN:
877 break;
878 case IMAGE_DEBUG_TYPE_COFF:
879 dump_coff(idd->PointerToRawData, idd->SizeOfData,
880 (const char*)PE_nt_headers + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader);
881 break;
882 case IMAGE_DEBUG_TYPE_CODEVIEW:
883 dump_codeview(idd->PointerToRawData, idd->SizeOfData);
884 break;
885 case IMAGE_DEBUG_TYPE_FPO:
886 dump_frame_pointer_omission(idd->PointerToRawData, idd->SizeOfData);
887 break;
888 case IMAGE_DEBUG_TYPE_MISC:
890 const IMAGE_DEBUG_MISC* misc = PRD(idd->PointerToRawData, idd->SizeOfData);
891 if (!misc) {printf("Can't get misc debug information\n"); break;}
892 printf(" DataType: %u (%s)\n",
893 misc->DataType,
894 (misc->DataType == IMAGE_DEBUG_MISC_EXENAME) ? "Exe name" : "Unknown");
895 printf(" Length: %u\n", misc->Length);
896 printf(" Unicode: %s\n", misc->Unicode ? "Yes" : "No");
897 printf(" Data: %s\n", misc->Data);
899 break;
900 case IMAGE_DEBUG_TYPE_EXCEPTION:
901 break;
902 case IMAGE_DEBUG_TYPE_FIXUP:
903 break;
904 case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:
905 break;
906 case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:
907 break;
908 case IMAGE_DEBUG_TYPE_BORLAND:
909 break;
910 case IMAGE_DEBUG_TYPE_RESERVED10:
911 break;
913 printf("\n");
916 static void dump_dir_debug(void)
918 const IMAGE_DEBUG_DIRECTORY*debugDir = get_dir(IMAGE_FILE_DEBUG_DIRECTORY);
919 unsigned nb_dbg, i;
921 if (!debugDir) return;
922 nb_dbg = PE_nt_headers->OptionalHeader.DataDirectory[IMAGE_FILE_DEBUG_DIRECTORY].Size /
923 sizeof(*debugDir);
924 if (!nb_dbg) return;
926 printf("Debug Table (%u directories)\n", nb_dbg);
928 for (i = 0; i < nb_dbg; i++)
930 dump_dir_debug_dir(debugDir, i);
931 debugDir++;
933 printf("\n");
936 static inline void print_clrflags(const char *title, WORD value)
938 printf(" %-34s 0x%X\n", title, value);
939 #define X(f,s) if (value & f) printf(" %s\n", s)
940 X(COMIMAGE_FLAGS_ILONLY, "ILONLY");
941 X(COMIMAGE_FLAGS_32BITREQUIRED, "32BITREQUIRED");
942 X(COMIMAGE_FLAGS_IL_LIBRARY, "IL_LIBRARY");
943 X(COMIMAGE_FLAGS_STRONGNAMESIGNED, "STRONGNAMESIGNED");
944 X(COMIMAGE_FLAGS_TRACKDEBUGDATA, "TRACKDEBUGDATA");
945 #undef X
948 static inline void print_clrdirectory(const char *title, const IMAGE_DATA_DIRECTORY *dir)
950 printf(" %-23s rva: 0x%-8x size: 0x%-8x\n", title, dir->VirtualAddress, dir->Size);
953 static void dump_dir_clr_header(void)
955 unsigned int size = 0;
956 const IMAGE_COR20_HEADER *dir = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &size);
958 if (!dir) return;
960 printf( "CLR Header\n" );
961 print_dword( "Header Size", dir->cb );
962 print_ver( "Required runtime version", dir->MajorRuntimeVersion, dir->MinorRuntimeVersion );
963 print_clrflags( "Flags", dir->Flags );
964 print_dword( "EntryPointToken", dir->EntryPointToken );
965 printf("\n");
966 printf( "CLR Data Directory\n" );
967 print_clrdirectory( "MetaData", &dir->MetaData );
968 print_clrdirectory( "Resources", &dir->Resources );
969 print_clrdirectory( "StrongNameSignature", &dir->StrongNameSignature );
970 print_clrdirectory( "CodeManagerTable", &dir->CodeManagerTable );
971 print_clrdirectory( "VTableFixups", &dir->VTableFixups );
972 print_clrdirectory( "ExportAddressTableJumps", &dir->ExportAddressTableJumps );
973 print_clrdirectory( "ManagedNativeHeader", &dir->ManagedNativeHeader );
974 printf("\n");
977 static void dump_dir_reloc(void)
979 unsigned int i, size = 0;
980 const USHORT *relocs;
981 const IMAGE_BASE_RELOCATION *rel = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_BASERELOC, &size);
982 const IMAGE_BASE_RELOCATION *end = (IMAGE_BASE_RELOCATION *)((char *)rel + size);
983 static const char * const names[] =
985 "BASED_ABSOLUTE",
986 "BASED_HIGH",
987 "BASED_LOW",
988 "BASED_HIGHLOW",
989 "BASED_HIGHADJ",
990 "BASED_MIPS_JMPADDR",
991 "BASED_SECTION",
992 "BASED_REL",
993 "unknown 8",
994 "BASED_IA64_IMM64",
995 "BASED_DIR64",
996 "BASED_HIGH3ADJ",
997 "unknown 12",
998 "unknown 13",
999 "unknown 14",
1000 "unknown 15"
1003 if (!rel) return;
1005 printf( "Relocations\n" );
1006 while (rel < end - 1 && rel->SizeOfBlock)
1008 printf( " Page %x\n", rel->VirtualAddress );
1009 relocs = (const USHORT *)(rel + 1);
1010 i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT);
1011 while (i--)
1013 USHORT offset = *relocs & 0xfff;
1014 int type = *relocs >> 12;
1015 printf( " off %04x type %s\n", offset, names[type] );
1016 relocs++;
1018 rel = (const IMAGE_BASE_RELOCATION *)relocs;
1020 printf("\n");
1023 static void dump_dir_tls(void)
1025 IMAGE_TLS_DIRECTORY64 dir;
1026 const DWORD *callbacks;
1027 const IMAGE_TLS_DIRECTORY32 *pdir = get_dir(IMAGE_FILE_THREAD_LOCAL_STORAGE);
1029 if (!pdir) return;
1031 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1032 memcpy(&dir, pdir, sizeof(dir));
1033 else
1035 dir.StartAddressOfRawData = pdir->StartAddressOfRawData;
1036 dir.EndAddressOfRawData = pdir->EndAddressOfRawData;
1037 dir.AddressOfIndex = pdir->AddressOfIndex;
1038 dir.AddressOfCallBacks = pdir->AddressOfCallBacks;
1039 dir.SizeOfZeroFill = pdir->SizeOfZeroFill;
1040 dir.Characteristics = pdir->Characteristics;
1043 /* FIXME: This does not properly handle large images */
1044 printf( "Thread Local Storage\n" );
1045 printf( " Raw data %08x-%08x (data size %x zero fill size %x)\n",
1046 (DWORD)dir.StartAddressOfRawData, (DWORD)dir.EndAddressOfRawData,
1047 (DWORD)(dir.EndAddressOfRawData - dir.StartAddressOfRawData),
1048 (DWORD)dir.SizeOfZeroFill );
1049 printf( " Index address %08x\n", (DWORD)dir.AddressOfIndex );
1050 printf( " Characteristics %08x\n", dir.Characteristics );
1051 printf( " Callbacks %08x -> {", (DWORD)dir.AddressOfCallBacks );
1052 if (dir.AddressOfCallBacks)
1054 DWORD addr = (DWORD)dir.AddressOfCallBacks - PE_nt_headers->OptionalHeader.ImageBase;
1055 while ((callbacks = RVA(addr, sizeof(DWORD))) && *callbacks)
1057 printf( " %08x", *callbacks );
1058 addr += sizeof(DWORD);
1061 printf(" }\n\n");
1064 enum FileSig get_kind_dbg(void)
1066 const WORD* pw;
1068 pw = PRD(0, sizeof(WORD));
1069 if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}
1071 if (*pw == 0x4944 /* "DI" */) return SIG_DBG;
1072 return SIG_UNKNOWN;
1075 void dbg_dump(void)
1077 const IMAGE_SEPARATE_DEBUG_HEADER* separateDebugHead;
1078 unsigned nb_dbg;
1079 unsigned i;
1080 const IMAGE_DEBUG_DIRECTORY* debugDir;
1082 separateDebugHead = PRD(0, sizeof(separateDebugHead));
1083 if (!separateDebugHead) {printf("Can't grab the separate header, aborting\n"); return;}
1085 printf ("Signature: %.2s (0x%4X)\n",
1086 (const char*)&separateDebugHead->Signature, separateDebugHead->Signature);
1087 printf ("Flags: 0x%04X\n", separateDebugHead->Flags);
1088 printf ("Machine: 0x%04X (%s)\n",
1089 separateDebugHead->Machine, get_machine_str(separateDebugHead->Machine));
1090 printf ("Characteristics: 0x%04X\n", separateDebugHead->Characteristics);
1091 printf ("TimeDateStamp: 0x%08X (%s)\n",
1092 separateDebugHead->TimeDateStamp, get_time_str(separateDebugHead->TimeDateStamp));
1093 printf ("CheckSum: 0x%08X\n", separateDebugHead->CheckSum);
1094 printf ("ImageBase: 0x%08X\n", separateDebugHead->ImageBase);
1095 printf ("SizeOfImage: 0x%08X\n", separateDebugHead->SizeOfImage);
1096 printf ("NumberOfSections: 0x%08X\n", separateDebugHead->NumberOfSections);
1097 printf ("ExportedNamesSize: 0x%08X\n", separateDebugHead->ExportedNamesSize);
1098 printf ("DebugDirectorySize: 0x%08X\n", separateDebugHead->DebugDirectorySize);
1100 if (!PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER),
1101 separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER)))
1102 {printf("Can't get the sections, aborting\n"); return;}
1104 dump_sections(separateDebugHead, separateDebugHead + 1, separateDebugHead->NumberOfSections);
1106 nb_dbg = separateDebugHead->DebugDirectorySize / sizeof(IMAGE_DEBUG_DIRECTORY);
1107 debugDir = PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER) +
1108 separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
1109 separateDebugHead->ExportedNamesSize,
1110 nb_dbg * sizeof(IMAGE_DEBUG_DIRECTORY));
1111 if (!debugDir) {printf("Couldn't get the debug directory info, aborting\n");return;}
1113 printf("Debug Table (%u directories)\n", nb_dbg);
1115 for (i = 0; i < nb_dbg; i++)
1117 dump_dir_debug_dir(debugDir, i);
1118 debugDir++;
1122 static const char *get_resource_type( unsigned int id )
1124 static const char * const types[] =
1126 NULL,
1127 "CURSOR",
1128 "BITMAP",
1129 "ICON",
1130 "MENU",
1131 "DIALOG",
1132 "STRING",
1133 "FONTDIR",
1134 "FONT",
1135 "ACCELERATOR",
1136 "RCDATA",
1137 "MESSAGETABLE",
1138 "GROUP_CURSOR",
1139 NULL,
1140 "GROUP_ICON",
1141 NULL,
1142 "VERSION",
1143 "DLGINCLUDE",
1144 NULL,
1145 "PLUGPLAY",
1146 "VXD",
1147 "ANICURSOR",
1148 "ANIICON",
1149 "HTML",
1150 "RT_MANIFEST"
1153 if ((size_t)id < sizeof(types)/sizeof(types[0])) return types[id];
1154 return NULL;
1157 /* dump an ASCII string with proper escaping */
1158 static int dump_strA( const unsigned char *str, size_t len )
1160 static const char escapes[32] = ".......abtnvfr.............e....";
1161 char buffer[256];
1162 char *pos = buffer;
1163 int count = 0;
1165 for (; len; str++, len--)
1167 if (pos > buffer + sizeof(buffer) - 8)
1169 fwrite( buffer, pos - buffer, 1, stdout );
1170 count += pos - buffer;
1171 pos = buffer;
1173 if (*str > 127) /* hex escape */
1175 pos += sprintf( pos, "\\x%02x", *str );
1176 continue;
1178 if (*str < 32) /* octal or C escape */
1180 if (!*str && len == 1) continue; /* do not output terminating NULL */
1181 if (escapes[*str] != '.')
1182 pos += sprintf( pos, "\\%c", escapes[*str] );
1183 else if (len > 1 && str[1] >= '0' && str[1] <= '7')
1184 pos += sprintf( pos, "\\%03o", *str );
1185 else
1186 pos += sprintf( pos, "\\%o", *str );
1187 continue;
1189 if (*str == '\\') *pos++ = '\\';
1190 *pos++ = *str;
1192 fwrite( buffer, pos - buffer, 1, stdout );
1193 count += pos - buffer;
1194 return count;
1197 /* dump a Unicode string with proper escaping */
1198 static int dump_strW( const WCHAR *str, size_t len )
1200 static const char escapes[32] = ".......abtnvfr.............e....";
1201 char buffer[256];
1202 char *pos = buffer;
1203 int count = 0;
1205 for (; len; str++, len--)
1207 if (pos > buffer + sizeof(buffer) - 8)
1209 fwrite( buffer, pos - buffer, 1, stdout );
1210 count += pos - buffer;
1211 pos = buffer;
1213 if (*str > 127) /* hex escape */
1215 if (len > 1 && str[1] < 128 && isxdigit((char)str[1]))
1216 pos += sprintf( pos, "\\x%04x", *str );
1217 else
1218 pos += sprintf( pos, "\\x%x", *str );
1219 continue;
1221 if (*str < 32) /* octal or C escape */
1223 if (!*str && len == 1) continue; /* do not output terminating NULL */
1224 if (escapes[*str] != '.')
1225 pos += sprintf( pos, "\\%c", escapes[*str] );
1226 else if (len > 1 && str[1] >= '0' && str[1] <= '7')
1227 pos += sprintf( pos, "\\%03o", *str );
1228 else
1229 pos += sprintf( pos, "\\%o", *str );
1230 continue;
1232 if (*str == '\\') *pos++ = '\\';
1233 *pos++ = *str;
1235 fwrite( buffer, pos - buffer, 1, stdout );
1236 count += pos - buffer;
1237 return count;
1240 /* dump data for a STRING resource */
1241 static void dump_string_data( const WCHAR *ptr, unsigned int size, unsigned int id, const char *prefix )
1243 int i;
1245 for (i = 0; i < 16 && size; i++)
1247 unsigned len = *ptr++;
1249 if (len >= size)
1251 len = size;
1252 size = 0;
1254 else size -= len + 1;
1256 if (len)
1258 printf( "%s%04x \"", prefix, (id - 1) * 16 + i );
1259 dump_strW( ptr, len );
1260 printf( "\"\n" );
1261 ptr += len;
1266 /* dump data for a MESSAGETABLE resource */
1267 static void dump_msgtable_data( const void *ptr, unsigned int size, unsigned int id, const char *prefix )
1269 const MESSAGE_RESOURCE_DATA *data = ptr;
1270 const MESSAGE_RESOURCE_BLOCK *block = data->Blocks;
1271 unsigned i, j;
1273 for (i = 0; i < data->NumberOfBlocks; i++, block++)
1275 const MESSAGE_RESOURCE_ENTRY *entry;
1277 entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)data + block->OffsetToEntries);
1278 for (j = block->LowId; j <= block->HighId; j++)
1280 if (entry->Flags & MESSAGE_RESOURCE_UNICODE)
1282 const WCHAR *str = (const WCHAR *)entry->Text;
1283 printf( "%s%08x L\"", prefix, j );
1284 dump_strW( str, strlenW(str) );
1285 printf( "\"\n" );
1287 else
1289 const char *str = (const char *) entry->Text;
1290 printf( "%s%08x \"", prefix, j );
1291 dump_strA( entry->Text, strlen(str) );
1292 printf( "\"\n" );
1294 entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)entry + entry->Length);
1299 static void dump_dir_resource(void)
1301 const IMAGE_RESOURCE_DIRECTORY *root = get_dir(IMAGE_FILE_RESOURCE_DIRECTORY);
1302 const IMAGE_RESOURCE_DIRECTORY *namedir;
1303 const IMAGE_RESOURCE_DIRECTORY *langdir;
1304 const IMAGE_RESOURCE_DIRECTORY_ENTRY *e1, *e2, *e3;
1305 const IMAGE_RESOURCE_DIR_STRING_U *string;
1306 const IMAGE_RESOURCE_DATA_ENTRY *data;
1307 int i, j, k;
1309 if (!root) return;
1311 printf( "Resources:" );
1313 for (i = 0; i< root->NumberOfNamedEntries + root->NumberOfIdEntries; i++)
1315 e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
1316 namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s3.OffsetToDirectory);
1317 for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
1319 e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
1320 langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s3.OffsetToDirectory);
1321 for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
1323 e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
1325 printf( "\n " );
1326 if (e1->u1.s1.NameIsString)
1328 string = (const IMAGE_RESOURCE_DIR_STRING_U*)((const char *)root + e1->u1.s1.NameOffset);
1329 dump_unicode_str( string->NameString, string->Length );
1331 else
1333 const char *type = get_resource_type( e1->u1.s2.Id );
1334 if (type) printf( "%s", type );
1335 else printf( "%04x", e1->u1.s2.Id );
1338 printf( " Name=" );
1339 if (e2->u1.s1.NameIsString)
1341 string = (const IMAGE_RESOURCE_DIR_STRING_U*) ((const char *)root + e2->u1.s1.NameOffset);
1342 dump_unicode_str( string->NameString, string->Length );
1344 else
1345 printf( "%04x", e2->u1.s2.Id );
1347 printf( " Language=%04x:\n", e3->u1.s2.Id );
1348 data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
1349 if (e1->u1.s1.NameIsString)
1351 dump_data( RVA( data->OffsetToData, data->Size ), data->Size, " " );
1353 else switch(e1->u1.s2.Id)
1355 case 6:
1356 dump_string_data( RVA( data->OffsetToData, data->Size ), data->Size,
1357 e2->u1.s2.Id, " " );
1358 break;
1359 case 11:
1360 dump_msgtable_data( RVA( data->OffsetToData, data->Size ), data->Size,
1361 e2->u1.s2.Id, " " );
1362 break;
1363 default:
1364 dump_data( RVA( data->OffsetToData, data->Size ), data->Size, " " );
1365 break;
1370 printf( "\n\n" );
1373 static void dump_debug(void)
1375 const char* stabs = NULL;
1376 unsigned szstabs = 0;
1377 const char* stabstr = NULL;
1378 unsigned szstr = 0;
1379 unsigned i;
1380 const IMAGE_SECTION_HEADER* sectHead;
1382 sectHead = (const IMAGE_SECTION_HEADER*)
1383 ((const char*)PE_nt_headers + sizeof(DWORD) +
1384 sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader);
1386 for (i = 0; i < PE_nt_headers->FileHeader.NumberOfSections; i++, sectHead++)
1388 if (!strcmp((const char *)sectHead->Name, ".stab"))
1390 stabs = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize);
1391 szstabs = sectHead->Misc.VirtualSize;
1393 if (!strncmp((const char *)sectHead->Name, ".stabstr", 8))
1395 stabstr = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize);
1396 szstr = sectHead->Misc.VirtualSize;
1399 if (stabs && stabstr)
1400 dump_stabs(stabs, szstabs, stabstr, szstr);
1403 enum FileSig get_kind_exec(void)
1405 const WORD* pw;
1406 const DWORD* pdw;
1407 const IMAGE_DOS_HEADER* dh;
1409 pw = PRD(0, sizeof(WORD));
1410 if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}
1412 if (*pw != IMAGE_DOS_SIGNATURE) return SIG_UNKNOWN;
1414 if ((dh = PRD(0, sizeof(IMAGE_DOS_HEADER))))
1416 /* the signature is the first DWORD */
1417 pdw = PRD(dh->e_lfanew, sizeof(DWORD));
1418 if (pdw)
1420 if (*pdw == IMAGE_NT_SIGNATURE) return SIG_PE;
1421 if (*(const WORD *)pdw == IMAGE_OS2_SIGNATURE) return SIG_NE;
1422 if (*(const WORD *)pdw == IMAGE_VXD_SIGNATURE) return SIG_LE;
1423 return SIG_DOS;
1426 return 0;
1429 void pe_dump(void)
1431 int all = (globals.dumpsect != NULL) && strcmp(globals.dumpsect, "ALL") == 0;
1433 PE_nt_headers = get_nt_header();
1434 if (is_fake_dll()) printf( "*** This is a Wine fake DLL ***\n\n" );
1436 if (globals.do_dumpheader)
1438 dump_pe_header();
1439 /* FIXME: should check ptr */
1440 dump_sections(PRD(0, 1), (const char*)PE_nt_headers + sizeof(DWORD) +
1441 sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader,
1442 PE_nt_headers->FileHeader.NumberOfSections);
1444 else if (!globals.dumpsect)
1446 /* show at least something here */
1447 dump_pe_header();
1450 if (globals.dumpsect)
1452 if (all || !strcmp(globals.dumpsect, "import"))
1454 dump_dir_imported_functions();
1455 dump_dir_delay_imported_functions();
1457 if (all || !strcmp(globals.dumpsect, "export"))
1458 dump_dir_exported_functions();
1459 if (all || !strcmp(globals.dumpsect, "debug"))
1460 dump_dir_debug();
1461 if (all || !strcmp(globals.dumpsect, "resource"))
1462 dump_dir_resource();
1463 if (all || !strcmp(globals.dumpsect, "tls"))
1464 dump_dir_tls();
1465 if (all || !strcmp(globals.dumpsect, "clr"))
1466 dump_dir_clr_header();
1467 if (all || !strcmp(globals.dumpsect, "reloc"))
1468 dump_dir_reloc();
1469 if (all || !strcmp(globals.dumpsect, "except"))
1470 dump_dir_exceptions();
1472 if (globals.do_debug)
1473 dump_debug();
1476 typedef struct _dll_symbol {
1477 size_t ordinal;
1478 char *symbol;
1479 } dll_symbol;
1481 static dll_symbol *dll_symbols = NULL;
1482 static dll_symbol *dll_current_symbol = NULL;
1484 /* Compare symbols by ordinal for qsort */
1485 static int symbol_cmp(const void *left, const void *right)
1487 return ((const dll_symbol *)left)->ordinal > ((const dll_symbol *)right)->ordinal;
1490 /*******************************************************************
1491 * dll_close
1493 * Free resources used by DLL
1495 /* FIXME: Not used yet
1496 static void dll_close (void)
1498 dll_symbol* ds;
1500 if (!dll_symbols) {
1501 fatal("No symbols");
1503 for (ds = dll_symbols; ds->symbol; ds++)
1504 free(ds->symbol);
1505 free (dll_symbols);
1506 dll_symbols = NULL;
1510 static void do_grab_sym( void )
1512 const IMAGE_EXPORT_DIRECTORY*exportDir;
1513 unsigned i, j;
1514 const DWORD* pName;
1515 const DWORD* pFunc;
1516 const WORD* pOrdl;
1517 const char* ptr;
1518 DWORD* map;
1520 PE_nt_headers = get_nt_header();
1521 if (!(exportDir = get_dir(IMAGE_FILE_EXPORT_DIRECTORY))) return;
1523 pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
1524 if (!pName) {printf("Can't grab functions' name table\n"); return;}
1525 pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
1526 if (!pOrdl) {printf("Can't grab functions' ordinal table\n"); return;}
1528 /* dll_close(); */
1530 if (!(dll_symbols = malloc((exportDir->NumberOfFunctions + 1) * sizeof(dll_symbol))))
1531 fatal ("Out of memory");
1532 if (exportDir->AddressOfFunctions != exportDir->NumberOfNames || exportDir->Base > 1)
1533 globals.do_ordinals = 1;
1535 /* bit map of used funcs */
1536 map = calloc(((exportDir->NumberOfFunctions + 31) & ~31) / 32, sizeof(DWORD));
1537 if (!map) fatal("no memory");
1539 for (j = 0; j < exportDir->NumberOfNames; j++, pOrdl++)
1541 map[*pOrdl / 32] |= 1 << (*pOrdl % 32);
1542 ptr = RVA(*pName++, sizeof(DWORD));
1543 if (!ptr) ptr = "cant_get_function";
1544 dll_symbols[j].symbol = strdup(ptr);
1545 dll_symbols[j].ordinal = exportDir->Base + *pOrdl;
1546 assert(dll_symbols[j].symbol);
1548 pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
1549 if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
1551 for (i = 0; i < exportDir->NumberOfFunctions; i++)
1553 if (pFunc[i] && !(map[i / 32] & (1 << (i % 32))))
1555 char ordinal_text[256];
1556 /* Ordinal only entry */
1557 snprintf (ordinal_text, sizeof(ordinal_text), "%s_%u",
1558 globals.forward_dll ? globals.forward_dll : OUTPUT_UC_DLL_NAME,
1559 exportDir->Base + i);
1560 str_toupper(ordinal_text);
1561 dll_symbols[j].symbol = strdup(ordinal_text);
1562 assert(dll_symbols[j].symbol);
1563 dll_symbols[j].ordinal = exportDir->Base + i;
1564 j++;
1565 assert(j <= exportDir->NumberOfFunctions);
1568 free(map);
1570 if (NORMAL)
1571 printf("%u named symbols in DLL, %u total, %d unique (ordinal base = %d)\n",
1572 exportDir->NumberOfNames, exportDir->NumberOfFunctions, j, exportDir->Base);
1574 qsort( dll_symbols, j, sizeof(dll_symbol), symbol_cmp );
1576 dll_symbols[j].symbol = NULL;
1578 dll_current_symbol = dll_symbols;
1581 /*******************************************************************
1582 * dll_open
1584 * Open a DLL and read in exported symbols
1586 int dll_open (const char *dll_name)
1588 return dump_analysis(dll_name, do_grab_sym, SIG_PE);
1591 /*******************************************************************
1592 * dll_next_symbol
1594 * Get next exported symbol from dll
1596 int dll_next_symbol (parsed_symbol * sym)
1598 if (!dll_current_symbol->symbol)
1599 return 1;
1601 assert (dll_symbols);
1603 sym->symbol = strdup (dll_current_symbol->symbol);
1604 sym->ordinal = dll_current_symbol->ordinal;
1605 dll_current_symbol++;
1606 return 0;