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