winedump: Start dumping .NET specific bits from PE executables.
[wine] / tools / winedump / pe.c
1 /*
2  *      PE dumping utility
3  *
4  *      Copyright 2001 Eric Pouech
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
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>
41
42 #define NONAMELESSUNION
43 #define NONAMELESSSTRUCT
44 #include "windef.h"
45 #include "winbase.h"
46 #include "winedump.h"
47
48 static const IMAGE_NT_HEADERS32*        PE_nt_headers;
49
50 const char *get_machine_str(int mach)
51 {
52     switch (mach)
53     {
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     }
65     return "???";
66 }
67
68 static const void*      RVA(unsigned long rva, unsigned long len)
69 {
70     IMAGE_SECTION_HEADER*       sectHead;
71     int                         i;
72
73     if (rva == 0) return NULL;
74
75     sectHead = IMAGE_FIRST_SECTION(PE_nt_headers);
76     for (i = PE_nt_headers->FileHeader.NumberOfSections - 1; i >= 0; i--)
77     {
78         if (sectHead[i].VirtualAddress <= rva &&
79             rva + len <= (DWORD)sectHead[i].VirtualAddress + sectHead[i].SizeOfRawData)
80         {
81             /* return image import directory offset */
82             return PRD(sectHead[i].PointerToRawData + rva - sectHead[i].VirtualAddress, len);
83         }
84     }
85
86     return NULL;
87 }
88
89 static const IMAGE_NT_HEADERS32 *get_nt_header( void )
90 {
91     const IMAGE_DOS_HEADER *dos;
92     dos = PRD(0, sizeof(*dos));
93     if (!dos) return NULL;
94     return PRD(dos->e_lfanew, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER));
95 }
96
97 static int is_fake_dll( void )
98 {
99     static const char fakedll_signature[] = "Wine placeholder DLL";
100     const IMAGE_DOS_HEADER *dos;
101
102     dos = PRD(0, sizeof(*dos) + sizeof(fakedll_signature));
103
104     if (dos && dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
105         !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
106     return FALSE;
107 }
108
109 static const void *get_dir_and_size(unsigned int idx, unsigned int *size)
110 {
111     if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
112     {
113         const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
114         if (idx >= opt->NumberOfRvaAndSizes)
115             return NULL;
116         if(size)
117             *size = opt->DataDirectory[idx].Size;
118         return RVA(opt->DataDirectory[idx].VirtualAddress,
119                    opt->DataDirectory[idx].Size);
120     }
121     else
122     {
123         const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
124         if (idx >= opt->NumberOfRvaAndSizes)
125             return NULL;
126         if(size)
127             *size = opt->DataDirectory[idx].Size;
128         return RVA(opt->DataDirectory[idx].VirtualAddress,
129                    opt->DataDirectory[idx].Size);
130     }
131 }
132
133 static  const void*     get_dir(unsigned idx)
134 {
135     return get_dir_and_size(idx, 0);
136 }
137
138 static const char * const DirectoryNames[16] = {
139     "EXPORT",           "IMPORT",       "RESOURCE",     "EXCEPTION",
140     "SECURITY",         "BASERELOC",    "DEBUG",        "ARCHITECTURE",
141     "GLOBALPTR",        "TLS",          "LOAD_CONFIG",  "Bound IAT",
142     "IAT",              "Delay IAT",    "CLR Header", ""
143 };
144
145 static const char *get_magic_type(WORD magic)
146 {
147     switch(magic) {
148         case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
149             return "32bit";
150         case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
151             return "64bit";
152         case IMAGE_ROM_OPTIONAL_HDR_MAGIC:
153             return "ROM";
154     }
155     return "???";
156 }
157
158 static inline void print_word(const char *title, WORD value)
159 {
160     printf("  %-34s 0x%-4X         %u\n", title, value, value);
161 }
162
163 static inline void print_dword(const char *title, DWORD value)
164 {
165     printf("  %-34s 0x%-8x     %u\n", title, value, value);
166 }
167
168 static inline void print_longlong(const char *title, ULONGLONG value)
169 {
170     printf("  %-34s 0x", title);
171     if(value >> 32)
172         printf("%lx%08lx\n", (unsigned long)(value >> 32), (unsigned long)value);
173     else
174         printf("%lx\n", (unsigned long)value);
175 }
176
177 static inline void print_ver(const char *title, BYTE major, BYTE minor)
178 {
179     printf("  %-34s %u.%02u\n", title, major, minor);
180 }
181
182 static inline void print_subsys(const char *title, WORD value)
183 {
184     const char *str;
185     switch (value)
186     {
187         default:
188         case IMAGE_SUBSYSTEM_UNKNOWN:       str = "Unknown";        break;
189         case IMAGE_SUBSYSTEM_NATIVE:        str = "Native";         break;
190         case IMAGE_SUBSYSTEM_WINDOWS_GUI:   str = "Windows GUI";    break;
191         case IMAGE_SUBSYSTEM_WINDOWS_CUI:   str = "Windows CUI";    break;
192         case IMAGE_SUBSYSTEM_OS2_CUI:       str = "OS/2 CUI";       break;
193         case IMAGE_SUBSYSTEM_POSIX_CUI:     str = "Posix CUI";      break;
194     }
195     printf("  %-34s 0x%X (%s)\n", title, value, str);
196 }
197
198 static inline void print_dllflags(const char *title, WORD value)
199 {
200     printf("  %-34s 0x%X\n", title, value);
201 #define X(f,s) if (value & f) printf("    %s\n", s)
202     X(IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE,          "DYNAMIC_BASE");
203     X(IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY,       "FORCE_INTEGRITY");
204     X(IMAGE_DLLCHARACTERISTICS_NX_COMPAT,             "NX_COMPAT");
205     X(IMAGE_DLLCHARACTERISTICS_NO_ISOLATION,          "NO_ISOLATION");
206     X(IMAGE_DLLCHARACTERISTICS_NO_SEH,                "NO_SEH");
207     X(IMAGE_DLLCHARACTERISTICS_NO_BIND,               "NO_BIND");
208     X(IMAGE_DLLCHARACTERISTICS_WDM_DRIVER,            "WDM_DRIVER");
209     X(IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE, "TERMINAL_SERVER_AWARE");
210 #undef X
211 }
212
213 static inline void print_datadirectory(DWORD n, const IMAGE_DATA_DIRECTORY *directory)
214 {
215     unsigned i;
216     printf("Data Directory\n");
217
218     for (i = 0; i < n && i < 16; i++)
219     {
220         printf("  %-12s rva: 0x%-8x  size: 0x%-8x\n",
221                DirectoryNames[i], directory[i].VirtualAddress,
222                directory[i].Size);
223     }
224 }
225
226 static void dump_optional_header32(const IMAGE_OPTIONAL_HEADER32 *image_oh, UINT header_size)
227 {
228     IMAGE_OPTIONAL_HEADER32 oh;
229     const IMAGE_OPTIONAL_HEADER32 *optionalHeader;
230
231     /* in case optional header is missing or partial */
232     memset(&oh, 0, sizeof(oh));
233     memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
234     optionalHeader = &oh;
235
236     print_word("Magic", optionalHeader->Magic);
237     print_ver("linker version",
238               optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
239     print_dword("size of code", optionalHeader->SizeOfCode);
240     print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
241     print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
242     print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
243     print_dword("base of code", optionalHeader->BaseOfCode);
244     print_dword("base of data", optionalHeader->BaseOfData);
245     print_dword("image base", optionalHeader->ImageBase);
246     print_dword("section align", optionalHeader->SectionAlignment);
247     print_dword("file align", optionalHeader->FileAlignment);
248     print_ver("required OS version",
249               optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
250     print_ver("image version",
251               optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
252     print_ver("subsystem version",
253               optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
254     print_dword("Win32 Version", optionalHeader->Win32VersionValue);
255     print_dword("size of image", optionalHeader->SizeOfImage);
256     print_dword("size of headers", optionalHeader->SizeOfHeaders);
257     print_dword("checksum", optionalHeader->CheckSum);
258     print_subsys("Subsystem", optionalHeader->Subsystem);
259     print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
260     print_dword("stack reserve size", optionalHeader->SizeOfStackReserve);
261     print_dword("stack commit size", optionalHeader->SizeOfStackCommit);
262     print_dword("heap reserve size", optionalHeader->SizeOfHeapReserve);
263     print_dword("heap commit size", optionalHeader->SizeOfHeapCommit);
264     print_dword("loader flags", optionalHeader->LoaderFlags);
265     print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
266     printf("\n");
267     print_datadirectory(optionalHeader->NumberOfRvaAndSizes, optionalHeader->DataDirectory);
268     printf("\n");
269 }
270
271 static void dump_optional_header64(const IMAGE_OPTIONAL_HEADER64 *image_oh, UINT header_size)
272 {
273     IMAGE_OPTIONAL_HEADER64 oh;
274     const IMAGE_OPTIONAL_HEADER64 *optionalHeader;
275
276     /* in case optional header is missing or partial */
277     memset(&oh, 0, sizeof(oh));
278     memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
279     optionalHeader = &oh;
280
281     print_word("Magic", optionalHeader->Magic);
282     print_ver("linker version",
283               optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
284     print_dword("size of code", optionalHeader->SizeOfCode);
285     print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
286     print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
287     print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
288     print_dword("base of code", optionalHeader->BaseOfCode);
289     print_longlong("image base", optionalHeader->ImageBase);
290     print_dword("section align", optionalHeader->SectionAlignment);
291     print_dword("file align", optionalHeader->FileAlignment);
292     print_ver("required OS version",
293               optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
294     print_ver("image version",
295               optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
296     print_ver("subsystem version",
297               optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
298     print_dword("Win32 Version", optionalHeader->Win32VersionValue);
299     print_dword("size of image", optionalHeader->SizeOfImage);
300     print_dword("size of headers", optionalHeader->SizeOfHeaders);
301     print_dword("checksum", optionalHeader->CheckSum);
302     print_subsys("Subsystem", optionalHeader->Subsystem);
303     print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
304     print_longlong("stack reserve size", optionalHeader->SizeOfStackReserve);
305     print_longlong("stack commit size", optionalHeader->SizeOfStackCommit);
306     print_longlong("heap reserve size", optionalHeader->SizeOfHeapReserve);
307     print_longlong("heap commit size", optionalHeader->SizeOfHeapCommit);
308     print_dword("loader flags", optionalHeader->LoaderFlags);
309     print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
310     printf("\n");
311     print_datadirectory(optionalHeader->NumberOfRvaAndSizes, optionalHeader->DataDirectory);
312     printf("\n");
313 }
314
315 void dump_optional_header(const IMAGE_OPTIONAL_HEADER32 *optionalHeader, UINT header_size)
316 {
317     printf("Optional Header (%s)\n", get_magic_type(optionalHeader->Magic));
318
319     switch(optionalHeader->Magic) {
320         case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
321             dump_optional_header32(optionalHeader, header_size);
322             break;
323         case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
324             dump_optional_header64((const IMAGE_OPTIONAL_HEADER64 *)optionalHeader, header_size);
325             break;
326         default:
327             printf("  Unknown optional header magic: 0x%-4X\n", optionalHeader->Magic);
328             break;
329     }
330 }
331
332 void dump_file_header(const IMAGE_FILE_HEADER *fileHeader)
333 {
334     printf("File Header\n");
335
336     printf("  Machine:                      %04X (%s)\n",
337            fileHeader->Machine, get_machine_str(fileHeader->Machine));
338     printf("  Number of Sections:           %d\n", fileHeader->NumberOfSections);
339     printf("  TimeDateStamp:                %08X (%s) offset %lu\n",
340            fileHeader->TimeDateStamp, get_time_str(fileHeader->TimeDateStamp),
341            Offset(&(fileHeader->TimeDateStamp)));
342     printf("  PointerToSymbolTable:         %08X\n", fileHeader->PointerToSymbolTable);
343     printf("  NumberOfSymbols:              %08X\n", fileHeader->NumberOfSymbols);
344     printf("  SizeOfOptionalHeader:         %04X\n", fileHeader->SizeOfOptionalHeader);
345     printf("  Characteristics:              %04X\n", fileHeader->Characteristics);
346 #define X(f,s)  if (fileHeader->Characteristics & f) printf("    %s\n", s)
347     X(IMAGE_FILE_RELOCS_STRIPPED,       "RELOCS_STRIPPED");
348     X(IMAGE_FILE_EXECUTABLE_IMAGE,      "EXECUTABLE_IMAGE");
349     X(IMAGE_FILE_LINE_NUMS_STRIPPED,    "LINE_NUMS_STRIPPED");
350     X(IMAGE_FILE_LOCAL_SYMS_STRIPPED,   "LOCAL_SYMS_STRIPPED");
351     X(IMAGE_FILE_AGGRESIVE_WS_TRIM,     "AGGRESIVE_WS_TRIM");
352     X(IMAGE_FILE_LARGE_ADDRESS_AWARE,   "LARGE_ADDRESS_AWARE");
353     X(IMAGE_FILE_16BIT_MACHINE,         "16BIT_MACHINE");
354     X(IMAGE_FILE_BYTES_REVERSED_LO,     "BYTES_REVERSED_LO");
355     X(IMAGE_FILE_32BIT_MACHINE,         "32BIT_MACHINE");
356     X(IMAGE_FILE_DEBUG_STRIPPED,        "DEBUG_STRIPPED");
357     X(IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP,       "REMOVABLE_RUN_FROM_SWAP");
358     X(IMAGE_FILE_NET_RUN_FROM_SWAP,     "NET_RUN_FROM_SWAP");
359     X(IMAGE_FILE_SYSTEM,                "SYSTEM");
360     X(IMAGE_FILE_DLL,                   "DLL");
361     X(IMAGE_FILE_UP_SYSTEM_ONLY,        "UP_SYSTEM_ONLY");
362     X(IMAGE_FILE_BYTES_REVERSED_HI,     "BYTES_REVERSED_HI");
363 #undef X
364     printf("\n");
365 }
366
367 static  void    dump_pe_header(void)
368 {
369     dump_file_header(&PE_nt_headers->FileHeader);
370     dump_optional_header((const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader, PE_nt_headers->FileHeader.SizeOfOptionalHeader);
371 }
372
373 void dump_section(const IMAGE_SECTION_HEADER *sectHead)
374 {
375         printf("  %-8.8s   VirtSize: 0x%08x  VirtAddr:  0x%08x\n",
376                sectHead->Name, sectHead->Misc.VirtualSize, sectHead->VirtualAddress);
377         printf("    raw data offs:   0x%08x  raw data size: 0x%08x\n",
378                sectHead->PointerToRawData, sectHead->SizeOfRawData);
379         printf("    relocation offs: 0x%08x  relocations:   0x%08x\n",
380                sectHead->PointerToRelocations, sectHead->NumberOfRelocations);
381         printf("    line # offs:     %-8u  line #'s:      %-8u\n",
382                sectHead->PointerToLinenumbers, sectHead->NumberOfLinenumbers);
383         printf("    characteristics: 0x%08x\n", sectHead->Characteristics);
384         printf("    ");
385 #define X(b,s)  if (sectHead->Characteristics & b) printf("  " s)
386 /* #define IMAGE_SCN_TYPE_REG                   0x00000000 - Reserved */
387 /* #define IMAGE_SCN_TYPE_DSECT                 0x00000001 - Reserved */
388 /* #define IMAGE_SCN_TYPE_NOLOAD                0x00000002 - Reserved */
389 /* #define IMAGE_SCN_TYPE_GROUP                 0x00000004 - Reserved */
390 /* #define IMAGE_SCN_TYPE_NO_PAD                0x00000008 - Reserved */
391 /* #define IMAGE_SCN_TYPE_COPY                  0x00000010 - Reserved */
392
393         X(IMAGE_SCN_CNT_CODE,                   "CODE");
394         X(IMAGE_SCN_CNT_INITIALIZED_DATA,       "INITIALIZED_DATA");
395         X(IMAGE_SCN_CNT_UNINITIALIZED_DATA,     "UNINITIALIZED_DATA");
396
397         X(IMAGE_SCN_LNK_OTHER,                  "LNK_OTHER");
398         X(IMAGE_SCN_LNK_INFO,                   "LNK_INFO");
399 /* #define      IMAGE_SCN_TYPE_OVER             0x00000400 - Reserved */
400         X(IMAGE_SCN_LNK_REMOVE,                 "LNK_REMOVE");
401         X(IMAGE_SCN_LNK_COMDAT,                 "LNK_COMDAT");
402
403 /*                                              0x00002000 - Reserved */
404 /* #define IMAGE_SCN_MEM_PROTECTED              0x00004000 - Obsolete */
405         X(IMAGE_SCN_MEM_FARDATA,                "MEM_FARDATA");
406
407 /* #define IMAGE_SCN_MEM_SYSHEAP                0x00010000 - Obsolete */
408         X(IMAGE_SCN_MEM_PURGEABLE,              "MEM_PURGEABLE");
409         X(IMAGE_SCN_MEM_16BIT,                  "MEM_16BIT");
410         X(IMAGE_SCN_MEM_LOCKED,                 "MEM_LOCKED");
411         X(IMAGE_SCN_MEM_PRELOAD,                "MEM_PRELOAD");
412
413         switch (sectHead->Characteristics & IMAGE_SCN_ALIGN_MASK)
414         {
415 #define X2(b,s) case b: printf("  " s); break
416         X2(IMAGE_SCN_ALIGN_1BYTES,              "ALIGN_1BYTES");
417         X2(IMAGE_SCN_ALIGN_2BYTES,              "ALIGN_2BYTES");
418         X2(IMAGE_SCN_ALIGN_4BYTES,              "ALIGN_4BYTES");
419         X2(IMAGE_SCN_ALIGN_8BYTES,              "ALIGN_8BYTES");
420         X2(IMAGE_SCN_ALIGN_16BYTES,             "ALIGN_16BYTES");
421         X2(IMAGE_SCN_ALIGN_32BYTES,             "ALIGN_32BYTES");
422         X2(IMAGE_SCN_ALIGN_64BYTES,             "ALIGN_64BYTES");
423         X2(IMAGE_SCN_ALIGN_128BYTES,            "ALIGN_128BYTES");
424         X2(IMAGE_SCN_ALIGN_256BYTES,            "ALIGN_256BYTES");
425         X2(IMAGE_SCN_ALIGN_512BYTES,            "ALIGN_512BYTES");
426         X2(IMAGE_SCN_ALIGN_1024BYTES,           "ALIGN_1024BYTES");
427         X2(IMAGE_SCN_ALIGN_2048BYTES,           "ALIGN_2048BYTES");
428         X2(IMAGE_SCN_ALIGN_4096BYTES,           "ALIGN_4096BYTES");
429         X2(IMAGE_SCN_ALIGN_8192BYTES,           "ALIGN_8192BYTES");
430 #undef X2
431         }
432
433         X(IMAGE_SCN_LNK_NRELOC_OVFL,            "LNK_NRELOC_OVFL");
434
435         X(IMAGE_SCN_MEM_DISCARDABLE,            "MEM_DISCARDABLE");
436         X(IMAGE_SCN_MEM_NOT_CACHED,             "MEM_NOT_CACHED");
437         X(IMAGE_SCN_MEM_NOT_PAGED,              "MEM_NOT_PAGED");
438         X(IMAGE_SCN_MEM_SHARED,                 "MEM_SHARED");
439         X(IMAGE_SCN_MEM_EXECUTE,                "MEM_EXECUTE");
440         X(IMAGE_SCN_MEM_READ,                   "MEM_READ");
441         X(IMAGE_SCN_MEM_WRITE,                  "MEM_WRITE");
442 #undef X
443         printf("\n\n");
444 }
445
446 static void dump_sections(const void *base, const void* addr, unsigned num_sect)
447 {
448     const IMAGE_SECTION_HEADER* sectHead = addr;
449     unsigned                    i;
450
451     printf("Section Table\n");
452     for (i = 0; i < num_sect; i++, sectHead++)
453     {
454         dump_section(sectHead);
455
456         if (globals.do_dump_rawdata)
457         {
458             dump_data((const unsigned char *)base + sectHead->PointerToRawData, sectHead->SizeOfRawData, "    " );
459             printf("\n");
460         }
461     }
462 }
463
464 static  void    dump_dir_exported_functions(void)
465 {
466     unsigned int size = 0;
467     const IMAGE_EXPORT_DIRECTORY*exportDir = get_dir_and_size(IMAGE_FILE_EXPORT_DIRECTORY, &size);
468     unsigned int                i;
469     const DWORD*                pFunc;
470     const DWORD*                pName;
471     const WORD*                 pOrdl;
472     DWORD*                      map;
473     parsed_symbol               symbol;
474
475     if (!exportDir) return;
476
477     printf("Exports table:\n");
478     printf("\n");
479     printf("  Name:            %s\n", (const char*)RVA(exportDir->Name, sizeof(DWORD)));
480     printf("  Characteristics: %08x\n", exportDir->Characteristics);
481     printf("  TimeDateStamp:   %08X %s\n",
482            exportDir->TimeDateStamp, get_time_str(exportDir->TimeDateStamp));
483     printf("  Version:         %u.%02u\n", exportDir->MajorVersion, exportDir->MinorVersion);
484     printf("  Ordinal base:    %u\n", exportDir->Base);
485     printf("  # of functions:  %u\n", exportDir->NumberOfFunctions);
486     printf("  # of Names:      %u\n", exportDir->NumberOfNames);
487     printf("Addresses of functions: %08X\n", exportDir->AddressOfFunctions);
488     printf("Addresses of name ordinals: %08X\n", exportDir->AddressOfNameOrdinals);
489     printf("Addresses of names: %08X\n", exportDir->AddressOfNames);
490     printf("\n");
491     printf("  Entry Pt  Ordn  Name\n");
492
493     pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
494     if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
495     pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
496     if (!pName) {printf("Can't grab functions' name table\n"); return;}
497     pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
498     if (!pOrdl) {printf("Can't grab functions' ordinal table\n"); return;}
499
500     /* bit map of used funcs */
501     map = calloc(((exportDir->NumberOfFunctions + 31) & ~31) / 32, sizeof(DWORD));
502     if (!map) fatal("no memory");
503
504     for (i = 0; i < exportDir->NumberOfNames; i++, pName++, pOrdl++)
505     {
506         const char*     name;
507
508         map[*pOrdl / 32] |= 1 << (*pOrdl % 32);
509
510         name = (const char*)RVA(*pName, sizeof(DWORD));
511         if (name && globals.do_demangle)
512         {
513             printf("  %08X  %4u ", pFunc[*pOrdl], exportDir->Base + *pOrdl);
514
515             symbol_init(&symbol, name);
516             if (symbol_demangle(&symbol) == -1)
517                 printf(name);
518             else if (symbol.flags & SYM_DATA)
519                 printf(symbol.arg_text[0]);
520             else
521                 output_prototype(stdout, &symbol);
522             symbol_clear(&symbol);
523         }
524         else
525         {
526             printf("  %08X  %4u %s", pFunc[*pOrdl], exportDir->Base + *pOrdl, name);
527         }
528         /* check for forwarded function */
529         if ((const char *)RVA(pFunc[*pOrdl],sizeof(void*)) >= (const char *)exportDir &&
530             (const char *)RVA(pFunc[*pOrdl],sizeof(void*)) < (const char *)exportDir + size)
531             printf( " (-> %s)", (const char *)RVA(pFunc[*pOrdl],1));
532         printf("\n");
533     }
534     pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
535     if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
536     for (i = 0; i < exportDir->NumberOfFunctions; i++)
537     {
538         if (pFunc[i] && !(map[i / 32] & (1 << (i % 32))))
539         {
540             printf("  %08X  %4u <by ordinal>\n", pFunc[i], exportDir->Base + i);
541         }
542     }
543     free(map);
544     printf("\n");
545 }
546
547 static void dump_image_thunk_data64(const IMAGE_THUNK_DATA64 *il)
548 {
549     /* FIXME: This does not properly handle large images */
550     const IMAGE_IMPORT_BY_NAME* iibn;
551     for (; il->u1.Ordinal; il++)
552     {
553         if (IMAGE_SNAP_BY_ORDINAL64(il->u1.Ordinal))
554             printf("  %4u  <by ordinal>\n", (DWORD)IMAGE_ORDINAL64(il->u1.Ordinal));
555         else
556         {
557             iibn = RVA((DWORD)il->u1.AddressOfData, sizeof(DWORD));
558             if (!iibn)
559                 printf("Can't grab import by name info, skipping to next ordinal\n");
560             else
561                 printf("  %4u  %s %x\n", iibn->Hint, iibn->Name, (DWORD)il->u1.AddressOfData);
562         }
563     }
564 }
565
566 static void dump_image_thunk_data32(const IMAGE_THUNK_DATA32 *il)
567 {
568     const IMAGE_IMPORT_BY_NAME* iibn;
569     for (; il->u1.Ordinal; il++)
570     {
571         if (IMAGE_SNAP_BY_ORDINAL32(il->u1.Ordinal))
572             printf("  %4u  <by ordinal>\n", IMAGE_ORDINAL32(il->u1.Ordinal));
573         else
574         {
575             iibn = RVA((DWORD)il->u1.AddressOfData, sizeof(DWORD));
576             if (!iibn)
577                 printf("Can't grab import by name info, skipping to next ordinal\n");
578             else
579                 printf("  %4u  %s %x\n", iibn->Hint, iibn->Name, (DWORD)il->u1.AddressOfData);
580         }
581     }
582 }
583
584 static  void    dump_dir_imported_functions(void)
585 {
586     const IMAGE_IMPORT_DESCRIPTOR       *importDesc = get_dir(IMAGE_FILE_IMPORT_DIRECTORY);
587     DWORD directorySize;
588
589     if (!importDesc)    return;
590     if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
591     {
592         const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
593         directorySize = opt->DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY].Size;
594     }
595     else
596     {
597         const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
598         directorySize = opt->DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY].Size;
599     }
600
601     printf("Import Table size: %08x\n", directorySize);/* FIXME */
602
603     for (;;)
604     {
605         const IMAGE_THUNK_DATA32*       il;
606
607         if (!importDesc->Name || !importDesc->FirstThunk) break;
608
609         printf("  offset %08lx %s\n", Offset(importDesc), (const char*)RVA(importDesc->Name, sizeof(DWORD)));
610         printf("  Hint/Name Table: %08X\n", (DWORD)importDesc->u.OriginalFirstThunk);
611         printf("  TimeDateStamp:   %08X (%s)\n",
612                importDesc->TimeDateStamp, get_time_str(importDesc->TimeDateStamp));
613         printf("  ForwarderChain:  %08X\n", importDesc->ForwarderChain);
614         printf("  First thunk RVA: %08X\n", (DWORD)importDesc->FirstThunk);
615
616         printf("  Ordn  Name\n");
617
618         il = (importDesc->u.OriginalFirstThunk != 0) ?
619             RVA((DWORD)importDesc->u.OriginalFirstThunk, sizeof(DWORD)) :
620             RVA((DWORD)importDesc->FirstThunk, sizeof(DWORD));
621
622         if (!il)
623             printf("Can't grab thunk data, going to next imported DLL\n");
624         else
625         {
626             if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
627                 dump_image_thunk_data64((const IMAGE_THUNK_DATA64*)il);
628             else
629                 dump_image_thunk_data32(il);
630             printf("\n");
631         }
632         importDesc++;
633     }
634     printf("\n");
635 }
636
637 static void dump_dir_delay_imported_functions(void)
638 {
639     const struct ImgDelayDescr
640     {
641         DWORD grAttrs;
642         DWORD szName;
643         DWORD phmod;
644         DWORD pIAT;
645         DWORD pINT;
646         DWORD pBoundIAT;
647         DWORD pUnloadIAT;
648         DWORD dwTimeStamp;
649     } *importDesc = get_dir(IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT);
650     DWORD directorySize;
651
652     if (!importDesc) return;
653     if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
654     {
655         const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64 *)&PE_nt_headers->OptionalHeader;
656         directorySize = opt->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
657     }
658     else
659     {
660         const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32 *)&PE_nt_headers->OptionalHeader;
661         directorySize = opt->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
662     }
663
664     printf("Delay Import Table size: %08x\n", directorySize); /* FIXME */
665
666     for (;;)
667     {
668         BOOL                            use_rva = importDesc->grAttrs & 1;
669         const IMAGE_THUNK_DATA32*       il;
670
671         if (!importDesc->szName || !importDesc->pIAT || !importDesc->pINT) break;
672
673         printf("  grAttrs %08x offset %08lx %s\n", importDesc->grAttrs, Offset(importDesc),
674                use_rva ? (const char *)RVA(importDesc->szName, sizeof(DWORD)) : (char *)importDesc->szName);
675         printf("  Hint/Name Table: %08x\n", importDesc->pINT);
676         printf("  TimeDateStamp:   %08X (%s)\n",
677                importDesc->dwTimeStamp, get_time_str(importDesc->dwTimeStamp));
678
679         printf("  Ordn  Name\n");
680
681         il = use_rva ? (const IMAGE_THUNK_DATA32 *)RVA(importDesc->pINT, sizeof(DWORD)) : (const IMAGE_THUNK_DATA32 *)importDesc->pINT;
682
683         if (!il)
684             printf("Can't grab thunk data, going to next imported DLL\n");
685         else
686         {
687             if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
688                 dump_image_thunk_data64((const IMAGE_THUNK_DATA64 *)il);
689             else
690                 dump_image_thunk_data32(il);
691             printf("\n");
692         }
693         importDesc++;
694     }
695     printf("\n");
696 }
697
698 static  void    dump_dir_debug_dir(const IMAGE_DEBUG_DIRECTORY* idd, int idx)
699 {
700     const       char*   str;
701
702     printf("Directory %02u\n", idx + 1);
703     printf("  Characteristics:   %08X\n", idd->Characteristics);
704     printf("  TimeDateStamp:     %08X %s\n",
705            idd->TimeDateStamp, get_time_str(idd->TimeDateStamp));
706     printf("  Version            %u.%02u\n", idd->MajorVersion, idd->MinorVersion);
707     switch (idd->Type)
708     {
709     default:
710     case IMAGE_DEBUG_TYPE_UNKNOWN:      str = "UNKNOWN";        break;
711     case IMAGE_DEBUG_TYPE_COFF:         str = "COFF";           break;
712     case IMAGE_DEBUG_TYPE_CODEVIEW:     str = "CODEVIEW";       break;
713     case IMAGE_DEBUG_TYPE_FPO:          str = "FPO";            break;
714     case IMAGE_DEBUG_TYPE_MISC:         str = "MISC";           break;
715     case IMAGE_DEBUG_TYPE_EXCEPTION:    str = "EXCEPTION";      break;
716     case IMAGE_DEBUG_TYPE_FIXUP:        str = "FIXUP";          break;
717     case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:  str = "OMAP_TO_SRC";    break;
718     case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:str = "OMAP_FROM_SRC";  break;
719     case IMAGE_DEBUG_TYPE_BORLAND:      str = "BORLAND";        break;
720     case IMAGE_DEBUG_TYPE_RESERVED10:   str = "RESERVED10";     break;
721     }
722     printf("  Type:              %u (%s)\n", idd->Type, str);
723     printf("  SizeOfData:        %u\n", idd->SizeOfData);
724     printf("  AddressOfRawData:  %08X\n", idd->AddressOfRawData);
725     printf("  PointerToRawData:  %08X\n", idd->PointerToRawData);
726
727     switch (idd->Type)
728     {
729     case IMAGE_DEBUG_TYPE_UNKNOWN:
730         break;
731     case IMAGE_DEBUG_TYPE_COFF:
732         dump_coff(idd->PointerToRawData, idd->SizeOfData, 
733                   (const char*)PE_nt_headers + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader);
734         break;
735     case IMAGE_DEBUG_TYPE_CODEVIEW:
736         dump_codeview(idd->PointerToRawData, idd->SizeOfData);
737         break;
738     case IMAGE_DEBUG_TYPE_FPO:
739         dump_frame_pointer_omission(idd->PointerToRawData, idd->SizeOfData);
740         break;
741     case IMAGE_DEBUG_TYPE_MISC:
742     {
743         const IMAGE_DEBUG_MISC* misc = PRD(idd->PointerToRawData, idd->SizeOfData);
744         if (!misc) {printf("Can't get misc debug information\n"); break;}
745         printf("    DataType:          %u (%s)\n",
746                misc->DataType,
747                (misc->DataType == IMAGE_DEBUG_MISC_EXENAME) ? "Exe name" : "Unknown");
748         printf("    Length:            %u\n", misc->Length);
749         printf("    Unicode:           %s\n", misc->Unicode ? "Yes" : "No");
750         printf("    Data:              %s\n", misc->Data);
751     }
752     break;
753     case IMAGE_DEBUG_TYPE_EXCEPTION:
754         break;
755     case IMAGE_DEBUG_TYPE_FIXUP:
756         break;
757     case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:
758         break;
759     case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:
760         break;
761     case IMAGE_DEBUG_TYPE_BORLAND:
762         break;
763     case IMAGE_DEBUG_TYPE_RESERVED10:
764         break;
765     }
766     printf("\n");
767 }
768
769 static void     dump_dir_debug(void)
770 {
771     const IMAGE_DEBUG_DIRECTORY*debugDir = get_dir(IMAGE_FILE_DEBUG_DIRECTORY);
772     unsigned                    nb_dbg, i;
773
774     if (!debugDir) return;
775     nb_dbg = PE_nt_headers->OptionalHeader.DataDirectory[IMAGE_FILE_DEBUG_DIRECTORY].Size /
776         sizeof(*debugDir);
777     if (!nb_dbg) return;
778
779     printf("Debug Table (%u directories)\n", nb_dbg);
780
781     for (i = 0; i < nb_dbg; i++)
782     {
783         dump_dir_debug_dir(debugDir, i);
784         debugDir++;
785     }
786     printf("\n");
787 }
788
789 static inline void print_clrflags(const char *title, WORD value)
790 {
791     printf("  %-34s 0x%X\n", title, value);
792 #define X(f,s) if (value & f) printf("    %s\n", s)
793     X(COMIMAGE_FLAGS_ILONLY,           "ILONLY");
794     X(COMIMAGE_FLAGS_32BITREQUIRED,    "32BITREQUIRED");
795     X(COMIMAGE_FLAGS_IL_LIBRARY,       "IL_LIBRARY");
796     X(COMIMAGE_FLAGS_STRONGNAMESIGNED, "STRONGNAMESIGNED");
797     X(COMIMAGE_FLAGS_TRACKDEBUGDATA,   "TRACKDEBUGDATA");
798 #undef X
799 }
800
801 static inline void print_clrdirectory(const char *title, const IMAGE_DATA_DIRECTORY *dir)
802 {
803     printf("  %-23s rva: 0x%-8x  size: 0x%-8x\n", title, dir->VirtualAddress, dir->Size);
804 }
805
806 static void dump_dir_clr_header(void)
807 {
808     unsigned int size = 0;
809     const IMAGE_COR20_HEADER *dir = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &size);
810
811     if (!dir) return;
812
813     printf( "CLR Header\n" );
814     print_dword( "Header Size", dir->cb );
815     print_ver( "Required runtime version", dir->MajorRuntimeVersion, dir->MinorRuntimeVersion );
816     print_clrflags( "Flags", dir->Flags );
817     print_dword( "EntryPointToken", dir->EntryPointToken );
818     printf("\n");
819     printf( "CLR Data Directory\n" );
820     print_clrdirectory( "MetaData", &dir->MetaData );
821     print_clrdirectory( "Resources", &dir->Resources );
822     print_clrdirectory( "StrongNameSignature", &dir->StrongNameSignature );
823     print_clrdirectory( "CodeManagerTable", &dir->CodeManagerTable );
824     print_clrdirectory( "VTableFixups", &dir->VTableFixups );
825     print_clrdirectory( "ExportAddressTableJumps", &dir->ExportAddressTableJumps );
826     print_clrdirectory( "ManagedNativeHeader", &dir->ManagedNativeHeader );
827     printf("\n");
828 }
829
830 static void dump_dir_tls(void)
831 {
832     IMAGE_TLS_DIRECTORY64 dir;
833     const DWORD *callbacks;
834     const IMAGE_TLS_DIRECTORY32 *pdir = get_dir(IMAGE_FILE_THREAD_LOCAL_STORAGE);
835
836     if (!pdir) return;
837
838     if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
839         memcpy(&dir, pdir, sizeof(dir));
840     else
841     {
842         dir.StartAddressOfRawData = pdir->StartAddressOfRawData;
843         dir.EndAddressOfRawData = pdir->EndAddressOfRawData;
844         dir.AddressOfIndex = pdir->AddressOfIndex;
845         dir.AddressOfCallBacks = pdir->AddressOfCallBacks;
846         dir.SizeOfZeroFill = pdir->SizeOfZeroFill;
847         dir.Characteristics = pdir->Characteristics;
848     }
849
850     /* FIXME: This does not properly handle large images */
851     printf( "Thread Local Storage\n" );
852     printf( "  Raw data        %08x-%08x (data size %x zero fill size %x)\n",
853             (DWORD)dir.StartAddressOfRawData, (DWORD)dir.EndAddressOfRawData,
854             (DWORD)(dir.EndAddressOfRawData - dir.StartAddressOfRawData),
855             (DWORD)dir.SizeOfZeroFill );
856     printf( "  Index address   %08x\n", (DWORD)dir.AddressOfIndex );
857     printf( "  Characteristics %08x\n", dir.Characteristics );
858     printf( "  Callbacks       %08x -> {", (DWORD)dir.AddressOfCallBacks );
859     if (dir.AddressOfCallBacks)
860     {
861         DWORD   addr = (DWORD)dir.AddressOfCallBacks - PE_nt_headers->OptionalHeader.ImageBase;
862         while ((callbacks = RVA(addr, sizeof(DWORD))) && *callbacks)
863         {
864             printf( " %08x", *callbacks );
865             addr += sizeof(DWORD);
866         }
867     }
868     printf(" }\n\n");
869 }
870
871 enum FileSig get_kind_dbg(void)
872 {
873     const WORD*                pw;
874
875     pw = PRD(0, sizeof(WORD));
876     if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}
877
878     if (*pw == 0x4944 /* "DI" */) return SIG_DBG;
879     return SIG_UNKNOWN;
880 }
881
882 void    dbg_dump(void)
883 {
884     const IMAGE_SEPARATE_DEBUG_HEADER*  separateDebugHead;
885     unsigned                            nb_dbg;
886     unsigned                            i;
887     const IMAGE_DEBUG_DIRECTORY*        debugDir;
888
889     separateDebugHead = PRD(0, sizeof(separateDebugHead));
890     if (!separateDebugHead) {printf("Can't grab the separate header, aborting\n"); return;}
891
892     printf ("Signature:          %.2s (0x%4X)\n",
893             (const char*)&separateDebugHead->Signature, separateDebugHead->Signature);
894     printf ("Flags:              0x%04X\n", separateDebugHead->Flags);
895     printf ("Machine:            0x%04X (%s)\n",
896             separateDebugHead->Machine, get_machine_str(separateDebugHead->Machine));
897     printf ("Characteristics:    0x%04X\n", separateDebugHead->Characteristics);
898     printf ("TimeDateStamp:      0x%08X (%s)\n",
899             separateDebugHead->TimeDateStamp, get_time_str(separateDebugHead->TimeDateStamp));
900     printf ("CheckSum:           0x%08X\n", separateDebugHead->CheckSum);
901     printf ("ImageBase:          0x%08X\n", separateDebugHead->ImageBase);
902     printf ("SizeOfImage:        0x%08X\n", separateDebugHead->SizeOfImage);
903     printf ("NumberOfSections:   0x%08X\n", separateDebugHead->NumberOfSections);
904     printf ("ExportedNamesSize:  0x%08X\n", separateDebugHead->ExportedNamesSize);
905     printf ("DebugDirectorySize: 0x%08X\n", separateDebugHead->DebugDirectorySize);
906
907     if (!PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER),
908              separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER)))
909     {printf("Can't get the sections, aborting\n"); return;}
910
911     dump_sections(separateDebugHead, separateDebugHead + 1, separateDebugHead->NumberOfSections);
912
913     nb_dbg = separateDebugHead->DebugDirectorySize / sizeof(IMAGE_DEBUG_DIRECTORY);
914     debugDir = PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER) +
915                    separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
916                    separateDebugHead->ExportedNamesSize,
917                    nb_dbg * sizeof(IMAGE_DEBUG_DIRECTORY));
918     if (!debugDir) {printf("Couldn't get the debug directory info, aborting\n");return;}
919
920     printf("Debug Table (%u directories)\n", nb_dbg);
921
922     for (i = 0; i < nb_dbg; i++)
923     {
924         dump_dir_debug_dir(debugDir, i);
925         debugDir++;
926     }
927 }
928
929 static const char *get_resource_type( unsigned int id )
930 {
931     static const char * const types[] =
932     {
933         NULL,
934         "CURSOR",
935         "BITMAP",
936         "ICON",
937         "MENU",
938         "DIALOG",
939         "STRING",
940         "FONTDIR",
941         "FONT",
942         "ACCELERATOR",
943         "RCDATA",
944         "MESSAGETABLE",
945         "GROUP_CURSOR",
946         NULL,
947         "GROUP_ICON",
948         NULL,
949         "VERSION",
950         "DLGINCLUDE",
951         NULL,
952         "PLUGPLAY",
953         "VXD",
954         "ANICURSOR",
955         "ANIICON",
956         "HTML"
957     };
958
959     if ((size_t)id < sizeof(types)/sizeof(types[0])) return types[id];
960     return NULL;
961 }
962
963 /* dump an ASCII string with proper escaping */
964 static int dump_strA( const unsigned char *str, size_t len )
965 {
966     static const char escapes[32] = ".......abtnvfr.............e....";
967     char buffer[256];
968     char *pos = buffer;
969     int count = 0;
970
971     for (; len; str++, len--)
972     {
973         if (pos > buffer + sizeof(buffer) - 8)
974         {
975             fwrite( buffer, pos - buffer, 1, stdout );
976             count += pos - buffer;
977             pos = buffer;
978         }
979         if (*str > 127)  /* hex escape */
980         {
981             pos += sprintf( pos, "\\x%02x", *str );
982             continue;
983         }
984         if (*str < 32)  /* octal or C escape */
985         {
986             if (!*str && len == 1) continue;  /* do not output terminating NULL */
987             if (escapes[*str] != '.')
988                 pos += sprintf( pos, "\\%c", escapes[*str] );
989             else if (len > 1 && str[1] >= '0' && str[1] <= '7')
990                 pos += sprintf( pos, "\\%03o", *str );
991             else
992                 pos += sprintf( pos, "\\%o", *str );
993             continue;
994         }
995         if (*str == '\\') *pos++ = '\\';
996         *pos++ = *str;
997     }
998     fwrite( buffer, pos - buffer, 1, stdout );
999     count += pos - buffer;
1000     return count;
1001 }
1002
1003 /* dump a Unicode string with proper escaping */
1004 static int dump_strW( const WCHAR *str, size_t len )
1005 {
1006     static const char escapes[32] = ".......abtnvfr.............e....";
1007     char buffer[256];
1008     char *pos = buffer;
1009     int count = 0;
1010
1011     for (; len; str++, len--)
1012     {
1013         if (pos > buffer + sizeof(buffer) - 8)
1014         {
1015             fwrite( buffer, pos - buffer, 1, stdout );
1016             count += pos - buffer;
1017             pos = buffer;
1018         }
1019         if (*str > 127)  /* hex escape */
1020         {
1021             if (len > 1 && str[1] < 128 && isxdigit((char)str[1]))
1022                 pos += sprintf( pos, "\\x%04x", *str );
1023             else
1024                 pos += sprintf( pos, "\\x%x", *str );
1025             continue;
1026         }
1027         if (*str < 32)  /* octal or C escape */
1028         {
1029             if (!*str && len == 1) continue;  /* do not output terminating NULL */
1030             if (escapes[*str] != '.')
1031                 pos += sprintf( pos, "\\%c", escapes[*str] );
1032             else if (len > 1 && str[1] >= '0' && str[1] <= '7')
1033                 pos += sprintf( pos, "\\%03o", *str );
1034             else
1035                 pos += sprintf( pos, "\\%o", *str );
1036             continue;
1037         }
1038         if (*str == '\\') *pos++ = '\\';
1039         *pos++ = *str;
1040     }
1041     fwrite( buffer, pos - buffer, 1, stdout );
1042     count += pos - buffer;
1043     return count;
1044 }
1045
1046 /* dump data for a STRING resource */
1047 static void dump_string_data( const WCHAR *ptr, unsigned int size, unsigned int id, const char *prefix )
1048 {
1049     int i;
1050
1051     for (i = 0; i < 16 && size; i++)
1052     {
1053         unsigned len = *ptr++;
1054
1055         if (len >= size)
1056         {
1057             len = size;
1058             size = 0;
1059         }
1060         else size -= len + 1;
1061
1062         if (len)
1063         {
1064             printf( "%s%04x \"", prefix, (id - 1) * 16 + i );
1065             dump_strW( ptr, len );
1066             printf( "\"\n" );
1067             ptr += len;
1068         }
1069     }
1070 }
1071
1072 /* dump data for a MESSAGETABLE resource */
1073 static void dump_msgtable_data( const void *ptr, unsigned int size, unsigned int id, const char *prefix )
1074 {
1075     const MESSAGE_RESOURCE_DATA *data = ptr;
1076     const MESSAGE_RESOURCE_BLOCK *block = data->Blocks;
1077     unsigned i, j;
1078
1079     for (i = 0; i < data->NumberOfBlocks; i++, block++)
1080     {
1081         const MESSAGE_RESOURCE_ENTRY *entry;
1082
1083         entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)data + block->OffsetToEntries);
1084         for (j = block->LowId; j <= block->HighId; j++)
1085         {
1086             if (entry->Flags & MESSAGE_RESOURCE_UNICODE)
1087             {
1088                 const WCHAR *str = (const WCHAR *)entry->Text;
1089                 printf( "%s%08x L\"", prefix, j );
1090                 dump_strW( str, strlenW(str) );
1091                 printf( "\"\n" );
1092             }
1093             else
1094             {
1095                 const char *str = (const char *) entry->Text;
1096                 printf( "%s%08x \"", prefix, j );
1097                 dump_strA( entry->Text, strlen(str) );
1098                 printf( "\"\n" );
1099             }
1100             entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)entry + entry->Length);
1101         }
1102     }
1103 }
1104
1105 static void dump_dir_resource(void)
1106 {
1107     const IMAGE_RESOURCE_DIRECTORY *root = get_dir(IMAGE_FILE_RESOURCE_DIRECTORY);
1108     const IMAGE_RESOURCE_DIRECTORY *namedir;
1109     const IMAGE_RESOURCE_DIRECTORY *langdir;
1110     const IMAGE_RESOURCE_DIRECTORY_ENTRY *e1, *e2, *e3;
1111     const IMAGE_RESOURCE_DIR_STRING_U *string;
1112     const IMAGE_RESOURCE_DATA_ENTRY *data;
1113     int i, j, k;
1114
1115     if (!root) return;
1116
1117     printf( "Resources:" );
1118
1119     for (i = 0; i< root->NumberOfNamedEntries + root->NumberOfIdEntries; i++)
1120     {
1121         e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
1122         namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s3.OffsetToDirectory);
1123         for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
1124         {
1125             e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
1126             langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s3.OffsetToDirectory);
1127             for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
1128             {
1129                 e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
1130
1131                 printf( "\n  " );
1132                 if (e1->u1.s1.NameIsString)
1133                 {
1134                     string = (const IMAGE_RESOURCE_DIR_STRING_U*)((const char *)root + e1->u1.s1.NameOffset);
1135                     dump_unicode_str( string->NameString, string->Length );
1136                 }
1137                 else
1138                 {
1139                     const char *type = get_resource_type( e1->u1.s2.Id );
1140                     if (type) printf( "%s", type );
1141                     else printf( "%04x", e1->u1.s2.Id );
1142                 }
1143
1144                 printf( " Name=" );
1145                 if (e2->u1.s1.NameIsString)
1146                 {
1147                     string = (const IMAGE_RESOURCE_DIR_STRING_U*) ((const char *)root + e2->u1.s1.NameOffset);
1148                     dump_unicode_str( string->NameString, string->Length );
1149                 }
1150                 else
1151                     printf( "%04x", e2->u1.s2.Id );
1152
1153                 printf( " Language=%04x:\n", e3->u1.s2.Id );
1154                 data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
1155                 if (e1->u1.s1.NameIsString)
1156                 {
1157                     dump_data( RVA( data->OffsetToData, data->Size ), data->Size, "    " );
1158                 }
1159                 else switch(e1->u1.s2.Id)
1160                 {
1161                 case 6:
1162                     dump_string_data( RVA( data->OffsetToData, data->Size ), data->Size,
1163                                       e2->u1.s2.Id, "    " );
1164                     break;
1165                 case 11:
1166                     dump_msgtable_data( RVA( data->OffsetToData, data->Size ), data->Size,
1167                                         e2->u1.s2.Id, "    " );
1168                     break;
1169                 default:
1170                     dump_data( RVA( data->OffsetToData, data->Size ), data->Size, "    " );
1171                     break;
1172                 }
1173             }
1174         }
1175     }
1176     printf( "\n\n" );
1177 }
1178
1179 static void dump_debug(void)
1180 {
1181     const char* stabs = NULL;
1182     unsigned    szstabs = 0;
1183     const char* stabstr = NULL;
1184     unsigned    szstr = 0;
1185     unsigned    i;
1186     const IMAGE_SECTION_HEADER* sectHead;
1187
1188     sectHead = (const IMAGE_SECTION_HEADER*)
1189         ((const char*)PE_nt_headers + sizeof(DWORD) +
1190          sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader);
1191
1192     for (i = 0; i < PE_nt_headers->FileHeader.NumberOfSections; i++, sectHead++)
1193     {
1194         if (!strcmp((const char *)sectHead->Name, ".stab"))
1195         {
1196             stabs = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize); 
1197             szstabs = sectHead->Misc.VirtualSize;
1198         }
1199         if (!strncmp((const char *)sectHead->Name, ".stabstr", 8))
1200         {
1201             stabstr = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize);
1202             szstr = sectHead->Misc.VirtualSize;
1203         }
1204     }
1205     if (stabs && stabstr)
1206         dump_stabs(stabs, szstabs, stabstr, szstr);
1207 }
1208
1209 enum FileSig get_kind_exec(void)
1210 {
1211     const WORD*                pw;
1212     const DWORD*               pdw;
1213     const IMAGE_DOS_HEADER*    dh;
1214
1215     pw = PRD(0, sizeof(WORD));
1216     if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}
1217
1218     if (*pw != IMAGE_DOS_SIGNATURE) return SIG_UNKNOWN;
1219
1220     if ((dh = PRD(0, sizeof(IMAGE_DOS_HEADER))))
1221     {
1222         /* the signature is the first DWORD */
1223         pdw = PRD(dh->e_lfanew, sizeof(DWORD));
1224         if (pdw)
1225         {
1226             if (*pdw == IMAGE_NT_SIGNATURE)                     return SIG_PE;
1227             if (*(const WORD *)pdw == IMAGE_OS2_SIGNATURE)      return SIG_NE;
1228             if (*(const WORD *)pdw == IMAGE_VXD_SIGNATURE)      return SIG_LE;
1229             return SIG_DOS;
1230         }
1231     }
1232     return 0;
1233 }
1234
1235 void pe_dump(void)
1236 {
1237     int all = (globals.dumpsect != NULL) && strcmp(globals.dumpsect, "ALL") == 0;
1238
1239     PE_nt_headers = get_nt_header();
1240     if (is_fake_dll()) printf( "*** This is a Wine fake DLL ***\n\n" );
1241
1242     if (globals.do_dumpheader)
1243     {
1244         dump_pe_header();
1245         /* FIXME: should check ptr */
1246         dump_sections(PRD(0, 1), (const char*)PE_nt_headers + sizeof(DWORD) +
1247                       sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader,
1248                       PE_nt_headers->FileHeader.NumberOfSections);
1249     }
1250     else if (!globals.dumpsect)
1251     {
1252         /* show at least something here */
1253         dump_pe_header();
1254     }
1255
1256     if (globals.dumpsect)
1257     {
1258         if (all || !strcmp(globals.dumpsect, "import"))
1259         {
1260             dump_dir_imported_functions();
1261             dump_dir_delay_imported_functions();
1262         }
1263         if (all || !strcmp(globals.dumpsect, "export"))
1264             dump_dir_exported_functions();
1265         if (all || !strcmp(globals.dumpsect, "debug"))
1266             dump_dir_debug();
1267         if (all || !strcmp(globals.dumpsect, "resource"))
1268             dump_dir_resource();
1269         if (all || !strcmp(globals.dumpsect, "tls"))
1270             dump_dir_tls();
1271         if (all || !strcmp(globals.dumpsect, "clr"))
1272             dump_dir_clr_header();
1273 #if 0
1274         /* FIXME: not implemented yet */
1275         if (all || !strcmp(globals.dumpsect, "reloc"))
1276             dump_dir_reloc();
1277 #endif
1278     }
1279     if (globals.do_debug)
1280         dump_debug();
1281 }
1282
1283 typedef struct _dll_symbol {
1284     size_t      ordinal;
1285     char       *symbol;
1286 } dll_symbol;
1287
1288 static dll_symbol *dll_symbols = NULL;
1289 static dll_symbol *dll_current_symbol = NULL;
1290
1291 /* Compare symbols by ordinal for qsort */
1292 static int symbol_cmp(const void *left, const void *right)
1293 {
1294     return ((const dll_symbol *)left)->ordinal > ((const dll_symbol *)right)->ordinal;
1295 }
1296
1297 /*******************************************************************
1298  *         dll_close
1299  *
1300  * Free resources used by DLL
1301  */
1302 /* FIXME: Not used yet
1303 static void dll_close (void)
1304 {
1305     dll_symbol* ds;
1306
1307     if (!dll_symbols) {
1308         fatal("No symbols");
1309     }
1310     for (ds = dll_symbols; ds->symbol; ds++)
1311         free(ds->symbol);
1312     free (dll_symbols);
1313     dll_symbols = NULL;
1314 }
1315 */
1316
1317 static  void    do_grab_sym( void )
1318 {
1319     const IMAGE_EXPORT_DIRECTORY*exportDir;
1320     unsigned                    i, j;
1321     const DWORD*                pName;
1322     const DWORD*                pFunc;
1323     const WORD*                 pOrdl;
1324     const char*                 ptr;
1325     DWORD*                      map;
1326
1327     PE_nt_headers = get_nt_header();
1328     if (!(exportDir = get_dir(IMAGE_FILE_EXPORT_DIRECTORY))) return;
1329
1330     pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
1331     if (!pName) {printf("Can't grab functions' name table\n"); return;}
1332     pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
1333     if (!pOrdl) {printf("Can't grab functions' ordinal table\n"); return;}
1334
1335     /* dll_close(); */
1336
1337     if (!(dll_symbols = (dll_symbol *) malloc((exportDir->NumberOfFunctions + 1) *
1338                                               sizeof (dll_symbol))))
1339         fatal ("Out of memory");
1340     if (exportDir->AddressOfFunctions != exportDir->NumberOfNames || exportDir->Base > 1)
1341         globals.do_ordinals = 1;
1342
1343     /* bit map of used funcs */
1344     map = calloc(((exportDir->NumberOfFunctions + 31) & ~31) / 32, sizeof(DWORD));
1345     if (!map) fatal("no memory");
1346
1347     for (j = 0; j < exportDir->NumberOfNames; j++, pOrdl++)
1348     {
1349         map[*pOrdl / 32] |= 1 << (*pOrdl % 32);
1350         ptr = RVA(*pName++, sizeof(DWORD));
1351         if (!ptr) ptr = "cant_get_function";
1352         dll_symbols[j].symbol = strdup(ptr);
1353         dll_symbols[j].ordinal = exportDir->Base + *pOrdl;
1354         assert(dll_symbols[j].symbol);
1355     }
1356     pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
1357     if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
1358
1359     for (i = 0; i < exportDir->NumberOfFunctions; i++)
1360     {
1361         if (pFunc[i] && !(map[i / 32] & (1 << (i % 32))))
1362         {
1363             char ordinal_text[256];
1364             /* Ordinal only entry */
1365             snprintf (ordinal_text, sizeof(ordinal_text), "%s_%u",
1366                       globals.forward_dll ? globals.forward_dll : OUTPUT_UC_DLL_NAME,
1367                       exportDir->Base + i);
1368             str_toupper(ordinal_text);
1369             dll_symbols[j].symbol = strdup(ordinal_text);
1370             assert(dll_symbols[j].symbol);
1371             dll_symbols[j].ordinal = exportDir->Base + i;
1372             j++;
1373             assert(j <= exportDir->NumberOfFunctions);
1374         }
1375     }
1376     free(map);
1377
1378     if (NORMAL)
1379         printf("%u named symbols in DLL, %u total, %d unique (ordinal base = %d)\n",
1380                exportDir->NumberOfNames, exportDir->NumberOfFunctions, j, exportDir->Base);
1381
1382     qsort( dll_symbols, j, sizeof(dll_symbol), symbol_cmp );
1383
1384     dll_symbols[j].symbol = NULL;
1385
1386     dll_current_symbol = dll_symbols;
1387 }
1388
1389 /*******************************************************************
1390  *         dll_open
1391  *
1392  * Open a DLL and read in exported symbols
1393  */
1394 int dll_open (const char *dll_name)
1395 {
1396     return dump_analysis(dll_name, do_grab_sym, SIG_PE);
1397 }
1398
1399 /*******************************************************************
1400  *         dll_next_symbol
1401  *
1402  * Get next exported symbol from dll
1403  */
1404 int dll_next_symbol (parsed_symbol * sym)
1405 {
1406     if (!dll_current_symbol->symbol)
1407         return 1;
1408
1409     assert (dll_symbols);
1410
1411     sym->symbol = strdup (dll_current_symbol->symbol);
1412     sym->ordinal = dll_current_symbol->ordinal;
1413     dll_current_symbol++;
1414     return 0;
1415 }