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