winspool: Implement SetDefaultPrinterA/W.
[wine.git] / tools / winedump / pe.c
bloba2b1fe5d34d95020150179833088bf7fcf1a3f4e
1 /*
2 * PE dumping utility
4 * Copyright 2001 Eric Pouech
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <time.h>
31 #ifdef HAVE_SYS_TYPES_H
32 # include <sys/types.h>
33 #endif
34 #ifdef HAVE_SYS_STAT_H
35 # include <sys/stat.h>
36 #endif
37 #ifdef HAVE_SYS_MMAN_H
38 #include <sys/mman.h>
39 #endif
40 #include <fcntl.h>
42 #define NONAMELESSUNION
43 #define NONAMELESSSTRUCT
44 #include "windef.h"
45 #include "winbase.h"
46 #include "winedump.h"
48 static const IMAGE_NT_HEADERS32* PE_nt_headers;
50 const char *get_machine_str(int mach)
52 switch (mach)
54 case IMAGE_FILE_MACHINE_UNKNOWN: return "Unknown";
55 case IMAGE_FILE_MACHINE_I860: return "i860";
56 case IMAGE_FILE_MACHINE_I386: return "i386";
57 case IMAGE_FILE_MACHINE_R3000: return "R3000";
58 case IMAGE_FILE_MACHINE_R4000: return "R4000";
59 case IMAGE_FILE_MACHINE_R10000: return "R10000";
60 case IMAGE_FILE_MACHINE_ALPHA: return "Alpha";
61 case IMAGE_FILE_MACHINE_POWERPC: return "PowerPC";
62 case IMAGE_FILE_MACHINE_AMD64: return "AMD64";
63 case IMAGE_FILE_MACHINE_IA64: return "IA64";
64 case IMAGE_FILE_MACHINE_ARM: return "ARM";
65 case IMAGE_FILE_MACHINE_SPARC: return "SPARC";
67 return "???";
70 static const void* RVA(unsigned long rva, unsigned long len)
72 IMAGE_SECTION_HEADER* sectHead;
73 int i;
75 if (rva == 0) return NULL;
77 sectHead = IMAGE_FIRST_SECTION(PE_nt_headers);
78 for (i = PE_nt_headers->FileHeader.NumberOfSections - 1; i >= 0; i--)
80 if (sectHead[i].VirtualAddress <= rva &&
81 rva + len <= (DWORD)sectHead[i].VirtualAddress + sectHead[i].SizeOfRawData)
83 /* return image import directory offset */
84 return PRD(sectHead[i].PointerToRawData + rva - sectHead[i].VirtualAddress, len);
88 return NULL;
91 static const IMAGE_NT_HEADERS32 *get_nt_header( void )
93 const IMAGE_DOS_HEADER *dos;
94 dos = PRD(0, sizeof(*dos));
95 if (!dos) return NULL;
96 return PRD(dos->e_lfanew, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER));
99 static int is_fake_dll( void )
101 static const char fakedll_signature[] = "Wine placeholder DLL";
102 const IMAGE_DOS_HEADER *dos;
104 dos = PRD(0, sizeof(*dos) + sizeof(fakedll_signature));
106 if (dos && dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
107 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
108 return FALSE;
111 static const void *get_dir_and_size(unsigned int idx, unsigned int *size)
113 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
115 const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
116 if (idx >= opt->NumberOfRvaAndSizes)
117 return NULL;
118 if(size)
119 *size = opt->DataDirectory[idx].Size;
120 return RVA(opt->DataDirectory[idx].VirtualAddress,
121 opt->DataDirectory[idx].Size);
123 else
125 const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
126 if (idx >= opt->NumberOfRvaAndSizes)
127 return NULL;
128 if(size)
129 *size = opt->DataDirectory[idx].Size;
130 return RVA(opt->DataDirectory[idx].VirtualAddress,
131 opt->DataDirectory[idx].Size);
135 static const void* get_dir(unsigned idx)
137 return get_dir_and_size(idx, 0);
140 static const char * const DirectoryNames[16] = {
141 "EXPORT", "IMPORT", "RESOURCE", "EXCEPTION",
142 "SECURITY", "BASERELOC", "DEBUG", "ARCHITECTURE",
143 "GLOBALPTR", "TLS", "LOAD_CONFIG", "Bound IAT",
144 "IAT", "Delay IAT", "CLR Header", ""
147 static const char *get_magic_type(WORD magic)
149 switch(magic) {
150 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
151 return "32bit";
152 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
153 return "64bit";
154 case IMAGE_ROM_OPTIONAL_HDR_MAGIC:
155 return "ROM";
157 return "???";
160 static inline void print_word(const char *title, WORD value)
162 printf(" %-34s 0x%-4X %u\n", title, value, value);
165 static inline void print_dword(const char *title, DWORD value)
167 printf(" %-34s 0x%-8x %u\n", title, value, value);
170 static inline void print_longlong(const char *title, ULONGLONG value)
172 printf(" %-34s 0x", title);
173 if(value >> 32)
174 printf("%lx%08lx\n", (unsigned long)(value >> 32), (unsigned long)value);
175 else
176 printf("%lx\n", (unsigned long)value);
179 static inline void print_ver(const char *title, BYTE major, BYTE minor)
181 printf(" %-34s %u.%02u\n", title, major, minor);
184 static inline void print_subsys(const char *title, WORD value)
186 const char *str;
187 switch (value)
189 default:
190 case IMAGE_SUBSYSTEM_UNKNOWN: str = "Unknown"; break;
191 case IMAGE_SUBSYSTEM_NATIVE: str = "Native"; break;
192 case IMAGE_SUBSYSTEM_WINDOWS_GUI: str = "Windows GUI"; break;
193 case IMAGE_SUBSYSTEM_WINDOWS_CUI: str = "Windows CUI"; break;
194 case IMAGE_SUBSYSTEM_OS2_CUI: str = "OS/2 CUI"; break;
195 case IMAGE_SUBSYSTEM_POSIX_CUI: str = "Posix CUI"; break;
196 case IMAGE_SUBSYSTEM_NATIVE_WINDOWS: str = "native Win9x driver"; break;
197 case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI: str = "Windows CE GUI"; break;
198 case IMAGE_SUBSYSTEM_EFI_APPLICATION: str = "EFI application"; break;
199 case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER: str = "EFI driver (boot)"; break;
200 case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER: str = "EFI driver (runtime)"; break;
201 case IMAGE_SUBSYSTEM_EFI_ROM: str = "EFI ROM"; break;
202 case IMAGE_SUBSYSTEM_XBOX: str = "Xbox application"; break;
203 case IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION: str = "Boot application"; break;
205 printf(" %-34s 0x%X (%s)\n", title, value, str);
208 static inline void print_dllflags(const char *title, WORD value)
210 printf(" %-34s 0x%X\n", title, value);
211 #define X(f,s) if (value & f) printf(" %s\n", s)
212 X(IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE, "DYNAMIC_BASE");
213 X(IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY, "FORCE_INTEGRITY");
214 X(IMAGE_DLLCHARACTERISTICS_NX_COMPAT, "NX_COMPAT");
215 X(IMAGE_DLLCHARACTERISTICS_NO_ISOLATION, "NO_ISOLATION");
216 X(IMAGE_DLLCHARACTERISTICS_NO_SEH, "NO_SEH");
217 X(IMAGE_DLLCHARACTERISTICS_NO_BIND, "NO_BIND");
218 X(IMAGE_DLLCHARACTERISTICS_WDM_DRIVER, "WDM_DRIVER");
219 X(IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE, "TERMINAL_SERVER_AWARE");
220 #undef X
223 static inline void print_datadirectory(DWORD n, const IMAGE_DATA_DIRECTORY *directory)
225 unsigned i;
226 printf("Data Directory\n");
228 for (i = 0; i < n && i < 16; i++)
230 printf(" %-12s rva: 0x%-8x size: 0x%-8x\n",
231 DirectoryNames[i], directory[i].VirtualAddress,
232 directory[i].Size);
236 static void dump_optional_header32(const IMAGE_OPTIONAL_HEADER32 *image_oh, UINT header_size)
238 IMAGE_OPTIONAL_HEADER32 oh;
239 const IMAGE_OPTIONAL_HEADER32 *optionalHeader;
241 /* in case optional header is missing or partial */
242 memset(&oh, 0, sizeof(oh));
243 memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
244 optionalHeader = &oh;
246 print_word("Magic", optionalHeader->Magic);
247 print_ver("linker version",
248 optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
249 print_dword("size of code", optionalHeader->SizeOfCode);
250 print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
251 print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
252 print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
253 print_dword("base of code", optionalHeader->BaseOfCode);
254 print_dword("base of data", optionalHeader->BaseOfData);
255 print_dword("image base", optionalHeader->ImageBase);
256 print_dword("section align", optionalHeader->SectionAlignment);
257 print_dword("file align", optionalHeader->FileAlignment);
258 print_ver("required OS version",
259 optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
260 print_ver("image version",
261 optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
262 print_ver("subsystem version",
263 optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
264 print_dword("Win32 Version", optionalHeader->Win32VersionValue);
265 print_dword("size of image", optionalHeader->SizeOfImage);
266 print_dword("size of headers", optionalHeader->SizeOfHeaders);
267 print_dword("checksum", optionalHeader->CheckSum);
268 print_subsys("Subsystem", optionalHeader->Subsystem);
269 print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
270 print_dword("stack reserve size", optionalHeader->SizeOfStackReserve);
271 print_dword("stack commit size", optionalHeader->SizeOfStackCommit);
272 print_dword("heap reserve size", optionalHeader->SizeOfHeapReserve);
273 print_dword("heap commit size", optionalHeader->SizeOfHeapCommit);
274 print_dword("loader flags", optionalHeader->LoaderFlags);
275 print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
276 printf("\n");
277 print_datadirectory(optionalHeader->NumberOfRvaAndSizes, optionalHeader->DataDirectory);
278 printf("\n");
281 static void dump_optional_header64(const IMAGE_OPTIONAL_HEADER64 *image_oh, UINT header_size)
283 IMAGE_OPTIONAL_HEADER64 oh;
284 const IMAGE_OPTIONAL_HEADER64 *optionalHeader;
286 /* in case optional header is missing or partial */
287 memset(&oh, 0, sizeof(oh));
288 memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
289 optionalHeader = &oh;
291 print_word("Magic", optionalHeader->Magic);
292 print_ver("linker version",
293 optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
294 print_dword("size of code", optionalHeader->SizeOfCode);
295 print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
296 print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
297 print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
298 print_dword("base of code", optionalHeader->BaseOfCode);
299 print_longlong("image base", optionalHeader->ImageBase);
300 print_dword("section align", optionalHeader->SectionAlignment);
301 print_dword("file align", optionalHeader->FileAlignment);
302 print_ver("required OS version",
303 optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
304 print_ver("image version",
305 optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
306 print_ver("subsystem version",
307 optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
308 print_dword("Win32 Version", optionalHeader->Win32VersionValue);
309 print_dword("size of image", optionalHeader->SizeOfImage);
310 print_dword("size of headers", optionalHeader->SizeOfHeaders);
311 print_dword("checksum", optionalHeader->CheckSum);
312 print_subsys("Subsystem", optionalHeader->Subsystem);
313 print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
314 print_longlong("stack reserve size", optionalHeader->SizeOfStackReserve);
315 print_longlong("stack commit size", optionalHeader->SizeOfStackCommit);
316 print_longlong("heap reserve size", optionalHeader->SizeOfHeapReserve);
317 print_longlong("heap commit size", optionalHeader->SizeOfHeapCommit);
318 print_dword("loader flags", optionalHeader->LoaderFlags);
319 print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
320 printf("\n");
321 print_datadirectory(optionalHeader->NumberOfRvaAndSizes, optionalHeader->DataDirectory);
322 printf("\n");
325 void dump_optional_header(const IMAGE_OPTIONAL_HEADER32 *optionalHeader, UINT header_size)
327 printf("Optional Header (%s)\n", get_magic_type(optionalHeader->Magic));
329 switch(optionalHeader->Magic) {
330 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
331 dump_optional_header32(optionalHeader, header_size);
332 break;
333 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
334 dump_optional_header64((const IMAGE_OPTIONAL_HEADER64 *)optionalHeader, header_size);
335 break;
336 default:
337 printf(" Unknown optional header magic: 0x%-4X\n", optionalHeader->Magic);
338 break;
342 void dump_file_header(const IMAGE_FILE_HEADER *fileHeader)
344 printf("File Header\n");
346 printf(" Machine: %04X (%s)\n",
347 fileHeader->Machine, get_machine_str(fileHeader->Machine));
348 printf(" Number of Sections: %d\n", fileHeader->NumberOfSections);
349 printf(" TimeDateStamp: %08X (%s) offset %lu\n",
350 fileHeader->TimeDateStamp, get_time_str(fileHeader->TimeDateStamp),
351 Offset(&(fileHeader->TimeDateStamp)));
352 printf(" PointerToSymbolTable: %08X\n", fileHeader->PointerToSymbolTable);
353 printf(" NumberOfSymbols: %08X\n", fileHeader->NumberOfSymbols);
354 printf(" SizeOfOptionalHeader: %04X\n", fileHeader->SizeOfOptionalHeader);
355 printf(" Characteristics: %04X\n", fileHeader->Characteristics);
356 #define X(f,s) if (fileHeader->Characteristics & f) printf(" %s\n", s)
357 X(IMAGE_FILE_RELOCS_STRIPPED, "RELOCS_STRIPPED");
358 X(IMAGE_FILE_EXECUTABLE_IMAGE, "EXECUTABLE_IMAGE");
359 X(IMAGE_FILE_LINE_NUMS_STRIPPED, "LINE_NUMS_STRIPPED");
360 X(IMAGE_FILE_LOCAL_SYMS_STRIPPED, "LOCAL_SYMS_STRIPPED");
361 X(IMAGE_FILE_AGGRESIVE_WS_TRIM, "AGGRESIVE_WS_TRIM");
362 X(IMAGE_FILE_LARGE_ADDRESS_AWARE, "LARGE_ADDRESS_AWARE");
363 X(IMAGE_FILE_16BIT_MACHINE, "16BIT_MACHINE");
364 X(IMAGE_FILE_BYTES_REVERSED_LO, "BYTES_REVERSED_LO");
365 X(IMAGE_FILE_32BIT_MACHINE, "32BIT_MACHINE");
366 X(IMAGE_FILE_DEBUG_STRIPPED, "DEBUG_STRIPPED");
367 X(IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "REMOVABLE_RUN_FROM_SWAP");
368 X(IMAGE_FILE_NET_RUN_FROM_SWAP, "NET_RUN_FROM_SWAP");
369 X(IMAGE_FILE_SYSTEM, "SYSTEM");
370 X(IMAGE_FILE_DLL, "DLL");
371 X(IMAGE_FILE_UP_SYSTEM_ONLY, "UP_SYSTEM_ONLY");
372 X(IMAGE_FILE_BYTES_REVERSED_HI, "BYTES_REVERSED_HI");
373 #undef X
374 printf("\n");
377 static void dump_pe_header(void)
379 dump_file_header(&PE_nt_headers->FileHeader);
380 dump_optional_header((const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader, PE_nt_headers->FileHeader.SizeOfOptionalHeader);
383 void dump_section(const IMAGE_SECTION_HEADER *sectHead, const char* strtable)
385 unsigned offset;
387 /* long section name ? */
388 if (strtable && sectHead->Name[0] == '/' &&
389 ((offset = atoi((const char*)sectHead->Name + 1)) < *(const DWORD*)strtable))
390 printf(" %.8s (%s)", sectHead->Name, strtable + offset);
391 else
392 printf(" %-8.8s", sectHead->Name);
393 printf(" VirtSize: 0x%08x VirtAddr: 0x%08x\n",
394 sectHead->Misc.VirtualSize, sectHead->VirtualAddress);
395 printf(" raw data offs: 0x%08x raw data size: 0x%08x\n",
396 sectHead->PointerToRawData, sectHead->SizeOfRawData);
397 printf(" relocation offs: 0x%08x relocations: 0x%08x\n",
398 sectHead->PointerToRelocations, sectHead->NumberOfRelocations);
399 printf(" line # offs: %-8u line #'s: %-8u\n",
400 sectHead->PointerToLinenumbers, sectHead->NumberOfLinenumbers);
401 printf(" characteristics: 0x%08x\n", sectHead->Characteristics);
402 printf(" ");
403 #define X(b,s) if (sectHead->Characteristics & b) printf(" " s)
404 /* #define IMAGE_SCN_TYPE_REG 0x00000000 - Reserved */
405 /* #define IMAGE_SCN_TYPE_DSECT 0x00000001 - Reserved */
406 /* #define IMAGE_SCN_TYPE_NOLOAD 0x00000002 - Reserved */
407 /* #define IMAGE_SCN_TYPE_GROUP 0x00000004 - Reserved */
408 /* #define IMAGE_SCN_TYPE_NO_PAD 0x00000008 - Reserved */
409 /* #define IMAGE_SCN_TYPE_COPY 0x00000010 - Reserved */
411 X(IMAGE_SCN_CNT_CODE, "CODE");
412 X(IMAGE_SCN_CNT_INITIALIZED_DATA, "INITIALIZED_DATA");
413 X(IMAGE_SCN_CNT_UNINITIALIZED_DATA, "UNINITIALIZED_DATA");
415 X(IMAGE_SCN_LNK_OTHER, "LNK_OTHER");
416 X(IMAGE_SCN_LNK_INFO, "LNK_INFO");
417 /* #define IMAGE_SCN_TYPE_OVER 0x00000400 - Reserved */
418 X(IMAGE_SCN_LNK_REMOVE, "LNK_REMOVE");
419 X(IMAGE_SCN_LNK_COMDAT, "LNK_COMDAT");
421 /* 0x00002000 - Reserved */
422 /* #define IMAGE_SCN_MEM_PROTECTED 0x00004000 - Obsolete */
423 X(IMAGE_SCN_MEM_FARDATA, "MEM_FARDATA");
425 /* #define IMAGE_SCN_MEM_SYSHEAP 0x00010000 - Obsolete */
426 X(IMAGE_SCN_MEM_PURGEABLE, "MEM_PURGEABLE");
427 X(IMAGE_SCN_MEM_16BIT, "MEM_16BIT");
428 X(IMAGE_SCN_MEM_LOCKED, "MEM_LOCKED");
429 X(IMAGE_SCN_MEM_PRELOAD, "MEM_PRELOAD");
431 switch (sectHead->Characteristics & IMAGE_SCN_ALIGN_MASK)
433 #define X2(b,s) case b: printf(" " s); break
434 X2(IMAGE_SCN_ALIGN_1BYTES, "ALIGN_1BYTES");
435 X2(IMAGE_SCN_ALIGN_2BYTES, "ALIGN_2BYTES");
436 X2(IMAGE_SCN_ALIGN_4BYTES, "ALIGN_4BYTES");
437 X2(IMAGE_SCN_ALIGN_8BYTES, "ALIGN_8BYTES");
438 X2(IMAGE_SCN_ALIGN_16BYTES, "ALIGN_16BYTES");
439 X2(IMAGE_SCN_ALIGN_32BYTES, "ALIGN_32BYTES");
440 X2(IMAGE_SCN_ALIGN_64BYTES, "ALIGN_64BYTES");
441 X2(IMAGE_SCN_ALIGN_128BYTES, "ALIGN_128BYTES");
442 X2(IMAGE_SCN_ALIGN_256BYTES, "ALIGN_256BYTES");
443 X2(IMAGE_SCN_ALIGN_512BYTES, "ALIGN_512BYTES");
444 X2(IMAGE_SCN_ALIGN_1024BYTES, "ALIGN_1024BYTES");
445 X2(IMAGE_SCN_ALIGN_2048BYTES, "ALIGN_2048BYTES");
446 X2(IMAGE_SCN_ALIGN_4096BYTES, "ALIGN_4096BYTES");
447 X2(IMAGE_SCN_ALIGN_8192BYTES, "ALIGN_8192BYTES");
448 #undef X2
451 X(IMAGE_SCN_LNK_NRELOC_OVFL, "LNK_NRELOC_OVFL");
453 X(IMAGE_SCN_MEM_DISCARDABLE, "MEM_DISCARDABLE");
454 X(IMAGE_SCN_MEM_NOT_CACHED, "MEM_NOT_CACHED");
455 X(IMAGE_SCN_MEM_NOT_PAGED, "MEM_NOT_PAGED");
456 X(IMAGE_SCN_MEM_SHARED, "MEM_SHARED");
457 X(IMAGE_SCN_MEM_EXECUTE, "MEM_EXECUTE");
458 X(IMAGE_SCN_MEM_READ, "MEM_READ");
459 X(IMAGE_SCN_MEM_WRITE, "MEM_WRITE");
460 #undef X
461 printf("\n\n");
464 static void dump_sections(const void *base, const void* addr, unsigned num_sect)
466 const IMAGE_SECTION_HEADER* sectHead = addr;
467 unsigned i;
468 const char* strtable;
470 if (PE_nt_headers->FileHeader.PointerToSymbolTable && PE_nt_headers->FileHeader.NumberOfSymbols)
472 strtable = (const char*)base +
473 PE_nt_headers->FileHeader.PointerToSymbolTable +
474 PE_nt_headers->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL);
476 else strtable = NULL;
478 printf("Section Table\n");
479 for (i = 0; i < num_sect; i++, sectHead++)
481 dump_section(sectHead, strtable);
483 if (globals.do_dump_rawdata)
485 dump_data((const unsigned char *)base + sectHead->PointerToRawData, sectHead->SizeOfRawData, " " );
486 printf("\n");
491 static void dump_dir_exported_functions(void)
493 unsigned int size = 0;
494 const IMAGE_EXPORT_DIRECTORY*exportDir = get_dir_and_size(IMAGE_FILE_EXPORT_DIRECTORY, &size);
495 unsigned int i;
496 const DWORD* pFunc;
497 const DWORD* pName;
498 const WORD* pOrdl;
499 DWORD* funcs;
501 if (!exportDir) return;
503 printf("Exports table:\n");
504 printf("\n");
505 printf(" Name: %s\n", (const char*)RVA(exportDir->Name, sizeof(DWORD)));
506 printf(" Characteristics: %08x\n", exportDir->Characteristics);
507 printf(" TimeDateStamp: %08X %s\n",
508 exportDir->TimeDateStamp, get_time_str(exportDir->TimeDateStamp));
509 printf(" Version: %u.%02u\n", exportDir->MajorVersion, exportDir->MinorVersion);
510 printf(" Ordinal base: %u\n", exportDir->Base);
511 printf(" # of functions: %u\n", exportDir->NumberOfFunctions);
512 printf(" # of Names: %u\n", exportDir->NumberOfNames);
513 printf("Addresses of functions: %08X\n", exportDir->AddressOfFunctions);
514 printf("Addresses of name ordinals: %08X\n", exportDir->AddressOfNameOrdinals);
515 printf("Addresses of names: %08X\n", exportDir->AddressOfNames);
516 printf("\n");
517 printf(" Entry Pt Ordn Name\n");
519 pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
520 if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
521 pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
522 pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
524 funcs = calloc( exportDir->NumberOfFunctions, sizeof(*funcs) );
525 if (!funcs) fatal("no memory");
527 for (i = 0; i < exportDir->NumberOfNames; i++) funcs[pOrdl[i]] = pName[i];
529 for (i = 0; i < exportDir->NumberOfFunctions; i++)
531 if (!pFunc[i]) continue;
532 printf(" %08X %5u ", pFunc[i], exportDir->Base + i);
533 if (funcs[i])
534 printf("%s", get_symbol_str((const char*)RVA(funcs[i], sizeof(DWORD))));
535 else
536 printf("<by ordinal>");
538 /* check for forwarded function */
539 if ((const char *)RVA(pFunc[i],1) >= (const char *)exportDir &&
540 (const char *)RVA(pFunc[i],1) < (const char *)exportDir + size)
541 printf(" (-> %s)", (const char *)RVA(pFunc[i],1));
542 printf("\n");
544 free(funcs);
545 printf("\n");
549 struct runtime_function
551 DWORD BeginAddress;
552 DWORD EndAddress;
553 DWORD UnwindData;
556 union handler_data
558 struct runtime_function chain;
559 DWORD handler;
562 struct opcode
564 BYTE offset;
565 BYTE code : 4;
566 BYTE info : 4;
569 struct unwind_info
571 BYTE version : 3;
572 BYTE flags : 5;
573 BYTE prolog;
574 BYTE count;
575 BYTE frame_reg : 4;
576 BYTE frame_offset : 4;
577 struct opcode opcodes[1]; /* count entries */
578 /* followed by union handler_data */
581 #define UWOP_PUSH_NONVOL 0
582 #define UWOP_ALLOC_LARGE 1
583 #define UWOP_ALLOC_SMALL 2
584 #define UWOP_SET_FPREG 3
585 #define UWOP_SAVE_NONVOL 4
586 #define UWOP_SAVE_NONVOL_FAR 5
587 #define UWOP_SAVE_XMM128 8
588 #define UWOP_SAVE_XMM128_FAR 9
589 #define UWOP_PUSH_MACHFRAME 10
591 #define UNW_FLAG_EHANDLER 1
592 #define UNW_FLAG_UHANDLER 2
593 #define UNW_FLAG_CHAININFO 4
595 static void dump_x86_64_unwind_info( const struct runtime_function *function )
597 static const char * const reg_names[16] =
598 { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
599 "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" };
601 const union handler_data *handler_data;
602 const struct unwind_info *info;
603 unsigned int i, count;
605 printf( "\nFunction %08x-%08x:\n", function->BeginAddress, function->EndAddress );
606 if (function->UnwindData & 1)
608 const struct runtime_function *next = RVA( function->UnwindData & ~1, sizeof(*next) );
609 printf( " -> function %08x-%08x\n", next->BeginAddress, next->EndAddress );
610 return;
612 info = RVA( function->UnwindData, sizeof(*info) );
614 printf( " unwind info at %08x\n", function->UnwindData );
615 if (info->version != 1)
617 printf( " *** unknown version %u\n", info->version );
618 return;
620 printf( " flags %x", info->flags );
621 if (info->flags & UNW_FLAG_EHANDLER) printf( " EHANDLER" );
622 if (info->flags & UNW_FLAG_UHANDLER) printf( " UHANDLER" );
623 if (info->flags & UNW_FLAG_CHAININFO) printf( " CHAININFO" );
624 printf( "\n prolog 0x%x bytes\n", info->prolog );
626 if (info->frame_reg)
627 printf( " frame register %s offset 0x%x(%%rsp)\n",
628 reg_names[info->frame_reg], info->frame_offset * 16 );
630 for (i = 0; i < info->count; i++)
632 printf( " 0x%02x: ", info->opcodes[i].offset );
633 switch (info->opcodes[i].code)
635 case UWOP_PUSH_NONVOL:
636 printf( "push %%%s\n", reg_names[info->opcodes[i].info] );
637 break;
638 case UWOP_ALLOC_LARGE:
639 if (info->opcodes[i].info)
641 count = *(const DWORD *)&info->opcodes[i+1];
642 i += 2;
644 else
646 count = *(const USHORT *)&info->opcodes[i+1] * 8;
647 i++;
649 printf( "sub $0x%x,%%rsp\n", count );
650 break;
651 case UWOP_ALLOC_SMALL:
652 count = (info->opcodes[i].info + 1) * 8;
653 printf( "sub $0x%x,%%rsp\n", count );
654 break;
655 case UWOP_SET_FPREG:
656 printf( "lea 0x%x(%%rsp),%s\n",
657 info->frame_offset * 16, reg_names[info->frame_reg] );
658 break;
659 case UWOP_SAVE_NONVOL:
660 count = *(const USHORT *)&info->opcodes[i+1] * 8;
661 printf( "mov %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
662 i++;
663 break;
664 case UWOP_SAVE_NONVOL_FAR:
665 count = *(const DWORD *)&info->opcodes[i+1];
666 printf( "mov %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
667 i += 2;
668 break;
669 case UWOP_SAVE_XMM128:
670 count = *(const USHORT *)&info->opcodes[i+1] * 16;
671 printf( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
672 i++;
673 break;
674 case UWOP_SAVE_XMM128_FAR:
675 count = *(const DWORD *)&info->opcodes[i+1];
676 printf( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
677 i += 2;
678 break;
679 case UWOP_PUSH_MACHFRAME:
680 printf( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
681 break;
682 default:
683 printf( "*** unknown code %u\n", info->opcodes[i].code );
684 break;
688 handler_data = (const union handler_data *)&info->opcodes[(info->count + 1) & ~1];
689 if (info->flags & UNW_FLAG_CHAININFO)
691 printf( " -> function %08x-%08x\n",
692 handler_data->chain.BeginAddress, handler_data->chain.EndAddress );
693 return;
695 if (info->flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER))
696 printf( " handler %08x data at %08x\n", handler_data->handler,
697 (ULONG)(function->UnwindData + (const char *)(&handler_data->handler + 1) - (const char *)info ));
700 static void dump_dir_exceptions(void)
702 unsigned int i, size = 0;
703 const struct runtime_function *funcs = get_dir_and_size(IMAGE_FILE_EXCEPTION_DIRECTORY, &size);
704 const IMAGE_FILE_HEADER *file_header = &PE_nt_headers->FileHeader;
706 if (!funcs) return;
708 if (file_header->Machine == IMAGE_FILE_MACHINE_AMD64)
710 size /= sizeof(*funcs);
711 printf( "Exception info (%u functions):\n", size );
712 for (i = 0; i < size; i++) dump_x86_64_unwind_info( funcs + i );
714 else printf( "Exception information not supported for %s binaries\n",
715 get_machine_str(file_header->Machine));
719 static void dump_image_thunk_data64(const IMAGE_THUNK_DATA64 *il)
721 /* FIXME: This does not properly handle large images */
722 const IMAGE_IMPORT_BY_NAME* iibn;
723 for (; il->u1.Ordinal; il++)
725 if (IMAGE_SNAP_BY_ORDINAL64(il->u1.Ordinal))
726 printf(" %4u <by ordinal>\n", (DWORD)IMAGE_ORDINAL64(il->u1.Ordinal));
727 else
729 iibn = RVA((DWORD)il->u1.AddressOfData, sizeof(DWORD));
730 if (!iibn)
731 printf("Can't grab import by name info, skipping to next ordinal\n");
732 else
733 printf(" %4u %s %x\n", iibn->Hint, iibn->Name, (DWORD)il->u1.AddressOfData);
738 static void dump_image_thunk_data32(const IMAGE_THUNK_DATA32 *il, int offset)
740 const IMAGE_IMPORT_BY_NAME* iibn;
741 for (; il->u1.Ordinal; il++)
743 if (IMAGE_SNAP_BY_ORDINAL32(il->u1.Ordinal))
744 printf(" %4u <by ordinal>\n", IMAGE_ORDINAL32(il->u1.Ordinal));
745 else
747 iibn = RVA((DWORD)il->u1.AddressOfData - offset, sizeof(DWORD));
748 if (!iibn)
749 printf("Can't grab import by name info, skipping to next ordinal\n");
750 else
751 printf(" %4u %s %x\n", iibn->Hint, iibn->Name, (DWORD)il->u1.AddressOfData);
756 static void dump_dir_imported_functions(void)
758 const IMAGE_IMPORT_DESCRIPTOR *importDesc = get_dir(IMAGE_FILE_IMPORT_DIRECTORY);
759 DWORD directorySize;
761 if (!importDesc) return;
762 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
764 const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
765 directorySize = opt->DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY].Size;
767 else
769 const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
770 directorySize = opt->DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY].Size;
773 printf("Import Table size: %08x\n", directorySize);/* FIXME */
775 for (;;)
777 const IMAGE_THUNK_DATA32* il;
779 if (!importDesc->Name || !importDesc->FirstThunk) break;
781 printf(" offset %08lx %s\n", Offset(importDesc), (const char*)RVA(importDesc->Name, sizeof(DWORD)));
782 printf(" Hint/Name Table: %08X\n", (DWORD)importDesc->u.OriginalFirstThunk);
783 printf(" TimeDateStamp: %08X (%s)\n",
784 importDesc->TimeDateStamp, get_time_str(importDesc->TimeDateStamp));
785 printf(" ForwarderChain: %08X\n", importDesc->ForwarderChain);
786 printf(" First thunk RVA: %08X\n", (DWORD)importDesc->FirstThunk);
788 printf(" Ordn Name\n");
790 il = (importDesc->u.OriginalFirstThunk != 0) ?
791 RVA((DWORD)importDesc->u.OriginalFirstThunk, sizeof(DWORD)) :
792 RVA((DWORD)importDesc->FirstThunk, sizeof(DWORD));
794 if (!il)
795 printf("Can't grab thunk data, going to next imported DLL\n");
796 else
798 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
799 dump_image_thunk_data64((const IMAGE_THUNK_DATA64*)il);
800 else
801 dump_image_thunk_data32(il, 0);
802 printf("\n");
804 importDesc++;
806 printf("\n");
809 static void dump_dir_delay_imported_functions(void)
811 const struct ImgDelayDescr
813 DWORD grAttrs;
814 DWORD szName;
815 DWORD phmod;
816 DWORD pIAT;
817 DWORD pINT;
818 DWORD pBoundIAT;
819 DWORD pUnloadIAT;
820 DWORD dwTimeStamp;
821 } *importDesc = get_dir(IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT);
822 DWORD directorySize;
824 if (!importDesc) return;
825 if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
827 const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64 *)&PE_nt_headers->OptionalHeader;
828 directorySize = opt->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
830 else
832 const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32 *)&PE_nt_headers->OptionalHeader;
833 directorySize = opt->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
836 printf("Delay Import Table size: %08x\n", directorySize); /* FIXME */
838 for (;;)
840 const IMAGE_THUNK_DATA32* il;
841 int offset = (importDesc->grAttrs & 1) ? 0 : PE_nt_headers->OptionalHeader.ImageBase;
843 if (!importDesc->szName || !importDesc->pIAT || !importDesc->pINT) break;
845 printf(" grAttrs %08x offset %08lx %s\n", importDesc->grAttrs, Offset(importDesc),
846 (const char *)RVA(importDesc->szName - offset, sizeof(DWORD)));
847 printf(" Hint/Name Table: %08x\n", importDesc->pINT);
848 printf(" TimeDateStamp: %08X (%s)\n",
849 importDesc->dwTimeStamp, get_time_str(importDesc->dwTimeStamp));
851 printf(" Ordn Name\n");
853 il = RVA(importDesc->pINT - offset, sizeof(DWORD));
855 if (!il)
856 printf("Can't grab thunk data, going to next imported DLL\n");
857 else
859 if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
860 dump_image_thunk_data64((const IMAGE_THUNK_DATA64 *)il);
861 else
862 dump_image_thunk_data32(il, offset);
863 printf("\n");
865 importDesc++;
867 printf("\n");
870 static void dump_dir_debug_dir(const IMAGE_DEBUG_DIRECTORY* idd, int idx)
872 const char* str;
874 printf("Directory %02u\n", idx + 1);
875 printf(" Characteristics: %08X\n", idd->Characteristics);
876 printf(" TimeDateStamp: %08X %s\n",
877 idd->TimeDateStamp, get_time_str(idd->TimeDateStamp));
878 printf(" Version %u.%02u\n", idd->MajorVersion, idd->MinorVersion);
879 switch (idd->Type)
881 default:
882 case IMAGE_DEBUG_TYPE_UNKNOWN: str = "UNKNOWN"; break;
883 case IMAGE_DEBUG_TYPE_COFF: str = "COFF"; break;
884 case IMAGE_DEBUG_TYPE_CODEVIEW: str = "CODEVIEW"; break;
885 case IMAGE_DEBUG_TYPE_FPO: str = "FPO"; break;
886 case IMAGE_DEBUG_TYPE_MISC: str = "MISC"; break;
887 case IMAGE_DEBUG_TYPE_EXCEPTION: str = "EXCEPTION"; break;
888 case IMAGE_DEBUG_TYPE_FIXUP: str = "FIXUP"; break;
889 case IMAGE_DEBUG_TYPE_OMAP_TO_SRC: str = "OMAP_TO_SRC"; break;
890 case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:str = "OMAP_FROM_SRC"; break;
891 case IMAGE_DEBUG_TYPE_BORLAND: str = "BORLAND"; break;
892 case IMAGE_DEBUG_TYPE_RESERVED10: str = "RESERVED10"; break;
894 printf(" Type: %u (%s)\n", idd->Type, str);
895 printf(" SizeOfData: %u\n", idd->SizeOfData);
896 printf(" AddressOfRawData: %08X\n", idd->AddressOfRawData);
897 printf(" PointerToRawData: %08X\n", idd->PointerToRawData);
899 switch (idd->Type)
901 case IMAGE_DEBUG_TYPE_UNKNOWN:
902 break;
903 case IMAGE_DEBUG_TYPE_COFF:
904 dump_coff(idd->PointerToRawData, idd->SizeOfData,
905 (const char*)PE_nt_headers + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader);
906 break;
907 case IMAGE_DEBUG_TYPE_CODEVIEW:
908 dump_codeview(idd->PointerToRawData, idd->SizeOfData);
909 break;
910 case IMAGE_DEBUG_TYPE_FPO:
911 dump_frame_pointer_omission(idd->PointerToRawData, idd->SizeOfData);
912 break;
913 case IMAGE_DEBUG_TYPE_MISC:
915 const IMAGE_DEBUG_MISC* misc = PRD(idd->PointerToRawData, idd->SizeOfData);
916 if (!misc) {printf("Can't get misc debug information\n"); break;}
917 printf(" DataType: %u (%s)\n",
918 misc->DataType,
919 (misc->DataType == IMAGE_DEBUG_MISC_EXENAME) ? "Exe name" : "Unknown");
920 printf(" Length: %u\n", misc->Length);
921 printf(" Unicode: %s\n", misc->Unicode ? "Yes" : "No");
922 printf(" Data: %s\n", misc->Data);
924 break;
925 case IMAGE_DEBUG_TYPE_EXCEPTION:
926 break;
927 case IMAGE_DEBUG_TYPE_FIXUP:
928 break;
929 case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:
930 break;
931 case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:
932 break;
933 case IMAGE_DEBUG_TYPE_BORLAND:
934 break;
935 case IMAGE_DEBUG_TYPE_RESERVED10:
936 break;
938 printf("\n");
941 static void dump_dir_debug(void)
943 const IMAGE_DEBUG_DIRECTORY*debugDir = get_dir(IMAGE_FILE_DEBUG_DIRECTORY);
944 unsigned nb_dbg, i;
946 if (!debugDir) return;
947 nb_dbg = PE_nt_headers->OptionalHeader.DataDirectory[IMAGE_FILE_DEBUG_DIRECTORY].Size /
948 sizeof(*debugDir);
949 if (!nb_dbg) return;
951 printf("Debug Table (%u directories)\n", nb_dbg);
953 for (i = 0; i < nb_dbg; i++)
955 dump_dir_debug_dir(debugDir, i);
956 debugDir++;
958 printf("\n");
961 static inline void print_clrflags(const char *title, WORD value)
963 printf(" %-34s 0x%X\n", title, value);
964 #define X(f,s) if (value & f) printf(" %s\n", s)
965 X(COMIMAGE_FLAGS_ILONLY, "ILONLY");
966 X(COMIMAGE_FLAGS_32BITREQUIRED, "32BITREQUIRED");
967 X(COMIMAGE_FLAGS_IL_LIBRARY, "IL_LIBRARY");
968 X(COMIMAGE_FLAGS_STRONGNAMESIGNED, "STRONGNAMESIGNED");
969 X(COMIMAGE_FLAGS_TRACKDEBUGDATA, "TRACKDEBUGDATA");
970 #undef X
973 static inline void print_clrdirectory(const char *title, const IMAGE_DATA_DIRECTORY *dir)
975 printf(" %-23s rva: 0x%-8x size: 0x%-8x\n", title, dir->VirtualAddress, dir->Size);
978 static void dump_dir_clr_header(void)
980 unsigned int size = 0;
981 const IMAGE_COR20_HEADER *dir = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &size);
983 if (!dir) return;
985 printf( "CLR Header\n" );
986 print_dword( "Header Size", dir->cb );
987 print_ver( "Required runtime version", dir->MajorRuntimeVersion, dir->MinorRuntimeVersion );
988 print_clrflags( "Flags", dir->Flags );
989 print_dword( "EntryPointToken", dir->EntryPointToken );
990 printf("\n");
991 printf( "CLR Data Directory\n" );
992 print_clrdirectory( "MetaData", &dir->MetaData );
993 print_clrdirectory( "Resources", &dir->Resources );
994 print_clrdirectory( "StrongNameSignature", &dir->StrongNameSignature );
995 print_clrdirectory( "CodeManagerTable", &dir->CodeManagerTable );
996 print_clrdirectory( "VTableFixups", &dir->VTableFixups );
997 print_clrdirectory( "ExportAddressTableJumps", &dir->ExportAddressTableJumps );
998 print_clrdirectory( "ManagedNativeHeader", &dir->ManagedNativeHeader );
999 printf("\n");
1002 static void dump_dir_reloc(void)
1004 unsigned int i, size = 0;
1005 const USHORT *relocs;
1006 const IMAGE_BASE_RELOCATION *rel = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_BASERELOC, &size);
1007 const IMAGE_BASE_RELOCATION *end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + size);
1008 static const char * const names[] =
1010 "BASED_ABSOLUTE",
1011 "BASED_HIGH",
1012 "BASED_LOW",
1013 "BASED_HIGHLOW",
1014 "BASED_HIGHADJ",
1015 "BASED_MIPS_JMPADDR",
1016 "BASED_SECTION",
1017 "BASED_REL",
1018 "unknown 8",
1019 "BASED_IA64_IMM64",
1020 "BASED_DIR64",
1021 "BASED_HIGH3ADJ",
1022 "unknown 12",
1023 "unknown 13",
1024 "unknown 14",
1025 "unknown 15"
1028 if (!rel) return;
1030 printf( "Relocations\n" );
1031 while (rel < end - 1 && rel->SizeOfBlock)
1033 printf( " Page %x\n", rel->VirtualAddress );
1034 relocs = (const USHORT *)(rel + 1);
1035 i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT);
1036 while (i--)
1038 USHORT offset = *relocs & 0xfff;
1039 int type = *relocs >> 12;
1040 printf( " off %04x type %s\n", offset, names[type] );
1041 relocs++;
1043 rel = (const IMAGE_BASE_RELOCATION *)relocs;
1045 printf("\n");
1048 static void dump_dir_tls(void)
1050 IMAGE_TLS_DIRECTORY64 dir;
1051 const DWORD *callbacks;
1052 const IMAGE_TLS_DIRECTORY32 *pdir = get_dir(IMAGE_FILE_THREAD_LOCAL_STORAGE);
1054 if (!pdir) return;
1056 if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1057 memcpy(&dir, pdir, sizeof(dir));
1058 else
1060 dir.StartAddressOfRawData = pdir->StartAddressOfRawData;
1061 dir.EndAddressOfRawData = pdir->EndAddressOfRawData;
1062 dir.AddressOfIndex = pdir->AddressOfIndex;
1063 dir.AddressOfCallBacks = pdir->AddressOfCallBacks;
1064 dir.SizeOfZeroFill = pdir->SizeOfZeroFill;
1065 dir.Characteristics = pdir->Characteristics;
1068 /* FIXME: This does not properly handle large images */
1069 printf( "Thread Local Storage\n" );
1070 printf( " Raw data %08x-%08x (data size %x zero fill size %x)\n",
1071 (DWORD)dir.StartAddressOfRawData, (DWORD)dir.EndAddressOfRawData,
1072 (DWORD)(dir.EndAddressOfRawData - dir.StartAddressOfRawData),
1073 (DWORD)dir.SizeOfZeroFill );
1074 printf( " Index address %08x\n", (DWORD)dir.AddressOfIndex );
1075 printf( " Characteristics %08x\n", dir.Characteristics );
1076 printf( " Callbacks %08x -> {", (DWORD)dir.AddressOfCallBacks );
1077 if (dir.AddressOfCallBacks)
1079 DWORD addr = (DWORD)dir.AddressOfCallBacks - PE_nt_headers->OptionalHeader.ImageBase;
1080 while ((callbacks = RVA(addr, sizeof(DWORD))) && *callbacks)
1082 printf( " %08x", *callbacks );
1083 addr += sizeof(DWORD);
1086 printf(" }\n\n");
1089 enum FileSig get_kind_dbg(void)
1091 const WORD* pw;
1093 pw = PRD(0, sizeof(WORD));
1094 if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}
1096 if (*pw == 0x4944 /* "DI" */) return SIG_DBG;
1097 return SIG_UNKNOWN;
1100 void dbg_dump(void)
1102 const IMAGE_SEPARATE_DEBUG_HEADER* separateDebugHead;
1103 unsigned nb_dbg;
1104 unsigned i;
1105 const IMAGE_DEBUG_DIRECTORY* debugDir;
1107 separateDebugHead = PRD(0, sizeof(*separateDebugHead));
1108 if (!separateDebugHead) {printf("Can't grab the separate header, aborting\n"); return;}
1110 printf ("Signature: %.2s (0x%4X)\n",
1111 (const char*)&separateDebugHead->Signature, separateDebugHead->Signature);
1112 printf ("Flags: 0x%04X\n", separateDebugHead->Flags);
1113 printf ("Machine: 0x%04X (%s)\n",
1114 separateDebugHead->Machine, get_machine_str(separateDebugHead->Machine));
1115 printf ("Characteristics: 0x%04X\n", separateDebugHead->Characteristics);
1116 printf ("TimeDateStamp: 0x%08X (%s)\n",
1117 separateDebugHead->TimeDateStamp, get_time_str(separateDebugHead->TimeDateStamp));
1118 printf ("CheckSum: 0x%08X\n", separateDebugHead->CheckSum);
1119 printf ("ImageBase: 0x%08X\n", separateDebugHead->ImageBase);
1120 printf ("SizeOfImage: 0x%08X\n", separateDebugHead->SizeOfImage);
1121 printf ("NumberOfSections: 0x%08X\n", separateDebugHead->NumberOfSections);
1122 printf ("ExportedNamesSize: 0x%08X\n", separateDebugHead->ExportedNamesSize);
1123 printf ("DebugDirectorySize: 0x%08X\n", separateDebugHead->DebugDirectorySize);
1125 if (!PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER),
1126 separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER)))
1127 {printf("Can't get the sections, aborting\n"); return;}
1129 dump_sections(separateDebugHead, separateDebugHead + 1, separateDebugHead->NumberOfSections);
1131 nb_dbg = separateDebugHead->DebugDirectorySize / sizeof(IMAGE_DEBUG_DIRECTORY);
1132 debugDir = PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER) +
1133 separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
1134 separateDebugHead->ExportedNamesSize,
1135 nb_dbg * sizeof(IMAGE_DEBUG_DIRECTORY));
1136 if (!debugDir) {printf("Couldn't get the debug directory info, aborting\n");return;}
1138 printf("Debug Table (%u directories)\n", nb_dbg);
1140 for (i = 0; i < nb_dbg; i++)
1142 dump_dir_debug_dir(debugDir, i);
1143 debugDir++;
1147 static const char *get_resource_type( unsigned int id )
1149 static const char * const types[] =
1151 NULL,
1152 "CURSOR",
1153 "BITMAP",
1154 "ICON",
1155 "MENU",
1156 "DIALOG",
1157 "STRING",
1158 "FONTDIR",
1159 "FONT",
1160 "ACCELERATOR",
1161 "RCDATA",
1162 "MESSAGETABLE",
1163 "GROUP_CURSOR",
1164 NULL,
1165 "GROUP_ICON",
1166 NULL,
1167 "VERSION",
1168 "DLGINCLUDE",
1169 NULL,
1170 "PLUGPLAY",
1171 "VXD",
1172 "ANICURSOR",
1173 "ANIICON",
1174 "HTML",
1175 "RT_MANIFEST"
1178 if ((size_t)id < sizeof(types)/sizeof(types[0])) return types[id];
1179 return NULL;
1182 /* dump an ASCII string with proper escaping */
1183 static int dump_strA( const unsigned char *str, size_t len )
1185 static const char escapes[32] = ".......abtnvfr.............e....";
1186 char buffer[256];
1187 char *pos = buffer;
1188 int count = 0;
1190 for (; len; str++, len--)
1192 if (pos > buffer + sizeof(buffer) - 8)
1194 fwrite( buffer, pos - buffer, 1, stdout );
1195 count += pos - buffer;
1196 pos = buffer;
1198 if (*str > 127) /* hex escape */
1200 pos += sprintf( pos, "\\x%02x", *str );
1201 continue;
1203 if (*str < 32) /* octal or C escape */
1205 if (!*str && len == 1) continue; /* do not output terminating NULL */
1206 if (escapes[*str] != '.')
1207 pos += sprintf( pos, "\\%c", escapes[*str] );
1208 else if (len > 1 && str[1] >= '0' && str[1] <= '7')
1209 pos += sprintf( pos, "\\%03o", *str );
1210 else
1211 pos += sprintf( pos, "\\%o", *str );
1212 continue;
1214 if (*str == '\\') *pos++ = '\\';
1215 *pos++ = *str;
1217 fwrite( buffer, pos - buffer, 1, stdout );
1218 count += pos - buffer;
1219 return count;
1222 /* dump a Unicode string with proper escaping */
1223 static int dump_strW( const WCHAR *str, size_t len )
1225 static const char escapes[32] = ".......abtnvfr.............e....";
1226 char buffer[256];
1227 char *pos = buffer;
1228 int count = 0;
1230 for (; len; str++, len--)
1232 if (pos > buffer + sizeof(buffer) - 8)
1234 fwrite( buffer, pos - buffer, 1, stdout );
1235 count += pos - buffer;
1236 pos = buffer;
1238 if (*str > 127) /* hex escape */
1240 if (len > 1 && str[1] < 128 && isxdigit((char)str[1]))
1241 pos += sprintf( pos, "\\x%04x", *str );
1242 else
1243 pos += sprintf( pos, "\\x%x", *str );
1244 continue;
1246 if (*str < 32) /* octal or C escape */
1248 if (!*str && len == 1) continue; /* do not output terminating NULL */
1249 if (escapes[*str] != '.')
1250 pos += sprintf( pos, "\\%c", escapes[*str] );
1251 else if (len > 1 && str[1] >= '0' && str[1] <= '7')
1252 pos += sprintf( pos, "\\%03o", *str );
1253 else
1254 pos += sprintf( pos, "\\%o", *str );
1255 continue;
1257 if (*str == '\\') *pos++ = '\\';
1258 *pos++ = *str;
1260 fwrite( buffer, pos - buffer, 1, stdout );
1261 count += pos - buffer;
1262 return count;
1265 /* dump data for a STRING resource */
1266 static void dump_string_data( const WCHAR *ptr, unsigned int size, unsigned int id, const char *prefix )
1268 int i;
1270 for (i = 0; i < 16 && size; i++)
1272 unsigned len = *ptr++;
1274 if (len >= size)
1276 len = size;
1277 size = 0;
1279 else size -= len + 1;
1281 if (len)
1283 printf( "%s%04x \"", prefix, (id - 1) * 16 + i );
1284 dump_strW( ptr, len );
1285 printf( "\"\n" );
1286 ptr += len;
1291 /* dump data for a MESSAGETABLE resource */
1292 static void dump_msgtable_data( const void *ptr, unsigned int size, unsigned int id, const char *prefix )
1294 const MESSAGE_RESOURCE_DATA *data = ptr;
1295 const MESSAGE_RESOURCE_BLOCK *block = data->Blocks;
1296 unsigned i, j;
1298 for (i = 0; i < data->NumberOfBlocks; i++, block++)
1300 const MESSAGE_RESOURCE_ENTRY *entry;
1302 entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)data + block->OffsetToEntries);
1303 for (j = block->LowId; j <= block->HighId; j++)
1305 if (entry->Flags & MESSAGE_RESOURCE_UNICODE)
1307 const WCHAR *str = (const WCHAR *)entry->Text;
1308 printf( "%s%08x L\"", prefix, j );
1309 dump_strW( str, strlenW(str) );
1310 printf( "\"\n" );
1312 else
1314 const char *str = (const char *) entry->Text;
1315 printf( "%s%08x \"", prefix, j );
1316 dump_strA( entry->Text, strlen(str) );
1317 printf( "\"\n" );
1319 entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)entry + entry->Length);
1324 static void dump_dir_resource(void)
1326 const IMAGE_RESOURCE_DIRECTORY *root = get_dir(IMAGE_FILE_RESOURCE_DIRECTORY);
1327 const IMAGE_RESOURCE_DIRECTORY *namedir;
1328 const IMAGE_RESOURCE_DIRECTORY *langdir;
1329 const IMAGE_RESOURCE_DIRECTORY_ENTRY *e1, *e2, *e3;
1330 const IMAGE_RESOURCE_DIR_STRING_U *string;
1331 const IMAGE_RESOURCE_DATA_ENTRY *data;
1332 int i, j, k;
1334 if (!root) return;
1336 printf( "Resources:" );
1338 for (i = 0; i< root->NumberOfNamedEntries + root->NumberOfIdEntries; i++)
1340 e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
1341 namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s3.OffsetToDirectory);
1342 for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
1344 e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
1345 langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s3.OffsetToDirectory);
1346 for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
1348 e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
1350 printf( "\n " );
1351 if (e1->u1.s1.NameIsString)
1353 string = (const IMAGE_RESOURCE_DIR_STRING_U*)((const char *)root + e1->u1.s1.NameOffset);
1354 dump_unicode_str( string->NameString, string->Length );
1356 else
1358 const char *type = get_resource_type( e1->u1.s2.Id );
1359 if (type) printf( "%s", type );
1360 else printf( "%04x", e1->u1.s2.Id );
1363 printf( " Name=" );
1364 if (e2->u1.s1.NameIsString)
1366 string = (const IMAGE_RESOURCE_DIR_STRING_U*) ((const char *)root + e2->u1.s1.NameOffset);
1367 dump_unicode_str( string->NameString, string->Length );
1369 else
1370 printf( "%04x", e2->u1.s2.Id );
1372 printf( " Language=%04x:\n", e3->u1.s2.Id );
1373 data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
1374 if (e1->u1.s1.NameIsString)
1376 dump_data( RVA( data->OffsetToData, data->Size ), data->Size, " " );
1378 else switch(e1->u1.s2.Id)
1380 case 6:
1381 dump_string_data( RVA( data->OffsetToData, data->Size ), data->Size,
1382 e2->u1.s2.Id, " " );
1383 break;
1384 case 11:
1385 dump_msgtable_data( RVA( data->OffsetToData, data->Size ), data->Size,
1386 e2->u1.s2.Id, " " );
1387 break;
1388 default:
1389 dump_data( RVA( data->OffsetToData, data->Size ), data->Size, " " );
1390 break;
1395 printf( "\n\n" );
1398 static void dump_debug(void)
1400 const char* stabs = NULL;
1401 unsigned szstabs = 0;
1402 const char* stabstr = NULL;
1403 unsigned szstr = 0;
1404 unsigned i;
1405 const IMAGE_SECTION_HEADER* sectHead;
1407 sectHead = (const IMAGE_SECTION_HEADER*)
1408 ((const char*)PE_nt_headers + sizeof(DWORD) +
1409 sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader);
1411 for (i = 0; i < PE_nt_headers->FileHeader.NumberOfSections; i++, sectHead++)
1413 if (!strcmp((const char *)sectHead->Name, ".stab"))
1415 stabs = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize);
1416 szstabs = sectHead->Misc.VirtualSize;
1418 if (!strncmp((const char *)sectHead->Name, ".stabstr", 8))
1420 stabstr = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize);
1421 szstr = sectHead->Misc.VirtualSize;
1424 if (stabs && stabstr)
1425 dump_stabs(stabs, szstabs, stabstr, szstr);
1428 static void dump_symbol_table(void)
1430 const IMAGE_SYMBOL* sym;
1431 int numsym;
1433 numsym = PE_nt_headers->FileHeader.NumberOfSymbols;
1434 if (!PE_nt_headers->FileHeader.PointerToSymbolTable || !numsym)
1435 return;
1436 sym = PRD(PE_nt_headers->FileHeader.PointerToSymbolTable,
1437 sizeof(*sym) * numsym);
1438 if (!sym) return;
1440 dump_coff_symbol_table(sym, numsym, IMAGE_FIRST_SECTION(PE_nt_headers));
1443 enum FileSig get_kind_exec(void)
1445 const WORD* pw;
1446 const DWORD* pdw;
1447 const IMAGE_DOS_HEADER* dh;
1449 pw = PRD(0, sizeof(WORD));
1450 if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}
1452 if (*pw != IMAGE_DOS_SIGNATURE) return SIG_UNKNOWN;
1454 if ((dh = PRD(0, sizeof(IMAGE_DOS_HEADER))))
1456 /* the signature is the first DWORD */
1457 pdw = PRD(dh->e_lfanew, sizeof(DWORD));
1458 if (pdw)
1460 if (*pdw == IMAGE_NT_SIGNATURE) return SIG_PE;
1461 if (*(const WORD *)pdw == IMAGE_OS2_SIGNATURE) return SIG_NE;
1462 if (*(const WORD *)pdw == IMAGE_VXD_SIGNATURE) return SIG_LE;
1463 return SIG_DOS;
1466 return 0;
1469 void pe_dump(void)
1471 int all = (globals.dumpsect != NULL) && strcmp(globals.dumpsect, "ALL") == 0;
1473 PE_nt_headers = get_nt_header();
1474 if (is_fake_dll()) printf( "*** This is a Wine fake DLL ***\n\n" );
1476 if (globals.do_dumpheader)
1478 dump_pe_header();
1479 /* FIXME: should check ptr */
1480 dump_sections(PRD(0, 1), (const char*)PE_nt_headers + sizeof(DWORD) +
1481 sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader,
1482 PE_nt_headers->FileHeader.NumberOfSections);
1484 else if (!globals.dumpsect)
1486 /* show at least something here */
1487 dump_pe_header();
1490 if (globals.dumpsect)
1492 if (all || !strcmp(globals.dumpsect, "import"))
1494 dump_dir_imported_functions();
1495 dump_dir_delay_imported_functions();
1497 if (all || !strcmp(globals.dumpsect, "export"))
1498 dump_dir_exported_functions();
1499 if (all || !strcmp(globals.dumpsect, "debug"))
1500 dump_dir_debug();
1501 if (all || !strcmp(globals.dumpsect, "resource"))
1502 dump_dir_resource();
1503 if (all || !strcmp(globals.dumpsect, "tls"))
1504 dump_dir_tls();
1505 if (all || !strcmp(globals.dumpsect, "clr"))
1506 dump_dir_clr_header();
1507 if (all || !strcmp(globals.dumpsect, "reloc"))
1508 dump_dir_reloc();
1509 if (all || !strcmp(globals.dumpsect, "except"))
1510 dump_dir_exceptions();
1512 if (globals.do_symbol_table)
1513 dump_symbol_table();
1514 if (globals.do_debug)
1515 dump_debug();
1518 typedef struct _dll_symbol {
1519 size_t ordinal;
1520 char *symbol;
1521 } dll_symbol;
1523 static dll_symbol *dll_symbols = NULL;
1524 static dll_symbol *dll_current_symbol = NULL;
1526 /* Compare symbols by ordinal for qsort */
1527 static int symbol_cmp(const void *left, const void *right)
1529 return ((const dll_symbol *)left)->ordinal > ((const dll_symbol *)right)->ordinal;
1532 /*******************************************************************
1533 * dll_close
1535 * Free resources used by DLL
1537 /* FIXME: Not used yet
1538 static void dll_close (void)
1540 dll_symbol* ds;
1542 if (!dll_symbols) {
1543 fatal("No symbols");
1545 for (ds = dll_symbols; ds->symbol; ds++)
1546 free(ds->symbol);
1547 free (dll_symbols);
1548 dll_symbols = NULL;
1552 static void do_grab_sym( void )
1554 const IMAGE_EXPORT_DIRECTORY*exportDir;
1555 unsigned i, j;
1556 const DWORD* pName;
1557 const DWORD* pFunc;
1558 const WORD* pOrdl;
1559 const char* ptr;
1560 DWORD* map;
1562 PE_nt_headers = get_nt_header();
1563 if (!(exportDir = get_dir(IMAGE_FILE_EXPORT_DIRECTORY))) return;
1565 pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
1566 if (!pName) {printf("Can't grab functions' name table\n"); return;}
1567 pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
1568 if (!pOrdl) {printf("Can't grab functions' ordinal table\n"); return;}
1569 pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
1570 if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
1572 /* dll_close(); */
1574 if (!(dll_symbols = malloc((exportDir->NumberOfFunctions + 1) * sizeof(dll_symbol))))
1575 fatal ("Out of memory");
1577 /* bit map of used funcs */
1578 map = calloc(((exportDir->NumberOfFunctions + 31) & ~31) / 32, sizeof(DWORD));
1579 if (!map) fatal("no memory");
1581 for (j = 0; j < exportDir->NumberOfNames; j++, pOrdl++)
1583 map[*pOrdl / 32] |= 1 << (*pOrdl % 32);
1584 ptr = RVA(*pName++, sizeof(DWORD));
1585 if (!ptr) ptr = "cant_get_function";
1586 dll_symbols[j].symbol = strdup(ptr);
1587 dll_symbols[j].ordinal = exportDir->Base + *pOrdl;
1588 assert(dll_symbols[j].symbol);
1591 for (i = 0; i < exportDir->NumberOfFunctions; i++)
1593 if (pFunc[i] && !(map[i / 32] & (1 << (i % 32))))
1595 char ordinal_text[256];
1596 /* Ordinal only entry */
1597 snprintf (ordinal_text, sizeof(ordinal_text), "%s_%u",
1598 globals.forward_dll ? globals.forward_dll : OUTPUT_UC_DLL_NAME,
1599 exportDir->Base + i);
1600 str_toupper(ordinal_text);
1601 dll_symbols[j].symbol = strdup(ordinal_text);
1602 assert(dll_symbols[j].symbol);
1603 dll_symbols[j].ordinal = exportDir->Base + i;
1604 j++;
1605 assert(j <= exportDir->NumberOfFunctions);
1608 free(map);
1610 if (NORMAL)
1611 printf("%u named symbols in DLL, %u total, %d unique (ordinal base = %d)\n",
1612 exportDir->NumberOfNames, exportDir->NumberOfFunctions, j, exportDir->Base);
1614 qsort( dll_symbols, j, sizeof(dll_symbol), symbol_cmp );
1616 dll_symbols[j].symbol = NULL;
1618 dll_current_symbol = dll_symbols;
1621 /*******************************************************************
1622 * dll_open
1624 * Open a DLL and read in exported symbols
1626 int dll_open (const char *dll_name)
1628 return dump_analysis(dll_name, do_grab_sym, SIG_PE);
1631 /*******************************************************************
1632 * dll_next_symbol
1634 * Get next exported symbol from dll
1636 int dll_next_symbol (parsed_symbol * sym)
1638 if (!dll_current_symbol || !dll_current_symbol->symbol)
1639 return 1;
1640 assert (dll_symbols);
1641 sym->symbol = strdup (dll_current_symbol->symbol);
1642 sym->ordinal = dll_current_symbol->ordinal;
1643 dll_current_symbol++;
1644 return 0;