mf: Implement file scheme handler.
[wine.git] / tools / winedump / pe.c
blobd33e8ef1e83e747aecef7c48680f545128989dc8
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_ARM64: return "ARM64";
65 case IMAGE_FILE_MACHINE_ARM: return "ARM";
66 case IMAGE_FILE_MACHINE_ARMNT: return "ARMNT";
67 case IMAGE_FILE_MACHINE_THUMB: return "ARM Thumb";
69 return "???";
72 static const void* RVA(unsigned long rva, unsigned long len)
74 IMAGE_SECTION_HEADER* sectHead;
75 int i;
77 if (rva == 0) return NULL;
79 sectHead = IMAGE_FIRST_SECTION(PE_nt_headers);
80 for (i = PE_nt_headers->FileHeader.NumberOfSections - 1; i >= 0; i--)
82 if (sectHead[i].VirtualAddress <= rva &&
83 rva + len <= (DWORD)sectHead[i].VirtualAddress + sectHead[i].SizeOfRawData)
85 /* return image import directory offset */
86 return PRD(sectHead[i].PointerToRawData + rva - sectHead[i].VirtualAddress, len);
90 return NULL;
93 static const IMAGE_NT_HEADERS32 *get_nt_header( void )
95 const IMAGE_DOS_HEADER *dos;
96 dos = PRD(0, sizeof(*dos));
97 if (!dos) return NULL;
98 return PRD(dos->e_lfanew, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER));
101 static void print_fake_dll( void )
103 static const char builtin_signature[] = "Wine builtin DLL";
104 static const char fakedll_signature[] = "Wine placeholder DLL";
105 const IMAGE_DOS_HEADER *dos;
107 dos = PRD(0, sizeof(*dos) + 32);
108 if (dos && dos->e_lfanew >= sizeof(*dos) + 32)
110 if (!memcmp( dos + 1, builtin_signature, sizeof(builtin_signature) ))
111 printf( "*** This is a Wine builtin DLL ***\n\n" );
112 else if (!memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) ))
113 printf( "*** This is a Wine fake DLL ***\n\n" );
117 static const void *get_dir_and_size(unsigned int idx, unsigned int *size)
119 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
121 const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
122 if (idx >= opt->NumberOfRvaAndSizes)
123 return NULL;
124 if(size)
125 *size = opt->DataDirectory[idx].Size;
126 return RVA(opt->DataDirectory[idx].VirtualAddress,
127 opt->DataDirectory[idx].Size);
129 else
131 const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
132 if (idx >= opt->NumberOfRvaAndSizes)
133 return NULL;
134 if(size)
135 *size = opt->DataDirectory[idx].Size;
136 return RVA(opt->DataDirectory[idx].VirtualAddress,
137 opt->DataDirectory[idx].Size);
141 static const void* get_dir(unsigned idx)
143 return get_dir_and_size(idx, 0);
146 static const char * const DirectoryNames[16] = {
147 "EXPORT", "IMPORT", "RESOURCE", "EXCEPTION",
148 "SECURITY", "BASERELOC", "DEBUG", "ARCHITECTURE",
149 "GLOBALPTR", "TLS", "LOAD_CONFIG", "Bound IAT",
150 "IAT", "Delay IAT", "CLR Header", ""
153 static const char *get_magic_type(WORD magic)
155 switch(magic) {
156 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
157 return "32bit";
158 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
159 return "64bit";
160 case IMAGE_ROM_OPTIONAL_HDR_MAGIC:
161 return "ROM";
163 return "???";
166 static inline void print_word(const char *title, WORD value)
168 printf(" %-34s 0x%-4X %u\n", title, value, value);
171 static inline void print_dword(const char *title, DWORD value)
173 printf(" %-34s 0x%-8x %u\n", title, value, value);
176 static inline void print_longlong(const char *title, ULONGLONG value)
178 printf(" %-34s 0x", title);
179 if(value >> 32)
180 printf("%lx%08lx\n", (unsigned long)(value >> 32), (unsigned long)value);
181 else
182 printf("%lx\n", (unsigned long)value);
185 static inline void print_ver(const char *title, BYTE major, BYTE minor)
187 printf(" %-34s %u.%02u\n", title, major, minor);
190 static inline void print_subsys(const char *title, WORD value)
192 const char *str;
193 switch (value)
195 default:
196 case IMAGE_SUBSYSTEM_UNKNOWN: str = "Unknown"; break;
197 case IMAGE_SUBSYSTEM_NATIVE: str = "Native"; break;
198 case IMAGE_SUBSYSTEM_WINDOWS_GUI: str = "Windows GUI"; break;
199 case IMAGE_SUBSYSTEM_WINDOWS_CUI: str = "Windows CUI"; break;
200 case IMAGE_SUBSYSTEM_OS2_CUI: str = "OS/2 CUI"; break;
201 case IMAGE_SUBSYSTEM_POSIX_CUI: str = "Posix CUI"; break;
202 case IMAGE_SUBSYSTEM_NATIVE_WINDOWS: str = "native Win9x driver"; break;
203 case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI: str = "Windows CE GUI"; break;
204 case IMAGE_SUBSYSTEM_EFI_APPLICATION: str = "EFI application"; break;
205 case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER: str = "EFI driver (boot)"; break;
206 case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER: str = "EFI driver (runtime)"; break;
207 case IMAGE_SUBSYSTEM_EFI_ROM: str = "EFI ROM"; break;
208 case IMAGE_SUBSYSTEM_XBOX: str = "Xbox application"; break;
209 case IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION: str = "Boot application"; break;
211 printf(" %-34s 0x%X (%s)\n", title, value, str);
214 static inline void print_dllflags(const char *title, WORD value)
216 printf(" %-34s 0x%X\n", title, value);
217 #define X(f,s) if (value & f) printf(" %s\n", s)
218 X(IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE, "DYNAMIC_BASE");
219 X(IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY, "FORCE_INTEGRITY");
220 X(IMAGE_DLLCHARACTERISTICS_NX_COMPAT, "NX_COMPAT");
221 X(IMAGE_DLLCHARACTERISTICS_NO_ISOLATION, "NO_ISOLATION");
222 X(IMAGE_DLLCHARACTERISTICS_NO_SEH, "NO_SEH");
223 X(IMAGE_DLLCHARACTERISTICS_NO_BIND, "NO_BIND");
224 X(IMAGE_DLLCHARACTERISTICS_WDM_DRIVER, "WDM_DRIVER");
225 X(IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE, "TERMINAL_SERVER_AWARE");
226 #undef X
229 static inline void print_datadirectory(DWORD n, const IMAGE_DATA_DIRECTORY *directory)
231 unsigned i;
232 printf("Data Directory\n");
234 for (i = 0; i < n && i < 16; i++)
236 printf(" %-12s rva: 0x%-8x size: 0x%-8x\n",
237 DirectoryNames[i], directory[i].VirtualAddress,
238 directory[i].Size);
242 static void dump_optional_header32(const IMAGE_OPTIONAL_HEADER32 *image_oh, UINT header_size)
244 IMAGE_OPTIONAL_HEADER32 oh;
245 const IMAGE_OPTIONAL_HEADER32 *optionalHeader;
247 /* in case optional header is missing or partial */
248 memset(&oh, 0, sizeof(oh));
249 memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
250 optionalHeader = &oh;
252 print_word("Magic", optionalHeader->Magic);
253 print_ver("linker version",
254 optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
255 print_dword("size of code", optionalHeader->SizeOfCode);
256 print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
257 print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
258 print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
259 print_dword("base of code", optionalHeader->BaseOfCode);
260 print_dword("base of data", optionalHeader->BaseOfData);
261 print_dword("image base", optionalHeader->ImageBase);
262 print_dword("section align", optionalHeader->SectionAlignment);
263 print_dword("file align", optionalHeader->FileAlignment);
264 print_ver("required OS version",
265 optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
266 print_ver("image version",
267 optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
268 print_ver("subsystem version",
269 optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
270 print_dword("Win32 Version", optionalHeader->Win32VersionValue);
271 print_dword("size of image", optionalHeader->SizeOfImage);
272 print_dword("size of headers", optionalHeader->SizeOfHeaders);
273 print_dword("checksum", optionalHeader->CheckSum);
274 print_subsys("Subsystem", optionalHeader->Subsystem);
275 print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
276 print_dword("stack reserve size", optionalHeader->SizeOfStackReserve);
277 print_dword("stack commit size", optionalHeader->SizeOfStackCommit);
278 print_dword("heap reserve size", optionalHeader->SizeOfHeapReserve);
279 print_dword("heap commit size", optionalHeader->SizeOfHeapCommit);
280 print_dword("loader flags", optionalHeader->LoaderFlags);
281 print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
282 printf("\n");
283 print_datadirectory(optionalHeader->NumberOfRvaAndSizes, optionalHeader->DataDirectory);
284 printf("\n");
287 static void dump_optional_header64(const IMAGE_OPTIONAL_HEADER64 *image_oh, UINT header_size)
289 IMAGE_OPTIONAL_HEADER64 oh;
290 const IMAGE_OPTIONAL_HEADER64 *optionalHeader;
292 /* in case optional header is missing or partial */
293 memset(&oh, 0, sizeof(oh));
294 memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
295 optionalHeader = &oh;
297 print_word("Magic", optionalHeader->Magic);
298 print_ver("linker version",
299 optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
300 print_dword("size of code", optionalHeader->SizeOfCode);
301 print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
302 print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
303 print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
304 print_dword("base of code", optionalHeader->BaseOfCode);
305 print_longlong("image base", optionalHeader->ImageBase);
306 print_dword("section align", optionalHeader->SectionAlignment);
307 print_dword("file align", optionalHeader->FileAlignment);
308 print_ver("required OS version",
309 optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
310 print_ver("image version",
311 optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
312 print_ver("subsystem version",
313 optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
314 print_dword("Win32 Version", optionalHeader->Win32VersionValue);
315 print_dword("size of image", optionalHeader->SizeOfImage);
316 print_dword("size of headers", optionalHeader->SizeOfHeaders);
317 print_dword("checksum", optionalHeader->CheckSum);
318 print_subsys("Subsystem", optionalHeader->Subsystem);
319 print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
320 print_longlong("stack reserve size", optionalHeader->SizeOfStackReserve);
321 print_longlong("stack commit size", optionalHeader->SizeOfStackCommit);
322 print_longlong("heap reserve size", optionalHeader->SizeOfHeapReserve);
323 print_longlong("heap commit size", optionalHeader->SizeOfHeapCommit);
324 print_dword("loader flags", optionalHeader->LoaderFlags);
325 print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
326 printf("\n");
327 print_datadirectory(optionalHeader->NumberOfRvaAndSizes, optionalHeader->DataDirectory);
328 printf("\n");
331 void dump_optional_header(const IMAGE_OPTIONAL_HEADER32 *optionalHeader, UINT header_size)
333 printf("Optional Header (%s)\n", get_magic_type(optionalHeader->Magic));
335 switch(optionalHeader->Magic) {
336 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
337 dump_optional_header32(optionalHeader, header_size);
338 break;
339 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
340 dump_optional_header64((const IMAGE_OPTIONAL_HEADER64 *)optionalHeader, header_size);
341 break;
342 default:
343 printf(" Unknown optional header magic: 0x%-4X\n", optionalHeader->Magic);
344 break;
348 void dump_file_header(const IMAGE_FILE_HEADER *fileHeader)
350 printf("File Header\n");
352 printf(" Machine: %04X (%s)\n",
353 fileHeader->Machine, get_machine_str(fileHeader->Machine));
354 printf(" Number of Sections: %d\n", fileHeader->NumberOfSections);
355 printf(" TimeDateStamp: %08X (%s) offset %lu\n",
356 fileHeader->TimeDateStamp, get_time_str(fileHeader->TimeDateStamp),
357 Offset(&(fileHeader->TimeDateStamp)));
358 printf(" PointerToSymbolTable: %08X\n", fileHeader->PointerToSymbolTable);
359 printf(" NumberOfSymbols: %08X\n", fileHeader->NumberOfSymbols);
360 printf(" SizeOfOptionalHeader: %04X\n", fileHeader->SizeOfOptionalHeader);
361 printf(" Characteristics: %04X\n", fileHeader->Characteristics);
362 #define X(f,s) if (fileHeader->Characteristics & f) printf(" %s\n", s)
363 X(IMAGE_FILE_RELOCS_STRIPPED, "RELOCS_STRIPPED");
364 X(IMAGE_FILE_EXECUTABLE_IMAGE, "EXECUTABLE_IMAGE");
365 X(IMAGE_FILE_LINE_NUMS_STRIPPED, "LINE_NUMS_STRIPPED");
366 X(IMAGE_FILE_LOCAL_SYMS_STRIPPED, "LOCAL_SYMS_STRIPPED");
367 X(IMAGE_FILE_AGGRESIVE_WS_TRIM, "AGGRESIVE_WS_TRIM");
368 X(IMAGE_FILE_LARGE_ADDRESS_AWARE, "LARGE_ADDRESS_AWARE");
369 X(IMAGE_FILE_16BIT_MACHINE, "16BIT_MACHINE");
370 X(IMAGE_FILE_BYTES_REVERSED_LO, "BYTES_REVERSED_LO");
371 X(IMAGE_FILE_32BIT_MACHINE, "32BIT_MACHINE");
372 X(IMAGE_FILE_DEBUG_STRIPPED, "DEBUG_STRIPPED");
373 X(IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "REMOVABLE_RUN_FROM_SWAP");
374 X(IMAGE_FILE_NET_RUN_FROM_SWAP, "NET_RUN_FROM_SWAP");
375 X(IMAGE_FILE_SYSTEM, "SYSTEM");
376 X(IMAGE_FILE_DLL, "DLL");
377 X(IMAGE_FILE_UP_SYSTEM_ONLY, "UP_SYSTEM_ONLY");
378 X(IMAGE_FILE_BYTES_REVERSED_HI, "BYTES_REVERSED_HI");
379 #undef X
380 printf("\n");
383 static void dump_pe_header(void)
385 dump_file_header(&PE_nt_headers->FileHeader);
386 dump_optional_header((const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader, PE_nt_headers->FileHeader.SizeOfOptionalHeader);
389 void dump_section(const IMAGE_SECTION_HEADER *sectHead, const char* strtable)
391 unsigned offset;
393 /* long section name ? */
394 if (strtable && sectHead->Name[0] == '/' &&
395 ((offset = atoi((const char*)sectHead->Name + 1)) < *(const DWORD*)strtable))
396 printf(" %.8s (%s)", sectHead->Name, strtable + offset);
397 else
398 printf(" %-8.8s", sectHead->Name);
399 printf(" VirtSize: 0x%08x VirtAddr: 0x%08x\n",
400 sectHead->Misc.VirtualSize, sectHead->VirtualAddress);
401 printf(" raw data offs: 0x%08x raw data size: 0x%08x\n",
402 sectHead->PointerToRawData, sectHead->SizeOfRawData);
403 printf(" relocation offs: 0x%08x relocations: 0x%08x\n",
404 sectHead->PointerToRelocations, sectHead->NumberOfRelocations);
405 printf(" line # offs: %-8u line #'s: %-8u\n",
406 sectHead->PointerToLinenumbers, sectHead->NumberOfLinenumbers);
407 printf(" characteristics: 0x%08x\n", sectHead->Characteristics);
408 printf(" ");
409 #define X(b,s) if (sectHead->Characteristics & b) printf(" " s)
410 /* #define IMAGE_SCN_TYPE_REG 0x00000000 - Reserved */
411 /* #define IMAGE_SCN_TYPE_DSECT 0x00000001 - Reserved */
412 /* #define IMAGE_SCN_TYPE_NOLOAD 0x00000002 - Reserved */
413 /* #define IMAGE_SCN_TYPE_GROUP 0x00000004 - Reserved */
414 /* #define IMAGE_SCN_TYPE_NO_PAD 0x00000008 - Reserved */
415 /* #define IMAGE_SCN_TYPE_COPY 0x00000010 - Reserved */
417 X(IMAGE_SCN_CNT_CODE, "CODE");
418 X(IMAGE_SCN_CNT_INITIALIZED_DATA, "INITIALIZED_DATA");
419 X(IMAGE_SCN_CNT_UNINITIALIZED_DATA, "UNINITIALIZED_DATA");
421 X(IMAGE_SCN_LNK_OTHER, "LNK_OTHER");
422 X(IMAGE_SCN_LNK_INFO, "LNK_INFO");
423 /* #define IMAGE_SCN_TYPE_OVER 0x00000400 - Reserved */
424 X(IMAGE_SCN_LNK_REMOVE, "LNK_REMOVE");
425 X(IMAGE_SCN_LNK_COMDAT, "LNK_COMDAT");
427 /* 0x00002000 - Reserved */
428 /* #define IMAGE_SCN_MEM_PROTECTED 0x00004000 - Obsolete */
429 X(IMAGE_SCN_MEM_FARDATA, "MEM_FARDATA");
431 /* #define IMAGE_SCN_MEM_SYSHEAP 0x00010000 - Obsolete */
432 X(IMAGE_SCN_MEM_PURGEABLE, "MEM_PURGEABLE");
433 X(IMAGE_SCN_MEM_16BIT, "MEM_16BIT");
434 X(IMAGE_SCN_MEM_LOCKED, "MEM_LOCKED");
435 X(IMAGE_SCN_MEM_PRELOAD, "MEM_PRELOAD");
437 switch (sectHead->Characteristics & IMAGE_SCN_ALIGN_MASK)
439 #define X2(b,s) case b: printf(" " s); break
440 X2(IMAGE_SCN_ALIGN_1BYTES, "ALIGN_1BYTES");
441 X2(IMAGE_SCN_ALIGN_2BYTES, "ALIGN_2BYTES");
442 X2(IMAGE_SCN_ALIGN_4BYTES, "ALIGN_4BYTES");
443 X2(IMAGE_SCN_ALIGN_8BYTES, "ALIGN_8BYTES");
444 X2(IMAGE_SCN_ALIGN_16BYTES, "ALIGN_16BYTES");
445 X2(IMAGE_SCN_ALIGN_32BYTES, "ALIGN_32BYTES");
446 X2(IMAGE_SCN_ALIGN_64BYTES, "ALIGN_64BYTES");
447 X2(IMAGE_SCN_ALIGN_128BYTES, "ALIGN_128BYTES");
448 X2(IMAGE_SCN_ALIGN_256BYTES, "ALIGN_256BYTES");
449 X2(IMAGE_SCN_ALIGN_512BYTES, "ALIGN_512BYTES");
450 X2(IMAGE_SCN_ALIGN_1024BYTES, "ALIGN_1024BYTES");
451 X2(IMAGE_SCN_ALIGN_2048BYTES, "ALIGN_2048BYTES");
452 X2(IMAGE_SCN_ALIGN_4096BYTES, "ALIGN_4096BYTES");
453 X2(IMAGE_SCN_ALIGN_8192BYTES, "ALIGN_8192BYTES");
454 #undef X2
457 X(IMAGE_SCN_LNK_NRELOC_OVFL, "LNK_NRELOC_OVFL");
459 X(IMAGE_SCN_MEM_DISCARDABLE, "MEM_DISCARDABLE");
460 X(IMAGE_SCN_MEM_NOT_CACHED, "MEM_NOT_CACHED");
461 X(IMAGE_SCN_MEM_NOT_PAGED, "MEM_NOT_PAGED");
462 X(IMAGE_SCN_MEM_SHARED, "MEM_SHARED");
463 X(IMAGE_SCN_MEM_EXECUTE, "MEM_EXECUTE");
464 X(IMAGE_SCN_MEM_READ, "MEM_READ");
465 X(IMAGE_SCN_MEM_WRITE, "MEM_WRITE");
466 #undef X
467 printf("\n\n");
470 static void dump_sections(const void *base, const void* addr, unsigned num_sect)
472 const IMAGE_SECTION_HEADER* sectHead = addr;
473 unsigned i;
474 const char* strtable;
476 if (PE_nt_headers->FileHeader.PointerToSymbolTable && PE_nt_headers->FileHeader.NumberOfSymbols)
478 strtable = (const char*)base +
479 PE_nt_headers->FileHeader.PointerToSymbolTable +
480 PE_nt_headers->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL);
482 else strtable = NULL;
484 printf("Section Table\n");
485 for (i = 0; i < num_sect; i++, sectHead++)
487 dump_section(sectHead, strtable);
489 if (globals.do_dump_rawdata)
491 dump_data((const unsigned char *)base + sectHead->PointerToRawData, sectHead->SizeOfRawData, " " );
492 printf("\n");
497 static void dump_dir_exported_functions(void)
499 unsigned int size = 0;
500 const IMAGE_EXPORT_DIRECTORY*exportDir = get_dir_and_size(IMAGE_FILE_EXPORT_DIRECTORY, &size);
501 unsigned int i;
502 const DWORD* pFunc;
503 const DWORD* pName;
504 const WORD* pOrdl;
505 DWORD* funcs;
507 if (!exportDir) return;
509 printf("Exports table:\n");
510 printf("\n");
511 printf(" Name: %s\n", (const char*)RVA(exportDir->Name, sizeof(DWORD)));
512 printf(" Characteristics: %08x\n", exportDir->Characteristics);
513 printf(" TimeDateStamp: %08X %s\n",
514 exportDir->TimeDateStamp, get_time_str(exportDir->TimeDateStamp));
515 printf(" Version: %u.%02u\n", exportDir->MajorVersion, exportDir->MinorVersion);
516 printf(" Ordinal base: %u\n", exportDir->Base);
517 printf(" # of functions: %u\n", exportDir->NumberOfFunctions);
518 printf(" # of Names: %u\n", exportDir->NumberOfNames);
519 printf("Addresses of functions: %08X\n", exportDir->AddressOfFunctions);
520 printf("Addresses of name ordinals: %08X\n", exportDir->AddressOfNameOrdinals);
521 printf("Addresses of names: %08X\n", exportDir->AddressOfNames);
522 printf("\n");
523 printf(" Entry Pt Ordn Name\n");
525 pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
526 if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
527 pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
528 pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
530 funcs = calloc( exportDir->NumberOfFunctions, sizeof(*funcs) );
531 if (!funcs) fatal("no memory");
533 for (i = 0; i < exportDir->NumberOfNames; i++) funcs[pOrdl[i]] = pName[i];
535 for (i = 0; i < exportDir->NumberOfFunctions; i++)
537 if (!pFunc[i]) continue;
538 printf(" %08X %5u ", pFunc[i], exportDir->Base + i);
539 if (funcs[i])
540 printf("%s", get_symbol_str((const char*)RVA(funcs[i], sizeof(DWORD))));
541 else
542 printf("<by ordinal>");
544 /* check for forwarded function */
545 if ((const char *)RVA(pFunc[i],1) >= (const char *)exportDir &&
546 (const char *)RVA(pFunc[i],1) < (const char *)exportDir + size)
547 printf(" (-> %s)", (const char *)RVA(pFunc[i],1));
548 printf("\n");
550 free(funcs);
551 printf("\n");
555 struct runtime_function_x86_64
557 DWORD BeginAddress;
558 DWORD EndAddress;
559 DWORD UnwindData;
562 struct runtime_function_armnt
564 DWORD BeginAddress;
565 union {
566 DWORD UnwindData;
567 struct {
568 DWORD Flag : 2;
569 DWORD FunctionLength : 11;
570 DWORD Ret : 2;
571 DWORD H : 1;
572 DWORD Reg : 3;
573 DWORD R : 1;
574 DWORD L : 1;
575 DWORD C : 1;
576 DWORD StackAdjust : 10;
577 } DUMMYSTRUCTNAME;
578 } DUMMYUNIONNAME;
581 union handler_data
583 struct runtime_function_x86_64 chain;
584 DWORD handler;
587 struct opcode
589 BYTE offset;
590 BYTE code : 4;
591 BYTE info : 4;
594 struct unwind_info_x86_64
596 BYTE version : 3;
597 BYTE flags : 5;
598 BYTE prolog;
599 BYTE count;
600 BYTE frame_reg : 4;
601 BYTE frame_offset : 4;
602 struct opcode opcodes[1]; /* count entries */
603 /* followed by union handler_data */
606 struct unwind_info_armnt
608 DWORD function_length : 18;
609 DWORD version : 2;
610 DWORD x : 1;
611 DWORD e : 1;
612 DWORD f : 1;
613 DWORD count : 5;
614 DWORD words : 4;
617 struct unwind_info_ext_armnt
619 WORD excount;
620 BYTE exwords;
621 BYTE reserved;
624 struct unwind_info_epilogue_armnt
626 DWORD offset : 18;
627 DWORD res : 2;
628 DWORD cond : 4;
629 DWORD index : 8;
632 #define UWOP_PUSH_NONVOL 0
633 #define UWOP_ALLOC_LARGE 1
634 #define UWOP_ALLOC_SMALL 2
635 #define UWOP_SET_FPREG 3
636 #define UWOP_SAVE_NONVOL 4
637 #define UWOP_SAVE_NONVOL_FAR 5
638 #define UWOP_SAVE_XMM128 8
639 #define UWOP_SAVE_XMM128_FAR 9
640 #define UWOP_PUSH_MACHFRAME 10
642 #define UNW_FLAG_EHANDLER 1
643 #define UNW_FLAG_UHANDLER 2
644 #define UNW_FLAG_CHAININFO 4
646 static void dump_x86_64_unwind_info( const struct runtime_function_x86_64 *function )
648 static const char * const reg_names[16] =
649 { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
650 "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" };
652 const union handler_data *handler_data;
653 const struct unwind_info_x86_64 *info;
654 unsigned int i, count;
656 printf( "\nFunction %08x-%08x:\n", function->BeginAddress, function->EndAddress );
657 if (function->UnwindData & 1)
659 const struct runtime_function_x86_64 *next = RVA( function->UnwindData & ~1, sizeof(*next) );
660 printf( " -> function %08x-%08x\n", next->BeginAddress, next->EndAddress );
661 return;
663 info = RVA( function->UnwindData, sizeof(*info) );
665 printf( " unwind info at %08x\n", function->UnwindData );
666 if (info->version != 1)
668 printf( " *** unknown version %u\n", info->version );
669 return;
671 printf( " flags %x", info->flags );
672 if (info->flags & UNW_FLAG_EHANDLER) printf( " EHANDLER" );
673 if (info->flags & UNW_FLAG_UHANDLER) printf( " UHANDLER" );
674 if (info->flags & UNW_FLAG_CHAININFO) printf( " CHAININFO" );
675 printf( "\n prolog 0x%x bytes\n", info->prolog );
677 if (info->frame_reg)
678 printf( " frame register %s offset 0x%x(%%rsp)\n",
679 reg_names[info->frame_reg], info->frame_offset * 16 );
681 for (i = 0; i < info->count; i++)
683 printf( " 0x%02x: ", info->opcodes[i].offset );
684 switch (info->opcodes[i].code)
686 case UWOP_PUSH_NONVOL:
687 printf( "push %%%s\n", reg_names[info->opcodes[i].info] );
688 break;
689 case UWOP_ALLOC_LARGE:
690 if (info->opcodes[i].info)
692 count = *(const DWORD *)&info->opcodes[i+1];
693 i += 2;
695 else
697 count = *(const USHORT *)&info->opcodes[i+1] * 8;
698 i++;
700 printf( "sub $0x%x,%%rsp\n", count );
701 break;
702 case UWOP_ALLOC_SMALL:
703 count = (info->opcodes[i].info + 1) * 8;
704 printf( "sub $0x%x,%%rsp\n", count );
705 break;
706 case UWOP_SET_FPREG:
707 printf( "lea 0x%x(%%rsp),%s\n",
708 info->frame_offset * 16, reg_names[info->frame_reg] );
709 break;
710 case UWOP_SAVE_NONVOL:
711 count = *(const USHORT *)&info->opcodes[i+1] * 8;
712 printf( "mov %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
713 i++;
714 break;
715 case UWOP_SAVE_NONVOL_FAR:
716 count = *(const DWORD *)&info->opcodes[i+1];
717 printf( "mov %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
718 i += 2;
719 break;
720 case UWOP_SAVE_XMM128:
721 count = *(const USHORT *)&info->opcodes[i+1] * 16;
722 printf( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
723 i++;
724 break;
725 case UWOP_SAVE_XMM128_FAR:
726 count = *(const DWORD *)&info->opcodes[i+1];
727 printf( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
728 i += 2;
729 break;
730 case UWOP_PUSH_MACHFRAME:
731 printf( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
732 break;
733 default:
734 printf( "*** unknown code %u\n", info->opcodes[i].code );
735 break;
739 handler_data = (const union handler_data *)&info->opcodes[(info->count + 1) & ~1];
740 if (info->flags & UNW_FLAG_CHAININFO)
742 printf( " -> function %08x-%08x\n",
743 handler_data->chain.BeginAddress, handler_data->chain.EndAddress );
744 return;
746 if (info->flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER))
747 printf( " handler %08x data at %08x\n", handler_data->handler,
748 (ULONG)(function->UnwindData + (const char *)(&handler_data->handler + 1) - (const char *)info ));
751 static void dump_armnt_unwind_info( const struct runtime_function_armnt *fnc )
753 const struct unwind_info_armnt *info;
754 const struct unwind_info_ext_armnt *infoex;
755 const struct unwind_info_epilogue_armnt *infoepi;
756 unsigned int rva;
757 WORD i, count = 0, words = 0;
759 if (fnc->u.s.Flag)
761 char intregs[32] = {0}, intregspop[32] = {0}, vfpregs[32] = {0};
762 WORD pf = 0, ef = 0, sc = 0;
764 printf( "\nFunction %08x-%08x:\n", fnc->BeginAddress & ~1,
765 (fnc->BeginAddress & ~1) + fnc->u.s.FunctionLength * 2 );
766 printf( " Flag %x\n", fnc->u.s.Flag );
767 printf( " FunctionLength %x\n", fnc->u.s.FunctionLength );
768 printf( " Ret %x\n", fnc->u.s.Ret );
769 printf( " H %x\n", fnc->u.s.H );
770 printf( " Reg %x\n", fnc->u.s.Reg );
771 printf( " R %x\n", fnc->u.s.R );
772 printf( " L %x\n", fnc->u.s.L );
773 printf( " C %x\n", fnc->u.s.C );
774 printf( " StackAdjust %x\n", fnc->u.s.StackAdjust );
776 if (fnc->u.s.StackAdjust >= 0x03f4)
778 pf = fnc->u.s.StackAdjust & 0x04;
779 ef = fnc->u.s.StackAdjust & 0x08;
782 if (!fnc->u.s.R && !pf)
784 if (fnc->u.s.Reg)
786 sprintf(intregs, "r4-r%u", fnc->u.s.Reg + 4);
787 sprintf(intregspop, "r4-r%u", fnc->u.s.Reg + 4);
789 else
791 strcpy(intregs, "r4");
792 strcpy(intregspop, "r4");
794 sc = fnc->u.s.Reg + 1;
795 if (fnc->u.s.C || fnc->u.s.L)
797 strcat(intregs, ", ");
798 if (fnc->u.s.C || (fnc->u.s.L && !fnc->u.s.H))
799 strcat(intregspop, ", ");
802 else if (fnc->u.s.R && pf)
804 if (((~fnc->u.s.StackAdjust) & 3) != 3)
806 sprintf(intregs, "r%u-r3", (~fnc->u.s.StackAdjust) & 3);
807 sprintf(intregspop, "r%u-r3", (~fnc->u.s.StackAdjust) & 3);
809 else
811 sprintf(intregs, "r3");
812 sprintf(intregspop, "r3");
814 sc = 4 - ((~fnc->u.s.StackAdjust) & 3);
815 if (fnc->u.s.C || fnc->u.s.L)
817 strcat(intregs, ", ");
818 if (fnc->u.s.C || (fnc->u.s.L && !fnc->u.s.H))
819 strcat(intregspop, ", ");
822 else if (!fnc->u.s.R && pf)
824 sprintf(intregs, "r%u-r%u", (~fnc->u.s.StackAdjust) & 3, fnc->u.s.Reg + 4);
825 sprintf(intregspop, "r%u-r%u", (~fnc->u.s.StackAdjust) & 3, fnc->u.s.Reg + 4);
826 sc = fnc->u.s.Reg + 5 - ((~fnc->u.s.StackAdjust) & 3);
827 if (fnc->u.s.C || fnc->u.s.L)
829 strcat(intregs, ", ");
830 if (fnc->u.s.C || (fnc->u.s.L && !fnc->u.s.H))
831 strcat(intregspop, ", ");
834 else if (fnc->u.s.R && !pf)
836 if (!fnc->u.s.C && !fnc->u.s.L)
838 strcpy(intregs, "none");
839 strcpy(intregspop, "none");
843 if (fnc->u.s.C && !fnc->u.s.L)
845 strcat(intregs, "r11");
846 strcat(intregspop, "r11");
848 else if (fnc->u.s.C && fnc->u.s.L)
850 strcat(intregs, "r11, lr");
851 if (fnc->u.s.H)
852 strcat(intregspop, "r11");
853 else
854 strcat(intregspop, "r11, pc");
856 else if (!fnc->u.s.C && fnc->u.s.L)
858 strcat(intregs, "lr");
859 if (!fnc->u.s.H)
860 strcat(intregspop, "pc");
863 if (fnc->u.s.R)
865 if (fnc->u.s.Reg)
866 sprintf(vfpregs, "d8-d%u", fnc->u.s.Reg + 8);
867 else
868 strcpy(vfpregs, "d8");
870 else
871 strcpy(vfpregs, "none");
873 if (fnc->u.s.H)
874 printf( " Unwind Code\tpush {r0-r3}\n" );
876 if (fnc->u.s.R || fnc->u.s.L || fnc->u.s.C || pf)
877 printf( " Unwind Code\tpush {%s}\n", intregs );
879 if (fnc->u.s.C && fnc->u.s.R && !fnc->u.s.L && !pf)
880 printf( " Unwind Code\tmov r11, sp\n" );
881 else if (fnc->u.s.C && (!fnc->u.s.R || fnc->u.s.L || pf))
883 if (fnc->u.s.StackAdjust >= 0x03f4 && !sc)
884 printf( " Unwind Code\tadd r11, sp, #<unknown>\n");
885 else if (fnc->u.s.StackAdjust >= 0x03f4)
886 printf( " Unwind Code\tadd r11, sp, #%d\n", sc * 4 );
887 else
888 printf( " Unwind Code\tadd r11, sp, #%d\n", fnc->u.s.StackAdjust * 4 );
891 if (fnc->u.s.R && fnc->u.s.Reg != 0x07)
892 printf( " Unwind Code\tvpush {%s}\n", vfpregs );
894 if (fnc->u.s.StackAdjust < 0x03f4 && !pf)
895 printf( " Unwind Code\tsub sp, sp, #%d\n", fnc->u.s.StackAdjust * 4 );
898 if (fnc->u.s.StackAdjust < 0x03f4 && !ef)
899 printf( " Unwind Code\tadd sp, sp, #%d\n", fnc->u.s.StackAdjust * 4 );
901 if (fnc->u.s.R && fnc->u.s.Reg != 0x07)
902 printf( " Unwind Code\tvpop {%s}\n", vfpregs );
904 if (fnc->u.s.C || !fnc->u.s.R || ef || (fnc->u.s.L && !fnc->u.s.H))
905 printf( " Unwind Code\tpop {%s}\n", intregspop );
907 if (fnc->u.s.H && !fnc->u.s.L)
908 printf( " Unwind Code\tadd sp, sp, #16\n" );
909 else if (fnc->u.s.H && fnc->u.s.L)
910 printf( " Unwind Code\tldr pc, [sp], #20\n" );
912 if (fnc->u.s.Ret == 1)
913 printf( " Unwind Code\tbx <reg>\n" );
914 else if (fnc->u.s.Ret == 2)
915 printf( " Unwind Code\tb <address>\n" );
917 return;
920 info = RVA( fnc->u.UnwindData, sizeof(*info) );
921 rva = fnc->u.UnwindData + sizeof(*info);
922 count = info->count;
923 words = info->words;
925 printf( "\nFunction %08x-%08x:\n", fnc->BeginAddress & ~1,
926 (fnc->BeginAddress & ~1) + info->function_length * 2 );
927 printf( " unwind info at %08x\n", fnc->u.UnwindData );
928 printf( " Flag %x\n", fnc->u.s.Flag );
929 printf( " FunctionLength %x\n", info->function_length );
930 printf( " Version %x\n", info->version );
931 printf( " X %x\n", info->x );
932 printf( " E %x\n", info->e );
933 printf( " F %x\n", info->f );
934 printf( " Count %x\n", count );
935 printf( " Words %x\n", words );
937 if (!info->count && !info->words)
939 infoex = RVA( rva, sizeof(*infoex) );
940 rva = rva + sizeof(*infoex);
941 count = infoex->excount;
942 words = infoex->exwords;
943 printf( " ExtCount %x\n", count );
944 printf( " ExtWords %x\n", words );
947 if (!info->e)
949 infoepi = RVA( rva, count * sizeof(*infoepi) );
950 rva = rva + count * sizeof(*infoepi);
952 for (i = 0; i < count; i++)
954 printf( " Epilogue Scope %x\n", i );
955 printf( " Offset %x\n", infoepi[i].offset );
956 printf( " Reserved %x\n", infoepi[i].res );
957 printf( " Condition %x\n", infoepi[i].cond );
958 printf( " Index %x\n", infoepi[i].index );
961 else
962 infoepi = NULL;
964 if (words)
966 const unsigned int *codes;
967 BYTE b, *bytes;
968 BOOL inepilogue = FALSE;
970 codes = RVA( rva, words * sizeof(*codes) );
971 rva = rva + words * sizeof(*codes);
972 bytes = (BYTE*)codes;
974 for (b = 0; b < words * sizeof(*codes); b++)
976 BYTE code = bytes[b];
978 if (info->e && b == count)
980 printf( "Epilogue:\n" );
981 inepilogue = TRUE;
983 else if (!info->e && infoepi)
985 for (i = 0; i < count; i++)
986 if (b == infoepi[i].index)
988 printf( "Epilogue from Scope %x at %08x:\n", i,
989 (fnc->BeginAddress & ~1) + infoepi[i].offset * 2 );
990 inepilogue = TRUE;
994 printf( " Unwind Code %x\t", code );
996 if (code == 0x00)
997 printf( "\n" );
998 else if (code <= 0x7f)
999 printf( "%s sp, sp, #%u\n", inepilogue ? "add" : "sub", code * 4 );
1000 else if (code <= 0xbf)
1002 WORD excode, f;
1003 BOOL first = TRUE;
1004 BYTE excodes = bytes[++b];
1006 excode = (code << 8) | excodes;
1007 printf( "%s {", inepilogue ? "pop" : "push" );
1009 for (f = 0; f <= 12; f++)
1011 if ((excode >> f) & 1)
1013 printf( "%sr%u", first ? "" : ", ", f );
1014 first = FALSE;
1018 if (excode & 0x2000)
1019 printf( "%s%s", first ? "" : ", ", inepilogue ? "pc" : "lr" );
1021 printf( "}\n" );
1023 else if (code <= 0xcf)
1024 if (inepilogue)
1025 printf( "mov sp, r%u\n", code & 0x0f );
1026 else
1027 printf( "mov r%u, sp\n", code & 0x0f );
1028 else if (code <= 0xd7)
1029 if (inepilogue)
1030 printf( "pop {r4-r%u%s}\n", (code & 0x03) + 4, (code & 0x04) ? ", pc" : "" );
1031 else
1032 printf( "push {r4-r%u%s}\n", (code & 0x03) + 4, (code & 0x04) ? ", lr" : "" );
1033 else if (code <= 0xdf)
1034 if (inepilogue)
1035 printf( "pop {r4-r%u%s}\n", (code & 0x03) + 8, (code & 0x04) ? ", pc" : "" );
1036 else
1037 printf( "push {r4-r%u%s}\n", (code & 0x03) + 8, (code & 0x04) ? ", lr" : "" );
1038 else if (code <= 0xe7)
1039 printf( "%s {d8-d%u}\n", inepilogue ? "vpop" : "vpush", (code & 0x07) + 8 );
1040 else if (code <= 0xeb)
1042 WORD excode;
1043 BYTE excodes = bytes[++b];
1045 excode = (code << 8) | excodes;
1046 printf( "%s sp, sp, #%u\n", inepilogue ? "addw" : "subw", (excode & 0x03ff) *4 );
1048 else if (code <= 0xed)
1050 WORD excode, f;
1051 BOOL first = TRUE;
1052 BYTE excodes = bytes[++b];
1054 excode = (code << 8) | excodes;
1055 printf( "%s {", inepilogue ? "pop" : "push" );
1057 for (f = 0; f < 8; f++)
1059 if ((excode >> f) & 1)
1061 printf( "%sr%u", first ? "" : ", ", f );
1062 first = FALSE;
1066 if (excode & 0x0100)
1067 printf( "%s%s", first ? "" : ", ", inepilogue ? "pc" : "lr" );
1069 printf( "}\n" );
1071 else if (code == 0xee)
1072 printf( "unknown 16\n" );
1073 else if (code == 0xef)
1075 WORD excode;
1076 BYTE excodes = bytes[++b];
1078 if (excodes <= 0x0f)
1080 excode = (code << 8) | excodes;
1081 if (inepilogue)
1082 printf( "ldr lr, [sp], #%u\n", (excode & 0x0f) * 4 );
1083 else
1084 printf( "unknown 32\n" );
1086 else
1087 printf( "unknown 32\n" );
1089 else if (code <= 0xf4)
1090 printf( "unknown\n" );
1091 else if (code <= 0xf6)
1093 WORD excode, offset = (code == 0xf6) ? 16 : 0;
1094 BYTE excodes = bytes[++b];
1096 excode = (code << 8) | excodes;
1097 printf( "%s {d%u-d%u}\n", inepilogue ? "vpop" : "vpush",
1098 ((excode & 0x00f0) >> 4) + offset, (excode & 0x0f) + offset );
1100 else if (code <= 0xf7)
1102 unsigned int excode;
1103 BYTE excodes[2];
1105 excodes[0] = bytes[++b];
1106 excodes[1] = bytes[++b];
1107 excode = (code << 16) | (excodes[0] << 8) | excodes[1];
1108 printf( "%s sp, sp, #%u\n", inepilogue ? "add" : "sub", (excode & 0xffff) *4 );
1110 else if (code <= 0xf8)
1112 unsigned int excode;
1113 BYTE excodes[3];
1115 excodes[0] = bytes[++b];
1116 excodes[1] = bytes[++b];
1117 excodes[2] = bytes[++b];
1118 excode = (code << 24) | (excodes[0] << 16) | (excodes[1] << 8) | excodes[2];
1119 printf( "%s sp, sp, #%u\n", inepilogue ? "add" : "sub", (excode & 0xffffff) * 4 );
1121 else if (code <= 0xf9)
1123 unsigned int excode;
1124 BYTE excodes[2];
1126 excodes[0] = bytes[++b];
1127 excodes[1] = bytes[++b];
1128 excode = (code << 16) | (excodes[0] << 8) | excodes[1];
1129 printf( "%s sp, sp, #%u\n", inepilogue ? "add" : "sub", (excode & 0xffff) *4 );
1131 else if (code <= 0xfa)
1133 unsigned int excode;
1134 BYTE excodes[3];
1136 excodes[0] = bytes[++b];
1137 excodes[1] = bytes[++b];
1138 excodes[2] = bytes[++b];
1139 excode = (code << 24) | (excodes[0] << 16) | (excodes[1] << 8) | excodes[2];
1140 printf( "%s sp, sp, #%u\n", inepilogue ? "add" : "sub", (excode & 0xffffff) * 4 );
1142 else if (code <= 0xfc)
1143 printf( "nop\n" );
1144 else if (code <= 0xfe)
1146 printf( "(end) nop\n" );
1147 inepilogue = TRUE;
1149 else
1151 printf( "end\n" );
1152 inepilogue = TRUE;
1157 if (info->x)
1159 const unsigned int *handler;
1161 handler = RVA( rva, sizeof(*handler) );
1162 rva = rva + sizeof(*handler);
1164 printf( " handler %08x data at %08x\n", *handler, rva);
1168 static void dump_dir_exceptions(void)
1170 unsigned int i, size = 0;
1171 const void *funcs = get_dir_and_size(IMAGE_FILE_EXCEPTION_DIRECTORY, &size);
1172 const IMAGE_FILE_HEADER *file_header = &PE_nt_headers->FileHeader;
1174 if (!funcs) return;
1176 if (file_header->Machine == IMAGE_FILE_MACHINE_AMD64)
1178 size /= sizeof(struct runtime_function_x86_64);
1179 printf( "Exception info (%u functions):\n", size );
1180 for (i = 0; i < size; i++) dump_x86_64_unwind_info( (struct runtime_function_x86_64*)funcs + i );
1182 else if (file_header->Machine == IMAGE_FILE_MACHINE_ARMNT)
1184 size /= sizeof(struct runtime_function_armnt);
1185 printf( "Exception info (%u functions):\n", size );
1186 for (i = 0; i < size; i++) dump_armnt_unwind_info( (struct runtime_function_armnt*)funcs + i );
1188 else printf( "Exception information not supported for %s binaries\n",
1189 get_machine_str(file_header->Machine));
1193 static void dump_image_thunk_data64(const IMAGE_THUNK_DATA64 *il, DWORD thunk_rva)
1195 /* FIXME: This does not properly handle large images */
1196 const IMAGE_IMPORT_BY_NAME* iibn;
1197 for (; il->u1.Ordinal; il++, thunk_rva += sizeof(LONGLONG))
1199 if (IMAGE_SNAP_BY_ORDINAL64(il->u1.Ordinal))
1200 printf(" %08x %4u <by ordinal>\n", thunk_rva, (DWORD)IMAGE_ORDINAL64(il->u1.Ordinal));
1201 else
1203 iibn = RVA((DWORD)il->u1.AddressOfData, sizeof(DWORD));
1204 if (!iibn)
1205 printf("Can't grab import by name info, skipping to next ordinal\n");
1206 else
1207 printf(" %08x %4u %s\n", thunk_rva, iibn->Hint, iibn->Name);
1212 static void dump_image_thunk_data32(const IMAGE_THUNK_DATA32 *il, int offset, DWORD thunk_rva)
1214 const IMAGE_IMPORT_BY_NAME* iibn;
1215 for (; il->u1.Ordinal; il++, thunk_rva += sizeof(DWORD))
1217 if (IMAGE_SNAP_BY_ORDINAL32(il->u1.Ordinal))
1218 printf(" %08x %4u <by ordinal>\n", thunk_rva, IMAGE_ORDINAL32(il->u1.Ordinal));
1219 else
1221 iibn = RVA((DWORD)il->u1.AddressOfData - offset, sizeof(DWORD));
1222 if (!iibn)
1223 printf("Can't grab import by name info, skipping to next ordinal\n");
1224 else
1225 printf(" %08x %4u %s\n", thunk_rva, iibn->Hint, iibn->Name);
1230 static void dump_dir_imported_functions(void)
1232 unsigned directorySize;
1233 const IMAGE_IMPORT_DESCRIPTOR* importDesc = get_dir_and_size(IMAGE_FILE_IMPORT_DIRECTORY, &directorySize);
1235 if (!importDesc) return;
1237 printf("Import Table size: %08x\n", directorySize);/* FIXME */
1239 for (;;)
1241 const IMAGE_THUNK_DATA32* il;
1243 if (!importDesc->Name || !importDesc->FirstThunk) break;
1245 printf(" offset %08lx %s\n", Offset(importDesc), (const char*)RVA(importDesc->Name, sizeof(DWORD)));
1246 printf(" Hint/Name Table: %08X\n", (DWORD)importDesc->u.OriginalFirstThunk);
1247 printf(" TimeDateStamp: %08X (%s)\n",
1248 importDesc->TimeDateStamp, get_time_str(importDesc->TimeDateStamp));
1249 printf(" ForwarderChain: %08X\n", importDesc->ForwarderChain);
1250 printf(" First thunk RVA: %08X\n", (DWORD)importDesc->FirstThunk);
1252 printf(" Thunk Ordn Name\n");
1254 il = (importDesc->u.OriginalFirstThunk != 0) ?
1255 RVA((DWORD)importDesc->u.OriginalFirstThunk, sizeof(DWORD)) :
1256 RVA((DWORD)importDesc->FirstThunk, sizeof(DWORD));
1258 if (!il)
1259 printf("Can't grab thunk data, going to next imported DLL\n");
1260 else
1262 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1263 dump_image_thunk_data64((const IMAGE_THUNK_DATA64*)il, importDesc->FirstThunk);
1264 else
1265 dump_image_thunk_data32(il, 0, importDesc->FirstThunk);
1266 printf("\n");
1268 importDesc++;
1270 printf("\n");
1273 static void dump_dir_loadconfig(void)
1275 const IMAGE_LOAD_CONFIG_DIRECTORY32 *loadcfg32 = get_dir(IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG);
1276 const IMAGE_LOAD_CONFIG_DIRECTORY64 *loadcfg64 = (void*)loadcfg32;
1278 if (!loadcfg32) return;
1280 printf( "Loadconfig\n" );
1281 print_dword( "Size", loadcfg32->Size );
1282 print_dword( "TimeDateStamp", loadcfg32->TimeDateStamp );
1283 print_word( "MajorVersion", loadcfg32->MajorVersion );
1284 print_word( "MinorVersion", loadcfg32->MinorVersion );
1285 print_dword( "GlobalFlagsClear", loadcfg32->GlobalFlagsClear );
1286 print_dword( "GlobalFlagsSet", loadcfg32->GlobalFlagsSet );
1287 print_dword( "CriticalSectionDefaultTimeout", loadcfg32->CriticalSectionDefaultTimeout );
1289 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1291 print_longlong( "DeCommitFreeBlockThreshold", loadcfg64->DeCommitFreeBlockThreshold );
1292 print_longlong( "DeCommitTotalFreeThreshold", loadcfg64->DeCommitTotalFreeThreshold );
1293 print_longlong( "MaximumAllocationSize", loadcfg64->MaximumAllocationSize );
1294 print_longlong( "VirtualMemoryThreshold", loadcfg64->VirtualMemoryThreshold );
1295 print_dword( "ProcessHeapFlags", loadcfg64->ProcessHeapFlags );
1296 print_longlong( "ProcessAffinityMask", loadcfg64->ProcessAffinityMask );
1297 print_word( "CSDVersion", loadcfg64->CSDVersion );
1298 print_word( "Reserved", loadcfg64->Reserved1 );
1299 print_longlong( "SecurityCookie", loadcfg64->SecurityCookie );
1300 print_longlong( "SEHandlerTable", loadcfg64->SEHandlerTable );
1301 print_longlong( "SEHandlerCount", loadcfg64->SEHandlerCount );
1303 else
1305 print_dword( "DeCommitFreeBlockThreshold", loadcfg32->DeCommitFreeBlockThreshold );
1306 print_dword( "DeCommitTotalFreeThreshold", loadcfg32->DeCommitTotalFreeThreshold );
1307 print_dword( "MaximumAllocationSize", loadcfg32->MaximumAllocationSize );
1308 print_dword( "VirtualMemoryThreshold", loadcfg32->VirtualMemoryThreshold );
1309 print_dword( "ProcessHeapFlags", loadcfg32->ProcessHeapFlags );
1310 print_dword( "ProcessAffinityMask", loadcfg32->ProcessAffinityMask );
1311 print_word( "CSDVersion", loadcfg32->CSDVersion );
1312 print_word( "Reserved", loadcfg32->Reserved1 );
1313 print_dword( "SecurityCookie", loadcfg32->SecurityCookie );
1314 print_dword( "SEHandlerTable", loadcfg32->SEHandlerTable );
1315 print_dword( "SEHandlerCount", loadcfg32->SEHandlerCount );
1319 static void dump_dir_delay_imported_functions(void)
1321 unsigned directorySize;
1322 const IMAGE_DELAYLOAD_DESCRIPTOR *importDesc = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT, &directorySize);
1324 if (!importDesc) return;
1326 printf("Delay Import Table size: %08x\n", directorySize); /* FIXME */
1328 for (;;)
1330 const IMAGE_THUNK_DATA32* il;
1331 int offset = (importDesc->Attributes.AllAttributes & 1) ? 0 : PE_nt_headers->OptionalHeader.ImageBase;
1333 if (!importDesc->DllNameRVA || !importDesc->ImportAddressTableRVA || !importDesc->ImportNameTableRVA) break;
1335 printf(" grAttrs %08x offset %08lx %s\n", importDesc->Attributes.AllAttributes, Offset(importDesc),
1336 (const char *)RVA(importDesc->DllNameRVA - offset, sizeof(DWORD)));
1337 printf(" Hint/Name Table: %08x\n", importDesc->ImportNameTableRVA);
1338 printf(" Address Table: %08x\n", importDesc->ImportAddressTableRVA);
1339 printf(" TimeDateStamp: %08X (%s)\n",
1340 importDesc->TimeDateStamp, get_time_str(importDesc->TimeDateStamp));
1342 printf(" Thunk Ordn Name\n");
1344 il = RVA(importDesc->ImportNameTableRVA - offset, sizeof(DWORD));
1346 if (!il)
1347 printf("Can't grab thunk data, going to next imported DLL\n");
1348 else
1350 if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1351 dump_image_thunk_data64((const IMAGE_THUNK_DATA64 *)il, importDesc->ImportAddressTableRVA);
1352 else
1353 dump_image_thunk_data32(il, offset, importDesc->ImportAddressTableRVA);
1354 printf("\n");
1356 importDesc++;
1358 printf("\n");
1361 static void dump_dir_debug_dir(const IMAGE_DEBUG_DIRECTORY* idd, int idx)
1363 const char* str;
1365 printf("Directory %02u\n", idx + 1);
1366 printf(" Characteristics: %08X\n", idd->Characteristics);
1367 printf(" TimeDateStamp: %08X %s\n",
1368 idd->TimeDateStamp, get_time_str(idd->TimeDateStamp));
1369 printf(" Version %u.%02u\n", idd->MajorVersion, idd->MinorVersion);
1370 switch (idd->Type)
1372 default:
1373 case IMAGE_DEBUG_TYPE_UNKNOWN: str = "UNKNOWN"; break;
1374 case IMAGE_DEBUG_TYPE_COFF: str = "COFF"; break;
1375 case IMAGE_DEBUG_TYPE_CODEVIEW: str = "CODEVIEW"; break;
1376 case IMAGE_DEBUG_TYPE_FPO: str = "FPO"; break;
1377 case IMAGE_DEBUG_TYPE_MISC: str = "MISC"; break;
1378 case IMAGE_DEBUG_TYPE_EXCEPTION: str = "EXCEPTION"; break;
1379 case IMAGE_DEBUG_TYPE_FIXUP: str = "FIXUP"; break;
1380 case IMAGE_DEBUG_TYPE_OMAP_TO_SRC: str = "OMAP_TO_SRC"; break;
1381 case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:str = "OMAP_FROM_SRC"; break;
1382 case IMAGE_DEBUG_TYPE_BORLAND: str = "BORLAND"; break;
1383 case IMAGE_DEBUG_TYPE_RESERVED10: str = "RESERVED10"; break;
1384 case IMAGE_DEBUG_TYPE_CLSID: str = "CLSID"; break;
1385 case IMAGE_DEBUG_TYPE_VC_FEATURE: str = "VC_FEATURE"; break;
1386 case IMAGE_DEBUG_TYPE_POGO: str = "POGO"; break;
1387 case IMAGE_DEBUG_TYPE_ILTCG: str = "ILTCG"; break;
1388 case IMAGE_DEBUG_TYPE_MPX: str = "MPX"; break;
1389 case IMAGE_DEBUG_TYPE_REPRO: str = "REPRO"; break;
1391 printf(" Type: %u (%s)\n", idd->Type, str);
1392 printf(" SizeOfData: %u\n", idd->SizeOfData);
1393 printf(" AddressOfRawData: %08X\n", idd->AddressOfRawData);
1394 printf(" PointerToRawData: %08X\n", idd->PointerToRawData);
1396 switch (idd->Type)
1398 case IMAGE_DEBUG_TYPE_UNKNOWN:
1399 break;
1400 case IMAGE_DEBUG_TYPE_COFF:
1401 dump_coff(idd->PointerToRawData, idd->SizeOfData,
1402 IMAGE_FIRST_SECTION(PE_nt_headers));
1403 break;
1404 case IMAGE_DEBUG_TYPE_CODEVIEW:
1405 dump_codeview(idd->PointerToRawData, idd->SizeOfData);
1406 break;
1407 case IMAGE_DEBUG_TYPE_FPO:
1408 dump_frame_pointer_omission(idd->PointerToRawData, idd->SizeOfData);
1409 break;
1410 case IMAGE_DEBUG_TYPE_MISC:
1412 const IMAGE_DEBUG_MISC* misc = PRD(idd->PointerToRawData, idd->SizeOfData);
1413 if (!misc) {printf("Can't get misc debug information\n"); break;}
1414 printf(" DataType: %u (%s)\n",
1415 misc->DataType,
1416 (misc->DataType == IMAGE_DEBUG_MISC_EXENAME) ? "Exe name" : "Unknown");
1417 printf(" Length: %u\n", misc->Length);
1418 printf(" Unicode: %s\n", misc->Unicode ? "Yes" : "No");
1419 printf(" Data: %s\n", misc->Data);
1421 break;
1422 default: break;
1424 printf("\n");
1427 static void dump_dir_debug(void)
1429 unsigned nb_dbg, i;
1430 const IMAGE_DEBUG_DIRECTORY*debugDir = get_dir_and_size(IMAGE_FILE_DEBUG_DIRECTORY, &nb_dbg);
1432 nb_dbg /= sizeof(*debugDir);
1433 if (!debugDir || !nb_dbg) return;
1435 printf("Debug Table (%u directories)\n", nb_dbg);
1437 for (i = 0; i < nb_dbg; i++)
1439 dump_dir_debug_dir(debugDir, i);
1440 debugDir++;
1442 printf("\n");
1445 static inline void print_clrflags(const char *title, DWORD value)
1447 printf(" %-34s 0x%X\n", title, value);
1448 #define X(f,s) if (value & f) printf(" %s\n", s)
1449 X(COMIMAGE_FLAGS_ILONLY, "ILONLY");
1450 X(COMIMAGE_FLAGS_32BITREQUIRED, "32BITREQUIRED");
1451 X(COMIMAGE_FLAGS_IL_LIBRARY, "IL_LIBRARY");
1452 X(COMIMAGE_FLAGS_STRONGNAMESIGNED, "STRONGNAMESIGNED");
1453 X(COMIMAGE_FLAGS_TRACKDEBUGDATA, "TRACKDEBUGDATA");
1454 #undef X
1457 static inline void print_clrdirectory(const char *title, const IMAGE_DATA_DIRECTORY *dir)
1459 printf(" %-23s rva: 0x%-8x size: 0x%-8x\n", title, dir->VirtualAddress, dir->Size);
1462 static void dump_dir_clr_header(void)
1464 unsigned int size = 0;
1465 const IMAGE_COR20_HEADER *dir = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &size);
1467 if (!dir) return;
1469 printf( "CLR Header\n" );
1470 print_dword( "Header Size", dir->cb );
1471 print_ver( "Required runtime version", dir->MajorRuntimeVersion, dir->MinorRuntimeVersion );
1472 print_clrflags( "Flags", dir->Flags );
1473 print_dword( "EntryPointToken", dir->u.EntryPointToken );
1474 printf("\n");
1475 printf( "CLR Data Directory\n" );
1476 print_clrdirectory( "MetaData", &dir->MetaData );
1477 print_clrdirectory( "Resources", &dir->Resources );
1478 print_clrdirectory( "StrongNameSignature", &dir->StrongNameSignature );
1479 print_clrdirectory( "CodeManagerTable", &dir->CodeManagerTable );
1480 print_clrdirectory( "VTableFixups", &dir->VTableFixups );
1481 print_clrdirectory( "ExportAddressTableJumps", &dir->ExportAddressTableJumps );
1482 print_clrdirectory( "ManagedNativeHeader", &dir->ManagedNativeHeader );
1483 printf("\n");
1486 static void dump_dir_reloc(void)
1488 unsigned int i, size = 0;
1489 const USHORT *relocs;
1490 const IMAGE_BASE_RELOCATION *rel = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_BASERELOC, &size);
1491 const IMAGE_BASE_RELOCATION *end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + size);
1492 static const char * const names[] =
1494 "BASED_ABSOLUTE",
1495 "BASED_HIGH",
1496 "BASED_LOW",
1497 "BASED_HIGHLOW",
1498 "BASED_HIGHADJ",
1499 "BASED_MIPS_JMPADDR",
1500 "BASED_SECTION",
1501 "BASED_REL",
1502 "unknown 8",
1503 "BASED_IA64_IMM64",
1504 "BASED_DIR64",
1505 "BASED_HIGH3ADJ",
1506 "unknown 12",
1507 "unknown 13",
1508 "unknown 14",
1509 "unknown 15"
1512 if (!rel) return;
1514 printf( "Relocations\n" );
1515 while (rel < end - 1 && rel->SizeOfBlock)
1517 printf( " Page %x\n", rel->VirtualAddress );
1518 relocs = (const USHORT *)(rel + 1);
1519 i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT);
1520 while (i--)
1522 USHORT offset = *relocs & 0xfff;
1523 int type = *relocs >> 12;
1524 printf( " off %04x type %s\n", offset, names[type] );
1525 relocs++;
1527 rel = (const IMAGE_BASE_RELOCATION *)relocs;
1529 printf("\n");
1532 static void dump_dir_tls(void)
1534 IMAGE_TLS_DIRECTORY64 dir;
1535 const DWORD *callbacks;
1536 const IMAGE_TLS_DIRECTORY32 *pdir = get_dir(IMAGE_FILE_THREAD_LOCAL_STORAGE);
1538 if (!pdir) return;
1540 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1541 memcpy(&dir, pdir, sizeof(dir));
1542 else
1544 dir.StartAddressOfRawData = pdir->StartAddressOfRawData;
1545 dir.EndAddressOfRawData = pdir->EndAddressOfRawData;
1546 dir.AddressOfIndex = pdir->AddressOfIndex;
1547 dir.AddressOfCallBacks = pdir->AddressOfCallBacks;
1548 dir.SizeOfZeroFill = pdir->SizeOfZeroFill;
1549 dir.Characteristics = pdir->Characteristics;
1552 /* FIXME: This does not properly handle large images */
1553 printf( "Thread Local Storage\n" );
1554 printf( " Raw data %08x-%08x (data size %x zero fill size %x)\n",
1555 (DWORD)dir.StartAddressOfRawData, (DWORD)dir.EndAddressOfRawData,
1556 (DWORD)(dir.EndAddressOfRawData - dir.StartAddressOfRawData),
1557 (DWORD)dir.SizeOfZeroFill );
1558 printf( " Index address %08x\n", (DWORD)dir.AddressOfIndex );
1559 printf( " Characteristics %08x\n", dir.Characteristics );
1560 printf( " Callbacks %08x -> {", (DWORD)dir.AddressOfCallBacks );
1561 if (dir.AddressOfCallBacks)
1563 DWORD addr = (DWORD)dir.AddressOfCallBacks - PE_nt_headers->OptionalHeader.ImageBase;
1564 while ((callbacks = RVA(addr, sizeof(DWORD))) && *callbacks)
1566 printf( " %08x", *callbacks );
1567 addr += sizeof(DWORD);
1570 printf(" }\n\n");
1573 enum FileSig get_kind_dbg(void)
1575 const WORD* pw;
1577 pw = PRD(0, sizeof(WORD));
1578 if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}
1580 if (*pw == 0x4944 /* "DI" */) return SIG_DBG;
1581 return SIG_UNKNOWN;
1584 void dbg_dump(void)
1586 const IMAGE_SEPARATE_DEBUG_HEADER* separateDebugHead;
1587 unsigned nb_dbg;
1588 unsigned i;
1589 const IMAGE_DEBUG_DIRECTORY* debugDir;
1591 separateDebugHead = PRD(0, sizeof(*separateDebugHead));
1592 if (!separateDebugHead) {printf("Can't grab the separate header, aborting\n"); return;}
1594 printf ("Signature: %.2s (0x%4X)\n",
1595 (const char*)&separateDebugHead->Signature, separateDebugHead->Signature);
1596 printf ("Flags: 0x%04X\n", separateDebugHead->Flags);
1597 printf ("Machine: 0x%04X (%s)\n",
1598 separateDebugHead->Machine, get_machine_str(separateDebugHead->Machine));
1599 printf ("Characteristics: 0x%04X\n", separateDebugHead->Characteristics);
1600 printf ("TimeDateStamp: 0x%08X (%s)\n",
1601 separateDebugHead->TimeDateStamp, get_time_str(separateDebugHead->TimeDateStamp));
1602 printf ("CheckSum: 0x%08X\n", separateDebugHead->CheckSum);
1603 printf ("ImageBase: 0x%08X\n", separateDebugHead->ImageBase);
1604 printf ("SizeOfImage: 0x%08X\n", separateDebugHead->SizeOfImage);
1605 printf ("NumberOfSections: 0x%08X\n", separateDebugHead->NumberOfSections);
1606 printf ("ExportedNamesSize: 0x%08X\n", separateDebugHead->ExportedNamesSize);
1607 printf ("DebugDirectorySize: 0x%08X\n", separateDebugHead->DebugDirectorySize);
1609 if (!PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER),
1610 separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER)))
1611 {printf("Can't get the sections, aborting\n"); return;}
1613 dump_sections(separateDebugHead, separateDebugHead + 1, separateDebugHead->NumberOfSections);
1615 nb_dbg = separateDebugHead->DebugDirectorySize / sizeof(IMAGE_DEBUG_DIRECTORY);
1616 debugDir = PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER) +
1617 separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
1618 separateDebugHead->ExportedNamesSize,
1619 nb_dbg * sizeof(IMAGE_DEBUG_DIRECTORY));
1620 if (!debugDir) {printf("Couldn't get the debug directory info, aborting\n");return;}
1622 printf("Debug Table (%u directories)\n", nb_dbg);
1624 for (i = 0; i < nb_dbg; i++)
1626 dump_dir_debug_dir(debugDir, i);
1627 debugDir++;
1631 static const char *get_resource_type( unsigned int id )
1633 static const char * const types[] =
1635 NULL,
1636 "CURSOR",
1637 "BITMAP",
1638 "ICON",
1639 "MENU",
1640 "DIALOG",
1641 "STRING",
1642 "FONTDIR",
1643 "FONT",
1644 "ACCELERATOR",
1645 "RCDATA",
1646 "MESSAGETABLE",
1647 "GROUP_CURSOR",
1648 NULL,
1649 "GROUP_ICON",
1650 NULL,
1651 "VERSION",
1652 "DLGINCLUDE",
1653 NULL,
1654 "PLUGPLAY",
1655 "VXD",
1656 "ANICURSOR",
1657 "ANIICON",
1658 "HTML",
1659 "RT_MANIFEST"
1662 if ((size_t)id < ARRAY_SIZE(types)) return types[id];
1663 return NULL;
1666 /* dump an ASCII string with proper escaping */
1667 static int dump_strA( const unsigned char *str, size_t len )
1669 static const char escapes[32] = ".......abtnvfr.............e....";
1670 char buffer[256];
1671 char *pos = buffer;
1672 int count = 0;
1674 for (; len; str++, len--)
1676 if (pos > buffer + sizeof(buffer) - 8)
1678 fwrite( buffer, pos - buffer, 1, stdout );
1679 count += pos - buffer;
1680 pos = buffer;
1682 if (*str > 127) /* hex escape */
1684 pos += sprintf( pos, "\\x%02x", *str );
1685 continue;
1687 if (*str < 32) /* octal or C escape */
1689 if (!*str && len == 1) continue; /* do not output terminating NULL */
1690 if (escapes[*str] != '.')
1691 pos += sprintf( pos, "\\%c", escapes[*str] );
1692 else if (len > 1 && str[1] >= '0' && str[1] <= '7')
1693 pos += sprintf( pos, "\\%03o", *str );
1694 else
1695 pos += sprintf( pos, "\\%o", *str );
1696 continue;
1698 if (*str == '\\') *pos++ = '\\';
1699 *pos++ = *str;
1701 fwrite( buffer, pos - buffer, 1, stdout );
1702 count += pos - buffer;
1703 return count;
1706 /* dump a Unicode string with proper escaping */
1707 static int dump_strW( const WCHAR *str, size_t len )
1709 static const char escapes[32] = ".......abtnvfr.............e....";
1710 char buffer[256];
1711 char *pos = buffer;
1712 int count = 0;
1714 for (; len; str++, len--)
1716 if (pos > buffer + sizeof(buffer) - 8)
1718 fwrite( buffer, pos - buffer, 1, stdout );
1719 count += pos - buffer;
1720 pos = buffer;
1722 if (*str > 127) /* hex escape */
1724 if (len > 1 && str[1] < 128 && isxdigit((char)str[1]))
1725 pos += sprintf( pos, "\\x%04x", *str );
1726 else
1727 pos += sprintf( pos, "\\x%x", *str );
1728 continue;
1730 if (*str < 32) /* octal or C escape */
1732 if (!*str && len == 1) continue; /* do not output terminating NULL */
1733 if (escapes[*str] != '.')
1734 pos += sprintf( pos, "\\%c", escapes[*str] );
1735 else if (len > 1 && str[1] >= '0' && str[1] <= '7')
1736 pos += sprintf( pos, "\\%03o", *str );
1737 else
1738 pos += sprintf( pos, "\\%o", *str );
1739 continue;
1741 if (*str == '\\') *pos++ = '\\';
1742 *pos++ = *str;
1744 fwrite( buffer, pos - buffer, 1, stdout );
1745 count += pos - buffer;
1746 return count;
1749 /* dump data for a STRING resource */
1750 static void dump_string_data( const WCHAR *ptr, unsigned int size, unsigned int id, const char *prefix )
1752 int i;
1754 for (i = 0; i < 16 && size; i++)
1756 unsigned len = *ptr++;
1758 if (len >= size)
1760 len = size;
1761 size = 0;
1763 else size -= len + 1;
1765 if (len)
1767 printf( "%s%04x \"", prefix, (id - 1) * 16 + i );
1768 dump_strW( ptr, len );
1769 printf( "\"\n" );
1770 ptr += len;
1775 /* dump data for a MESSAGETABLE resource */
1776 static void dump_msgtable_data( const void *ptr, unsigned int size, unsigned int id, const char *prefix )
1778 const MESSAGE_RESOURCE_DATA *data = ptr;
1779 const MESSAGE_RESOURCE_BLOCK *block = data->Blocks;
1780 unsigned i, j;
1782 for (i = 0; i < data->NumberOfBlocks; i++, block++)
1784 const MESSAGE_RESOURCE_ENTRY *entry;
1786 entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)data + block->OffsetToEntries);
1787 for (j = block->LowId; j <= block->HighId; j++)
1789 if (entry->Flags & MESSAGE_RESOURCE_UNICODE)
1791 const WCHAR *str = (const WCHAR *)entry->Text;
1792 printf( "%s%08x L\"", prefix, j );
1793 dump_strW( str, strlenW(str) );
1794 printf( "\"\n" );
1796 else
1798 const char *str = (const char *) entry->Text;
1799 printf( "%s%08x \"", prefix, j );
1800 dump_strA( entry->Text, strlen(str) );
1801 printf( "\"\n" );
1803 entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)entry + entry->Length);
1808 static void dump_dir_resource(void)
1810 const IMAGE_RESOURCE_DIRECTORY *root = get_dir(IMAGE_FILE_RESOURCE_DIRECTORY);
1811 const IMAGE_RESOURCE_DIRECTORY *namedir;
1812 const IMAGE_RESOURCE_DIRECTORY *langdir;
1813 const IMAGE_RESOURCE_DIRECTORY_ENTRY *e1, *e2, *e3;
1814 const IMAGE_RESOURCE_DIR_STRING_U *string;
1815 const IMAGE_RESOURCE_DATA_ENTRY *data;
1816 int i, j, k;
1818 if (!root) return;
1820 printf( "Resources:" );
1822 for (i = 0; i< root->NumberOfNamedEntries + root->NumberOfIdEntries; i++)
1824 e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
1825 namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s2.OffsetToDirectory);
1826 for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
1828 e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
1829 langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s2.OffsetToDirectory);
1830 for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
1832 e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
1834 printf( "\n " );
1835 if (e1->u.s.NameIsString)
1837 string = (const IMAGE_RESOURCE_DIR_STRING_U*)((const char *)root + e1->u.s.NameOffset);
1838 dump_unicode_str( string->NameString, string->Length );
1840 else
1842 const char *type = get_resource_type( e1->u.Id );
1843 if (type) printf( "%s", type );
1844 else printf( "%04x", e1->u.Id );
1847 printf( " Name=" );
1848 if (e2->u.s.NameIsString)
1850 string = (const IMAGE_RESOURCE_DIR_STRING_U*) ((const char *)root + e2->u.s.NameOffset);
1851 dump_unicode_str( string->NameString, string->Length );
1853 else
1854 printf( "%04x", e2->u.Id );
1856 printf( " Language=%04x:\n", e3->u.Id );
1857 data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
1858 if (e1->u.s.NameIsString)
1860 dump_data( RVA( data->OffsetToData, data->Size ), data->Size, " " );
1862 else switch(e1->u.Id)
1864 case 6:
1865 dump_string_data( RVA( data->OffsetToData, data->Size ), data->Size, e2->u.Id, " " );
1866 break;
1867 case 11:
1868 dump_msgtable_data( RVA( data->OffsetToData, data->Size ), data->Size,
1869 e2->u.Id, " " );
1870 break;
1871 default:
1872 dump_data( RVA( data->OffsetToData, data->Size ), data->Size, " " );
1873 break;
1878 printf( "\n\n" );
1881 static void dump_debug(void)
1883 const char* stabs = NULL;
1884 unsigned szstabs = 0;
1885 const char* stabstr = NULL;
1886 unsigned szstr = 0;
1887 unsigned i;
1888 const IMAGE_SECTION_HEADER* sectHead;
1890 sectHead = IMAGE_FIRST_SECTION(PE_nt_headers);
1892 for (i = 0; i < PE_nt_headers->FileHeader.NumberOfSections; i++, sectHead++)
1894 if (!strcmp((const char *)sectHead->Name, ".stab"))
1896 stabs = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize);
1897 szstabs = sectHead->Misc.VirtualSize;
1899 if (!strncmp((const char *)sectHead->Name, ".stabstr", 8))
1901 stabstr = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize);
1902 szstr = sectHead->Misc.VirtualSize;
1905 if (stabs && stabstr)
1906 dump_stabs(stabs, szstabs, stabstr, szstr);
1909 static void dump_symbol_table(void)
1911 const IMAGE_SYMBOL* sym;
1912 int numsym;
1914 numsym = PE_nt_headers->FileHeader.NumberOfSymbols;
1915 if (!PE_nt_headers->FileHeader.PointerToSymbolTable || !numsym)
1916 return;
1917 sym = PRD(PE_nt_headers->FileHeader.PointerToSymbolTable,
1918 sizeof(*sym) * numsym);
1919 if (!sym) return;
1921 dump_coff_symbol_table(sym, numsym, IMAGE_FIRST_SECTION(PE_nt_headers));
1924 enum FileSig get_kind_exec(void)
1926 const WORD* pw;
1927 const DWORD* pdw;
1928 const IMAGE_DOS_HEADER* dh;
1930 pw = PRD(0, sizeof(WORD));
1931 if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}
1933 if (*pw != IMAGE_DOS_SIGNATURE) return SIG_UNKNOWN;
1935 if ((dh = PRD(0, sizeof(IMAGE_DOS_HEADER))))
1937 /* the signature is the first DWORD */
1938 pdw = PRD(dh->e_lfanew, sizeof(DWORD));
1939 if (pdw)
1941 if (*pdw == IMAGE_NT_SIGNATURE) return SIG_PE;
1942 if (*(const WORD *)pdw == IMAGE_OS2_SIGNATURE) return SIG_NE;
1943 if (*(const WORD *)pdw == IMAGE_VXD_SIGNATURE) return SIG_LE;
1945 return SIG_DOS;
1947 return SIG_UNKNOWN;
1950 void pe_dump(void)
1952 int all = (globals.dumpsect != NULL) && strcmp(globals.dumpsect, "ALL") == 0;
1954 PE_nt_headers = get_nt_header();
1955 print_fake_dll();
1957 if (globals.do_dumpheader)
1959 dump_pe_header();
1960 /* FIXME: should check ptr */
1961 dump_sections(PRD(0, 1), IMAGE_FIRST_SECTION(PE_nt_headers),
1962 PE_nt_headers->FileHeader.NumberOfSections);
1964 else if (!globals.dumpsect)
1966 /* show at least something here */
1967 dump_pe_header();
1970 if (globals.dumpsect)
1972 if (all || !strcmp(globals.dumpsect, "import"))
1974 dump_dir_imported_functions();
1975 dump_dir_delay_imported_functions();
1977 if (all || !strcmp(globals.dumpsect, "export"))
1978 dump_dir_exported_functions();
1979 if (all || !strcmp(globals.dumpsect, "debug"))
1980 dump_dir_debug();
1981 if (all || !strcmp(globals.dumpsect, "resource"))
1982 dump_dir_resource();
1983 if (all || !strcmp(globals.dumpsect, "tls"))
1984 dump_dir_tls();
1985 if (all || !strcmp(globals.dumpsect, "loadcfg"))
1986 dump_dir_loadconfig();
1987 if (all || !strcmp(globals.dumpsect, "clr"))
1988 dump_dir_clr_header();
1989 if (all || !strcmp(globals.dumpsect, "reloc"))
1990 dump_dir_reloc();
1991 if (all || !strcmp(globals.dumpsect, "except"))
1992 dump_dir_exceptions();
1994 if (globals.do_symbol_table)
1995 dump_symbol_table();
1996 if (globals.do_debug)
1997 dump_debug();
2000 typedef struct _dll_symbol {
2001 size_t ordinal;
2002 char *symbol;
2003 } dll_symbol;
2005 static dll_symbol *dll_symbols = NULL;
2006 static dll_symbol *dll_current_symbol = NULL;
2008 /* Compare symbols by ordinal for qsort */
2009 static int symbol_cmp(const void *left, const void *right)
2011 return ((const dll_symbol *)left)->ordinal > ((const dll_symbol *)right)->ordinal;
2014 /*******************************************************************
2015 * dll_close
2017 * Free resources used by DLL
2019 /* FIXME: Not used yet
2020 static void dll_close (void)
2022 dll_symbol* ds;
2024 if (!dll_symbols) {
2025 fatal("No symbols");
2027 for (ds = dll_symbols; ds->symbol; ds++)
2028 free(ds->symbol);
2029 free (dll_symbols);
2030 dll_symbols = NULL;
2034 static void do_grab_sym( void )
2036 const IMAGE_EXPORT_DIRECTORY*exportDir;
2037 unsigned i, j;
2038 const DWORD* pName;
2039 const DWORD* pFunc;
2040 const WORD* pOrdl;
2041 const char* ptr;
2042 DWORD* map;
2044 PE_nt_headers = get_nt_header();
2045 if (!(exportDir = get_dir(IMAGE_FILE_EXPORT_DIRECTORY))) return;
2047 pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
2048 if (!pName) {printf("Can't grab functions' name table\n"); return;}
2049 pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
2050 if (!pOrdl) {printf("Can't grab functions' ordinal table\n"); return;}
2051 pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
2052 if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
2054 /* dll_close(); */
2056 if (!(dll_symbols = malloc((exportDir->NumberOfFunctions + 1) * sizeof(dll_symbol))))
2057 fatal ("Out of memory");
2059 /* bit map of used funcs */
2060 map = calloc(((exportDir->NumberOfFunctions + 31) & ~31) / 32, sizeof(DWORD));
2061 if (!map) fatal("no memory");
2063 for (j = 0; j < exportDir->NumberOfNames; j++, pOrdl++)
2065 map[*pOrdl / 32] |= 1 << (*pOrdl % 32);
2066 ptr = RVA(*pName++, sizeof(DWORD));
2067 if (!ptr) ptr = "cant_get_function";
2068 dll_symbols[j].symbol = strdup(ptr);
2069 dll_symbols[j].ordinal = exportDir->Base + *pOrdl;
2070 assert(dll_symbols[j].symbol);
2073 for (i = 0; i < exportDir->NumberOfFunctions; i++)
2075 if (pFunc[i] && !(map[i / 32] & (1 << (i % 32))))
2077 char ordinal_text[256];
2078 /* Ordinal only entry */
2079 snprintf (ordinal_text, sizeof(ordinal_text), "%s_%u",
2080 globals.forward_dll ? globals.forward_dll : OUTPUT_UC_DLL_NAME,
2081 exportDir->Base + i);
2082 str_toupper(ordinal_text);
2083 dll_symbols[j].symbol = strdup(ordinal_text);
2084 assert(dll_symbols[j].symbol);
2085 dll_symbols[j].ordinal = exportDir->Base + i;
2086 j++;
2087 assert(j <= exportDir->NumberOfFunctions);
2090 free(map);
2092 if (NORMAL)
2093 printf("%u named symbols in DLL, %u total, %d unique (ordinal base = %d)\n",
2094 exportDir->NumberOfNames, exportDir->NumberOfFunctions, j, exportDir->Base);
2096 qsort( dll_symbols, j, sizeof(dll_symbol), symbol_cmp );
2098 dll_symbols[j].symbol = NULL;
2100 dll_current_symbol = dll_symbols;
2103 /*******************************************************************
2104 * dll_open
2106 * Open a DLL and read in exported symbols
2108 BOOL dll_open (const char *dll_name)
2110 return dump_analysis(dll_name, do_grab_sym, SIG_PE);
2113 /*******************************************************************
2114 * dll_next_symbol
2116 * Get next exported symbol from dll
2118 BOOL dll_next_symbol (parsed_symbol * sym)
2120 if (!dll_current_symbol || !dll_current_symbol->symbol)
2121 return FALSE;
2122 assert (dll_symbols);
2123 sym->symbol = strdup (dll_current_symbol->symbol);
2124 sym->ordinal = dll_current_symbol->ordinal;
2125 dll_current_symbol++;
2126 return TRUE;