~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/tools/winedump/pe.c

Version: ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

This page was automatically generated by the LXR engine.
Visit the LXR main site for more information.