pe.c 49.7 KB
Newer Older
1 2 3 4
/*
 *	PE dumping utility
 *
 * 	Copyright 2001 Eric Pouech
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 22 23
#include "config.h"
#include "wine/port.h"

24
#include <stdlib.h>
25
#include <stdarg.h>
26
#include <stdio.h>
27 28 29
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
30
#include <time.h>
31 32 33 34 35 36
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
37
#ifdef HAVE_SYS_MMAN_H
38
#include <sys/mman.h>
39
#endif
40 41
#include <fcntl.h>

42 43
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
44
#include "windef.h"
45
#include "winbase.h"
46 47
#include "winedump.h"

48
static const IMAGE_NT_HEADERS32*        PE_nt_headers;
49

50
const char *get_machine_str(int mach)
51 52 53 54 55 56 57 58 59 60 61
{
    switch (mach)
    {
    case IMAGE_FILE_MACHINE_UNKNOWN:	return "Unknown";
    case IMAGE_FILE_MACHINE_I860:	return "i860";
    case IMAGE_FILE_MACHINE_I386:	return "i386";
    case IMAGE_FILE_MACHINE_R3000:	return "R3000";
    case IMAGE_FILE_MACHINE_R4000:	return "R4000";
    case IMAGE_FILE_MACHINE_R10000:	return "R10000";
    case IMAGE_FILE_MACHINE_ALPHA:	return "Alpha";
    case IMAGE_FILE_MACHINE_POWERPC:	return "PowerPC";
62 63
    case IMAGE_FILE_MACHINE_AMD64:      return "AMD64";
    case IMAGE_FILE_MACHINE_IA64:       return "IA64";
64 65 66 67
    }
    return "???";
}

68
static const void*	RVA(unsigned long rva, unsigned long len)
69 70 71
{
    IMAGE_SECTION_HEADER*	sectHead;
    int				i;
72

73 74
    if (rva == 0) return NULL;

75
    sectHead = IMAGE_FIRST_SECTION(PE_nt_headers);
76
    for (i = PE_nt_headers->FileHeader.NumberOfSections - 1; i >= 0; i--)
77 78 79
    {
        if (sectHead[i].VirtualAddress <= rva &&
            rva + len <= (DWORD)sectHead[i].VirtualAddress + sectHead[i].SizeOfRawData)
80 81 82 83
        {
            /* return image import directory offset */
            return PRD(sectHead[i].PointerToRawData + rva - sectHead[i].VirtualAddress, len);
        }
84
    }
85

86
    return NULL;
87 88
}

89
static const IMAGE_NT_HEADERS32 *get_nt_header( void )
90
{
91 92 93
    const IMAGE_DOS_HEADER *dos;
    dos = PRD(0, sizeof(*dos));
    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 103 104
    dos = PRD(0, sizeof(*dos) + sizeof(fakedll_signature));

    if (dos && dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
105 106 107 108
        !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
    return FALSE;
}

109
static const void *get_dir_and_size(unsigned int idx, unsigned int *size)
110
{
111 112
    if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
    {
113
        const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
114 115 116 117 118 119 120 121 122
        if (idx >= opt->NumberOfRvaAndSizes)
            return NULL;
        if(size)
            *size = opt->DataDirectory[idx].Size;
        return RVA(opt->DataDirectory[idx].VirtualAddress,
                   opt->DataDirectory[idx].Size);
    }
    else
    {
123
        const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
124 125 126 127 128 129 130
        if (idx >= opt->NumberOfRvaAndSizes)
            return NULL;
        if(size)
            *size = opt->DataDirectory[idx].Size;
        return RVA(opt->DataDirectory[idx].VirtualAddress,
                   opt->DataDirectory[idx].Size);
    }
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 140 141
    "EXPORT",		"IMPORT",	"RESOURCE", 	"EXCEPTION",
    "SECURITY", 	"BASERELOC", 	"DEBUG", 	"ARCHITECTURE",
    "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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
{
    switch(magic) {
        case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
            return "32bit";
        case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
            return "64bit";
        case IMAGE_ROM_OPTIONAL_HDR_MAGIC:
            return "ROM";
    }
    return "???";
}

static inline void print_word(const char *title, WORD value)
{
    printf("  %-34s 0x%-4X         %u\n", title, value, value);
}

static inline void print_dword(const char *title, DWORD value)
{
165
    printf("  %-34s 0x%-8x     %u\n", title, value, value);
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
}

static inline void print_longlong(const char *title, ULONGLONG value)
{
    printf("  %-34s 0x", title);
    if(value >> 32)
        printf("%lx%08lx\n", (unsigned long)(value >> 32), (unsigned long)value);
    else
        printf("%lx\n", (unsigned long)value);
}

static inline void print_ver(const char *title, BYTE major, BYTE minor)
{
    printf("  %-34s %u.%02u\n", title, major, minor);
}

static inline void print_subsys(const char *title, WORD value)
{
    const char *str;
    switch (value)
    {
        default:
        case IMAGE_SUBSYSTEM_UNKNOWN:       str = "Unknown";        break;
        case IMAGE_SUBSYSTEM_NATIVE:        str = "Native";         break;
        case IMAGE_SUBSYSTEM_WINDOWS_GUI:   str = "Windows GUI";    break;
        case IMAGE_SUBSYSTEM_WINDOWS_CUI:   str = "Windows CUI";    break;
        case IMAGE_SUBSYSTEM_OS2_CUI:       str = "OS/2 CUI";       break;
        case IMAGE_SUBSYSTEM_POSIX_CUI:     str = "Posix CUI";      break;
    }
    printf("  %-34s 0x%X (%s)\n", title, value, str);
}

static inline void print_dllflags(const char *title, WORD value)
{
    printf("  %-34s 0x%X\n", title, value);
#define X(f,s) if (value & f) printf("    %s\n", s)
202 203 204
    X(IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE,          "DYNAMIC_BASE");
    X(IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY,       "FORCE_INTEGRITY");
    X(IMAGE_DLLCHARACTERISTICS_NX_COMPAT,             "NX_COMPAT");
205 206 207 208 209 210 211 212
    X(IMAGE_DLLCHARACTERISTICS_NO_ISOLATION,          "NO_ISOLATION");
    X(IMAGE_DLLCHARACTERISTICS_NO_SEH,                "NO_SEH");
    X(IMAGE_DLLCHARACTERISTICS_NO_BIND,               "NO_BIND");
    X(IMAGE_DLLCHARACTERISTICS_WDM_DRIVER,            "WDM_DRIVER");
    X(IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE, "TERMINAL_SERVER_AWARE");
#undef X
}

213
static inline void print_datadirectory(DWORD n, const IMAGE_DATA_DIRECTORY *directory)
214 215 216 217 218 219
{
    unsigned i;
    printf("Data Directory\n");

    for (i = 0; i < n && i < 16; i++)
    {
220
        printf("  %-12s rva: 0x%-8x  size: 0x%-8x\n",
221 222 223 224 225
               DirectoryNames[i], directory[i].VirtualAddress,
               directory[i].Size);
    }
}

226
static void dump_optional_header32(const IMAGE_OPTIONAL_HEADER32 *image_oh, UINT header_size)
227
{
228 229 230 231 232 233 234 235
    IMAGE_OPTIONAL_HEADER32 oh;
    const IMAGE_OPTIONAL_HEADER32 *optionalHeader;

    /* in case optional header is missing or partial */
    memset(&oh, 0, sizeof(oh));
    memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
    optionalHeader = &oh;

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    print_word("Magic", optionalHeader->Magic);
    print_ver("linker version",
              optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
    print_dword("size of code", optionalHeader->SizeOfCode);
    print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
    print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
    print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
    print_dword("base of code", optionalHeader->BaseOfCode);
    print_dword("base of data", optionalHeader->BaseOfData);
    print_dword("image base", optionalHeader->ImageBase);
    print_dword("section align", optionalHeader->SectionAlignment);
    print_dword("file align", optionalHeader->FileAlignment);
    print_ver("required OS version",
              optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
    print_ver("image version",
              optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
    print_ver("subsystem version",
              optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
    print_dword("Win32 Version", optionalHeader->Win32VersionValue);
    print_dword("size of image", optionalHeader->SizeOfImage);
    print_dword("size of headers", optionalHeader->SizeOfHeaders);
    print_dword("checksum", optionalHeader->CheckSum);
    print_subsys("Subsystem", optionalHeader->Subsystem);
    print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
    print_dword("stack reserve size", optionalHeader->SizeOfStackReserve);
    print_dword("stack commit size", optionalHeader->SizeOfStackCommit);
    print_dword("heap reserve size", optionalHeader->SizeOfHeapReserve);
    print_dword("heap commit size", optionalHeader->SizeOfHeapCommit);
    print_dword("loader flags", optionalHeader->LoaderFlags);
    print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
    printf("\n");
    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 274 275 276 277 278 279 280
    IMAGE_OPTIONAL_HEADER64 oh;
    const IMAGE_OPTIONAL_HEADER64 *optionalHeader;

    /* in case optional header is missing or partial */
    memset(&oh, 0, sizeof(oh));
    memcpy(&oh, image_oh, min(header_size, sizeof(oh)));
    optionalHeader = &oh;

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    print_word("Magic", optionalHeader->Magic);
    print_ver("linker version",
              optionalHeader->MajorLinkerVersion, optionalHeader->MinorLinkerVersion);
    print_dword("size of code", optionalHeader->SizeOfCode);
    print_dword("size of initialized data", optionalHeader->SizeOfInitializedData);
    print_dword("size of uninitialized data", optionalHeader->SizeOfUninitializedData);
    print_dword("entrypoint RVA", optionalHeader->AddressOfEntryPoint);
    print_dword("base of code", optionalHeader->BaseOfCode);
    print_longlong("image base", optionalHeader->ImageBase);
    print_dword("section align", optionalHeader->SectionAlignment);
    print_dword("file align", optionalHeader->FileAlignment);
    print_ver("required OS version",
              optionalHeader->MajorOperatingSystemVersion, optionalHeader->MinorOperatingSystemVersion);
    print_ver("image version",
              optionalHeader->MajorImageVersion, optionalHeader->MinorImageVersion);
    print_ver("subsystem version",
              optionalHeader->MajorSubsystemVersion, optionalHeader->MinorSubsystemVersion);
    print_dword("Win32 Version", optionalHeader->Win32VersionValue);
    print_dword("size of image", optionalHeader->SizeOfImage);
    print_dword("size of headers", optionalHeader->SizeOfHeaders);
    print_dword("checksum", optionalHeader->CheckSum);
    print_subsys("Subsystem", optionalHeader->Subsystem);
    print_dllflags("DLL characteristics:", optionalHeader->DllCharacteristics);
    print_longlong("stack reserve size", optionalHeader->SizeOfStackReserve);
    print_longlong("stack commit size", optionalHeader->SizeOfStackCommit);
    print_longlong("heap reserve size", optionalHeader->SizeOfHeapReserve);
    print_longlong("heap commit size", optionalHeader->SizeOfHeapCommit);
    print_dword("loader flags", optionalHeader->LoaderFlags);
    print_dword("RVAs & sizes", optionalHeader->NumberOfRvaAndSizes);
    printf("\n");
    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 318 319 320 321 322 323 324 325 326 327 328 329 330
    printf("Optional Header (%s)\n", get_magic_type(optionalHeader->Magic));

    switch(optionalHeader->Magic) {
        case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
            dump_optional_header32(optionalHeader, header_size);
            break;
        case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
            dump_optional_header64((const IMAGE_OPTIONAL_HEADER64 *)optionalHeader, header_size);
            break;
        default:
            printf("  Unknown optional header magic: 0x%-4X\n", optionalHeader->Magic);
            break;
    }
}
331

332 333
void dump_file_header(const IMAGE_FILE_HEADER *fileHeader)
{
334
    printf("File Header\n");
335 336

    printf("  Machine:                      %04X (%s)\n",
337 338
	   fileHeader->Machine, get_machine_str(fileHeader->Machine));
    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 343
    printf("  PointerToSymbolTable:         %08X\n", fileHeader->PointerToSymbolTable);
    printf("  NumberOfSymbols:              %08X\n", fileHeader->NumberOfSymbols);
344 345 346 347 348 349 350
    printf("  SizeOfOptionalHeader:         %04X\n", fileHeader->SizeOfOptionalHeader);
    printf("  Characteristics:              %04X\n", fileHeader->Characteristics);
#define	X(f,s)	if (fileHeader->Characteristics & f) printf("    %s\n", s)
    X(IMAGE_FILE_RELOCS_STRIPPED, 	"RELOCS_STRIPPED");
    X(IMAGE_FILE_EXECUTABLE_IMAGE, 	"EXECUTABLE_IMAGE");
    X(IMAGE_FILE_LINE_NUMS_STRIPPED, 	"LINE_NUMS_STRIPPED");
    X(IMAGE_FILE_LOCAL_SYMS_STRIPPED, 	"LOCAL_SYMS_STRIPPED");
351 352
    X(IMAGE_FILE_AGGRESIVE_WS_TRIM, 	"AGGRESIVE_WS_TRIM");
    X(IMAGE_FILE_LARGE_ADDRESS_AWARE, 	"LARGE_ADDRESS_AWARE");
353 354 355 356
    X(IMAGE_FILE_16BIT_MACHINE, 	"16BIT_MACHINE");
    X(IMAGE_FILE_BYTES_REVERSED_LO, 	"BYTES_REVERSED_LO");
    X(IMAGE_FILE_32BIT_MACHINE, 	"32BIT_MACHINE");
    X(IMAGE_FILE_DEBUG_STRIPPED, 	"DEBUG_STRIPPED");
357 358
    X(IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, 	"REMOVABLE_RUN_FROM_SWAP");
    X(IMAGE_FILE_NET_RUN_FROM_SWAP, 	"NET_RUN_FROM_SWAP");
359 360
    X(IMAGE_FILE_SYSTEM, 		"SYSTEM");
    X(IMAGE_FILE_DLL, 			"DLL");
361
    X(IMAGE_FILE_UP_SYSTEM_ONLY, 	"UP_SYSTEM_ONLY");
362 363 364
    X(IMAGE_FILE_BYTES_REVERSED_HI, 	"BYTES_REVERSED_HI");
#undef X
    printf("\n");
365
}
366

367 368 369 370
static	void	dump_pe_header(void)
{
    dump_file_header(&PE_nt_headers->FileHeader);
    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 376 377
	printf("  %-8.8s   VirtSize: 0x%08x  VirtAddr:  0x%08x\n",
               sectHead->Name, sectHead->Misc.VirtualSize, sectHead->VirtualAddress);
	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 385
	printf("    ");
#define X(b,s)	if (sectHead->Characteristics & b) printf("  " s)
386 387 388 389 390 391
/* #define IMAGE_SCN_TYPE_REG			0x00000000 - Reserved */
/* #define IMAGE_SCN_TYPE_DSECT			0x00000001 - Reserved */
/* #define IMAGE_SCN_TYPE_NOLOAD		0x00000002 - Reserved */
/* #define IMAGE_SCN_TYPE_GROUP			0x00000004 - Reserved */
/* #define IMAGE_SCN_TYPE_NO_PAD		0x00000008 - Reserved */
/* #define IMAGE_SCN_TYPE_COPY			0x00000010 - Reserved */
392

393 394 395
	X(IMAGE_SCN_CNT_CODE, 			"CODE");
	X(IMAGE_SCN_CNT_INITIALIZED_DATA, 	"INITIALIZED_DATA");
	X(IMAGE_SCN_CNT_UNINITIALIZED_DATA, 	"UNINITIALIZED_DATA");
396

397 398 399 400 401
	X(IMAGE_SCN_LNK_OTHER, 			"LNK_OTHER");
	X(IMAGE_SCN_LNK_INFO, 			"LNK_INFO");
/* #define	IMAGE_SCN_TYPE_OVER		0x00000400 - Reserved */
	X(IMAGE_SCN_LNK_REMOVE, 		"LNK_REMOVE");
	X(IMAGE_SCN_LNK_COMDAT, 		"LNK_COMDAT");
402

403 404 405
/* 						0x00002000 - Reserved */
/* #define IMAGE_SCN_MEM_PROTECTED 		0x00004000 - Obsolete */
	X(IMAGE_SCN_MEM_FARDATA, 		"MEM_FARDATA");
406

407 408 409 410 411
/* #define IMAGE_SCN_MEM_SYSHEAP		0x00010000 - Obsolete */
	X(IMAGE_SCN_MEM_PURGEABLE, 		"MEM_PURGEABLE");
	X(IMAGE_SCN_MEM_16BIT, 			"MEM_16BIT");
	X(IMAGE_SCN_MEM_LOCKED, 		"MEM_LOCKED");
	X(IMAGE_SCN_MEM_PRELOAD, 		"MEM_PRELOAD");
412

413 414
        switch (sectHead->Characteristics & IMAGE_SCN_ALIGN_MASK)
        {
415
#define X2(b,s)	case b: printf("  " s); break
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        X2(IMAGE_SCN_ALIGN_1BYTES, 		"ALIGN_1BYTES");
        X2(IMAGE_SCN_ALIGN_2BYTES, 		"ALIGN_2BYTES");
        X2(IMAGE_SCN_ALIGN_4BYTES, 		"ALIGN_4BYTES");
        X2(IMAGE_SCN_ALIGN_8BYTES, 		"ALIGN_8BYTES");
        X2(IMAGE_SCN_ALIGN_16BYTES, 		"ALIGN_16BYTES");
        X2(IMAGE_SCN_ALIGN_32BYTES, 		"ALIGN_32BYTES");
        X2(IMAGE_SCN_ALIGN_64BYTES, 		"ALIGN_64BYTES");
        X2(IMAGE_SCN_ALIGN_128BYTES, 		"ALIGN_128BYTES");
        X2(IMAGE_SCN_ALIGN_256BYTES, 		"ALIGN_256BYTES");
        X2(IMAGE_SCN_ALIGN_512BYTES, 		"ALIGN_512BYTES");
        X2(IMAGE_SCN_ALIGN_1024BYTES, 		"ALIGN_1024BYTES");
        X2(IMAGE_SCN_ALIGN_2048BYTES, 		"ALIGN_2048BYTES");
        X2(IMAGE_SCN_ALIGN_4096BYTES, 		"ALIGN_4096BYTES");
        X2(IMAGE_SCN_ALIGN_8192BYTES, 		"ALIGN_8192BYTES");
#undef X2
        }
432

433
	X(IMAGE_SCN_LNK_NRELOC_OVFL, 		"LNK_NRELOC_OVFL");
434

435 436 437 438 439 440 441 442 443
	X(IMAGE_SCN_MEM_DISCARDABLE, 		"MEM_DISCARDABLE");
	X(IMAGE_SCN_MEM_NOT_CACHED, 		"MEM_NOT_CACHED");
	X(IMAGE_SCN_MEM_NOT_PAGED, 		"MEM_NOT_PAGED");
	X(IMAGE_SCN_MEM_SHARED, 		"MEM_SHARED");
	X(IMAGE_SCN_MEM_EXECUTE, 		"MEM_EXECUTE");
	X(IMAGE_SCN_MEM_READ, 			"MEM_READ");
	X(IMAGE_SCN_MEM_WRITE, 			"MEM_WRITE");
#undef X
	printf("\n\n");
444 445 446 447 448 449 450 451 452 453 454
}

static void dump_sections(const void *base, const void* addr, unsigned num_sect)
{
    const IMAGE_SECTION_HEADER*	sectHead = addr;
    unsigned			i;

    printf("Section Table\n");
    for (i = 0; i < num_sect; i++, sectHead++)
    {
        dump_section(sectHead);
455 456 457 458 459 460

        if (globals.do_dump_rawdata)
        {
            dump_data((const unsigned char *)base + sectHead->PointerToRawData, sectHead->SizeOfRawData, "    " );
            printf("\n");
        }
461 462 463 464 465
    }
}

static	void	dump_dir_exported_functions(void)
{
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 470 471 472
    const DWORD*		pFunc;
    const DWORD*		pName;
    const WORD* 		pOrdl;
    DWORD*		        map;
473
    parsed_symbol		symbol;
474

475
    if (!exportDir) return;
476

477 478
    printf("Exports table:\n");
    printf("\n");
479
    printf("  Name:            %s\n", (const char*)RVA(exportDir->Name, sizeof(DWORD)));
480 481
    printf("  Characteristics: %08x\n", exportDir->Characteristics);
    printf("  TimeDateStamp:   %08X %s\n",
482 483
	   exportDir->TimeDateStamp, get_time_str(exportDir->TimeDateStamp));
    printf("  Version:         %u.%02u\n", exportDir->MajorVersion, exportDir->MinorVersion);
484 485 486 487 488 489
    printf("  Ordinal base:    %u\n", exportDir->Base);
    printf("  # of functions:  %u\n", exportDir->NumberOfFunctions);
    printf("  # of Names:      %u\n", exportDir->NumberOfNames);
    printf("Addresses of functions: %08X\n", exportDir->AddressOfFunctions);
    printf("Addresses of name ordinals: %08X\n", exportDir->AddressOfNameOrdinals);
    printf("Addresses of names: %08X\n", exportDir->AddressOfNames);
490 491
    printf("\n");
    printf("  Entry Pt  Ordn  Name\n");
492

493 494 495 496 497 498
    pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
    if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
    pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
    if (!pName) {printf("Can't grab functions' name table\n"); return;}
    pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
    if (!pOrdl) {printf("Can't grab functions' ordinal table\n"); return;}
499

500 501 502
    /* bit map of used funcs */
    map = calloc(((exportDir->NumberOfFunctions + 31) & ~31) / 32, sizeof(DWORD));
    if (!map) fatal("no memory");
503

504
    for (i = 0; i < exportDir->NumberOfNames; i++, pName++, pOrdl++)
505
    {
506
	const char*	name;
507

508
	map[*pOrdl / 32] |= 1 << (*pOrdl % 32);
509

510
	name = (const char*)RVA(*pName, sizeof(DWORD));
511 512
	if (name && globals.do_demangle)
	{
513
            printf("  %08X  %4u ", pFunc[*pOrdl], exportDir->Base + *pOrdl);
514 515 516 517 518 519

	    symbol_init(&symbol, name);
	    if (symbol_demangle(&symbol) == -1)
		printf(name);
	    else if (symbol.flags & SYM_DATA)
		printf(symbol.arg_text[0]);
520 521
	    else
		output_prototype(stdout, &symbol);
522
	    symbol_clear(&symbol);
523 524 525
	}
	else
	{
526
            printf("  %08X  %4u %s", pFunc[*pOrdl], exportDir->Base + *pOrdl, name);
527
	}
528
        /* check for forwarded function */
529 530 531
        if ((const char *)RVA(pFunc[*pOrdl],sizeof(void*)) >= (const char *)exportDir &&
            (const char *)RVA(pFunc[*pOrdl],sizeof(void*)) < (const char *)exportDir + size)
            printf( " (-> %s)", (const char *)RVA(pFunc[*pOrdl],1));
532
        printf("\n");
533 534
    }
    pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
535 536 537 538 539 540
    if (!pFunc)
    {
        printf("Can't grab functions' address table\n");
        free(map);
        return;
    }
541 542
    for (i = 0; i < exportDir->NumberOfFunctions; i++)
    {
543
	if (pFunc[i] && !(map[i / 32] & (1 << (i % 32))))
544
	{
545
            printf("  %08X  %4u <by ordinal>\n", pFunc[i], exportDir->Base + i);
546 547 548 549 550 551
	}
    }
    free(map);
    printf("\n");
}

552
static void dump_image_thunk_data64(const IMAGE_THUNK_DATA64 *il)
553 554
{
    /* FIXME: This does not properly handle large images */
555
    const IMAGE_IMPORT_BY_NAME* iibn;
556 557 558
    for (; il->u1.Ordinal; il++)
    {
        if (IMAGE_SNAP_BY_ORDINAL64(il->u1.Ordinal))
559
            printf("  %4u  <by ordinal>\n", (DWORD)IMAGE_ORDINAL64(il->u1.Ordinal));
560 561 562
        else
        {
            iibn = RVA((DWORD)il->u1.AddressOfData, sizeof(DWORD));
563
            if (!iibn)
564 565
                printf("Can't grab import by name info, skipping to next ordinal\n");
            else
566
                printf("  %4u  %s %x\n", iibn->Hint, iibn->Name, (DWORD)il->u1.AddressOfData);
567 568 569 570
        }
    }
}

571
static void dump_image_thunk_data32(const IMAGE_THUNK_DATA32 *il, int offset)
572
{
573
    const IMAGE_IMPORT_BY_NAME* iibn;
574 575 576
    for (; il->u1.Ordinal; il++)
    {
        if (IMAGE_SNAP_BY_ORDINAL32(il->u1.Ordinal))
577
            printf("  %4u  <by ordinal>\n", IMAGE_ORDINAL32(il->u1.Ordinal));
578 579
        else
        {
580
            iibn = RVA((DWORD)il->u1.AddressOfData - offset, sizeof(DWORD));
581
            if (!iibn)
582 583
                printf("Can't grab import by name info, skipping to next ordinal\n");
            else
584
                printf("  %4u  %s %x\n", iibn->Hint, iibn->Name, (DWORD)il->u1.AddressOfData);
585 586 587 588
        }
    }
}

589 590
static	void	dump_dir_imported_functions(void)
{
591
    const IMAGE_IMPORT_DESCRIPTOR	*importDesc = get_dir(IMAGE_FILE_IMPORT_DIRECTORY);
592
    DWORD directorySize;
593

594
    if (!importDesc)	return;
595 596
    if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
    {
597
        const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
598 599 600 601
        directorySize = opt->DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY].Size;
    }
    else
    {
602
        const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
603 604
        directorySize = opt->DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY].Size;
    }
605

606
    printf("Import Table size: %08x\n", directorySize);/* FIXME */
607

608
    for (;;)
609
    {
610
	const IMAGE_THUNK_DATA32*	il;
611

612 613
        if (!importDesc->Name || !importDesc->FirstThunk) break;

614
	printf("  offset %08lx %s\n", Offset(importDesc), (const char*)RVA(importDesc->Name, sizeof(DWORD)));
615
	printf("  Hint/Name Table: %08X\n", (DWORD)importDesc->u.OriginalFirstThunk);
616
	printf("  TimeDateStamp:   %08X (%s)\n",
617
	       importDesc->TimeDateStamp, get_time_str(importDesc->TimeDateStamp));
618 619
	printf("  ForwarderChain:  %08X\n", importDesc->ForwarderChain);
	printf("  First thunk RVA: %08X\n", (DWORD)importDesc->FirstThunk);
620

621
	printf("  Ordn  Name\n");
622 623 624

	il = (importDesc->u.OriginalFirstThunk != 0) ?
	    RVA((DWORD)importDesc->u.OriginalFirstThunk, sizeof(DWORD)) :
625
	    RVA((DWORD)importDesc->FirstThunk, sizeof(DWORD));
626

627 628
	if (!il)
            printf("Can't grab thunk data, going to next imported DLL\n");
629
        else
630 631
        {
            if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
632
                dump_image_thunk_data64((const IMAGE_THUNK_DATA64*)il);
633
            else
634
                dump_image_thunk_data32(il, 0);
635 636
            printf("\n");
        }
637 638 639 640 641
	importDesc++;
    }
    printf("\n");
}

642 643
static void dump_dir_delay_imported_functions(void)
{
644
    const struct ImgDelayDescr
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
    {
        DWORD grAttrs;
        DWORD szName;
        DWORD phmod;
        DWORD pIAT;
        DWORD pINT;
        DWORD pBoundIAT;
        DWORD pUnloadIAT;
        DWORD dwTimeStamp;
    } *importDesc = get_dir(IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT);
    DWORD directorySize;

    if (!importDesc) return;
    if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
    {
660
        const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64 *)&PE_nt_headers->OptionalHeader;
661 662 663 664
        directorySize = opt->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
    }
    else
    {
665
        const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32 *)&PE_nt_headers->OptionalHeader;
666 667 668
        directorySize = opt->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
    }

669
    printf("Delay Import Table size: %08x\n", directorySize); /* FIXME */
670

671
    for (;;)
672
    {
673
        const IMAGE_THUNK_DATA32*       il;
674
        int                             offset = (importDesc->grAttrs & 1) ? 0 : PE_nt_headers->OptionalHeader.ImageBase;
675

676 677
        if (!importDesc->szName || !importDesc->pIAT || !importDesc->pINT) break;

678
        printf("  grAttrs %08x offset %08lx %s\n", importDesc->grAttrs, Offset(importDesc),
679
               (const char *)RVA(importDesc->szName - offset, sizeof(DWORD)));
680
        printf("  Hint/Name Table: %08x\n", importDesc->pINT);
681
        printf("  TimeDateStamp:   %08X (%s)\n",
682 683 684 685
               importDesc->dwTimeStamp, get_time_str(importDesc->dwTimeStamp));

        printf("  Ordn  Name\n");

686
        il = (const IMAGE_THUNK_DATA32 *)RVA(importDesc->pINT - offset, sizeof(DWORD));
687 688 689 690

        if (!il)
            printf("Can't grab thunk data, going to next imported DLL\n");
        else
691 692
        {
            if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
693
                dump_image_thunk_data64((const IMAGE_THUNK_DATA64 *)il);
694
            else
695
                dump_image_thunk_data32(il, offset);
696 697
            printf("\n");
        }
698 699 700 701 702
        importDesc++;
    }
    printf("\n");
}

703
static	void	dump_dir_debug_dir(const IMAGE_DEBUG_DIRECTORY* idd, int idx)
704 705
{
    const	char*	str;
706

707
    printf("Directory %02u\n", idx + 1);
708 709
    printf("  Characteristics:   %08X\n", idd->Characteristics);
    printf("  TimeDateStamp:     %08X %s\n",
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
	   idd->TimeDateStamp, get_time_str(idd->TimeDateStamp));
    printf("  Version            %u.%02u\n", idd->MajorVersion, idd->MinorVersion);
    switch (idd->Type)
    {
    default:
    case IMAGE_DEBUG_TYPE_UNKNOWN:	str = "UNKNOWN"; 	break;
    case IMAGE_DEBUG_TYPE_COFF:		str = "COFF"; 		break;
    case IMAGE_DEBUG_TYPE_CODEVIEW:	str = "CODEVIEW"; 	break;
    case IMAGE_DEBUG_TYPE_FPO:		str = "FPO"; 		break;
    case IMAGE_DEBUG_TYPE_MISC:		str = "MISC"; 		break;
    case IMAGE_DEBUG_TYPE_EXCEPTION:	str = "EXCEPTION"; 	break;
    case IMAGE_DEBUG_TYPE_FIXUP:	str = "FIXUP"; 		break;
    case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:	str = "OMAP_TO_SRC"; 	break;
    case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:str = "OMAP_FROM_SRC"; 	break;
    case IMAGE_DEBUG_TYPE_BORLAND:	str = "BORLAND"; 	break;
    case IMAGE_DEBUG_TYPE_RESERVED10:	str = "RESERVED10"; 	break;
    }
727 728 729 730
    printf("  Type:              %u (%s)\n", idd->Type, str);
    printf("  SizeOfData:        %u\n", idd->SizeOfData);
    printf("  AddressOfRawData:  %08X\n", idd->AddressOfRawData);
    printf("  PointerToRawData:  %08X\n", idd->PointerToRawData);
731

732 733
    switch (idd->Type)
    {
734
    case IMAGE_DEBUG_TYPE_UNKNOWN:
735
	break;
736
    case IMAGE_DEBUG_TYPE_COFF:
737
	dump_coff(idd->PointerToRawData, idd->SizeOfData, 
738
                  (const char*)PE_nt_headers + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader);
739 740 741 742
	break;
    case IMAGE_DEBUG_TYPE_CODEVIEW:
	dump_codeview(idd->PointerToRawData, idd->SizeOfData);
	break;
743
    case IMAGE_DEBUG_TYPE_FPO:
744
	dump_frame_pointer_omission(idd->PointerToRawData, idd->SizeOfData);
745 746 747
	break;
    case IMAGE_DEBUG_TYPE_MISC:
    {
748
	const IMAGE_DEBUG_MISC* misc = PRD(idd->PointerToRawData, idd->SizeOfData);
749
	if (!misc) {printf("Can't get misc debug information\n"); break;}
750
	printf("    DataType:          %u (%s)\n",
751
	       misc->DataType,
752
	       (misc->DataType == IMAGE_DEBUG_MISC_EXENAME) ? "Exe name" : "Unknown");
753
	printf("    Length:            %u\n", misc->Length);
754 755 756 757 758 759
	printf("    Unicode:           %s\n", misc->Unicode ? "Yes" : "No");
	printf("    Data:              %s\n", misc->Data);
    }
    break;
    case IMAGE_DEBUG_TYPE_EXCEPTION:
	break;
760
    case IMAGE_DEBUG_TYPE_FIXUP:
761 762 763 764 765
	break;
    case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:
	break;
    case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:
	break;
766
    case IMAGE_DEBUG_TYPE_BORLAND:
767 768 769 770 771 772 773 774 775
	break;
    case IMAGE_DEBUG_TYPE_RESERVED10:
	break;
    }
    printf("\n");
}

static void	dump_dir_debug(void)
{
776
    const IMAGE_DEBUG_DIRECTORY*debugDir = get_dir(IMAGE_FILE_DEBUG_DIRECTORY);
777
    unsigned			nb_dbg, i;
778

779
    if (!debugDir) return;
780
    nb_dbg = PE_nt_headers->OptionalHeader.DataDirectory[IMAGE_FILE_DEBUG_DIRECTORY].Size /
781 782
	sizeof(*debugDir);
    if (!nb_dbg) return;
783

784
    printf("Debug Table (%u directories)\n", nb_dbg);
785

786 787 788 789 790 791 792 793
    for (i = 0; i < nb_dbg; i++)
    {
	dump_dir_debug_dir(debugDir, i);
	debugDir++;
    }
    printf("\n");
}

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
static inline void print_clrflags(const char *title, WORD value)
{
    printf("  %-34s 0x%X\n", title, value);
#define X(f,s) if (value & f) printf("    %s\n", s)
    X(COMIMAGE_FLAGS_ILONLY,           "ILONLY");
    X(COMIMAGE_FLAGS_32BITREQUIRED,    "32BITREQUIRED");
    X(COMIMAGE_FLAGS_IL_LIBRARY,       "IL_LIBRARY");
    X(COMIMAGE_FLAGS_STRONGNAMESIGNED, "STRONGNAMESIGNED");
    X(COMIMAGE_FLAGS_TRACKDEBUGDATA,   "TRACKDEBUGDATA");
#undef X
}

static inline void print_clrdirectory(const char *title, const IMAGE_DATA_DIRECTORY *dir)
{
    printf("  %-23s rva: 0x%-8x  size: 0x%-8x\n", title, dir->VirtualAddress, dir->Size);
}

static void dump_dir_clr_header(void)
{
    unsigned int size = 0;
    const IMAGE_COR20_HEADER *dir = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &size);

    if (!dir) return;

    printf( "CLR Header\n" );
    print_dword( "Header Size", dir->cb );
    print_ver( "Required runtime version", dir->MajorRuntimeVersion, dir->MinorRuntimeVersion );
    print_clrflags( "Flags", dir->Flags );
    print_dword( "EntryPointToken", dir->EntryPointToken );
    printf("\n");
    printf( "CLR Data Directory\n" );
    print_clrdirectory( "MetaData", &dir->MetaData );
    print_clrdirectory( "Resources", &dir->Resources );
    print_clrdirectory( "StrongNameSignature", &dir->StrongNameSignature );
    print_clrdirectory( "CodeManagerTable", &dir->CodeManagerTable );
    print_clrdirectory( "VTableFixups", &dir->VTableFixups );
    print_clrdirectory( "ExportAddressTableJumps", &dir->ExportAddressTableJumps );
    print_clrdirectory( "ManagedNativeHeader", &dir->ManagedNativeHeader );
    printf("\n");
}

835 836
static void dump_dir_tls(void)
{
837
    IMAGE_TLS_DIRECTORY64 dir;
838
    const DWORD *callbacks;
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
    const IMAGE_TLS_DIRECTORY32 *pdir = get_dir(IMAGE_FILE_THREAD_LOCAL_STORAGE);

    if (!pdir) return;

    if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
        memcpy(&dir, pdir, sizeof(dir));
    else
    {
        dir.StartAddressOfRawData = pdir->StartAddressOfRawData;
        dir.EndAddressOfRawData = pdir->EndAddressOfRawData;
        dir.AddressOfIndex = pdir->AddressOfIndex;
        dir.AddressOfCallBacks = pdir->AddressOfCallBacks;
        dir.SizeOfZeroFill = pdir->SizeOfZeroFill;
        dir.Characteristics = pdir->Characteristics;
    }
854

855
    /* FIXME: This does not properly handle large images */
856
    printf( "Thread Local Storage\n" );
857
    printf( "  Raw data        %08x-%08x (data size %x zero fill size %x)\n",
858 859 860
            (DWORD)dir.StartAddressOfRawData, (DWORD)dir.EndAddressOfRawData,
            (DWORD)(dir.EndAddressOfRawData - dir.StartAddressOfRawData),
            (DWORD)dir.SizeOfZeroFill );
861 862 863
    printf( "  Index address   %08x\n", (DWORD)dir.AddressOfIndex );
    printf( "  Characteristics %08x\n", dir.Characteristics );
    printf( "  Callbacks       %08x -> {", (DWORD)dir.AddressOfCallBacks );
864
    if (dir.AddressOfCallBacks)
865
    {
866
        DWORD   addr = (DWORD)dir.AddressOfCallBacks - PE_nt_headers->OptionalHeader.ImageBase;
867 868
        while ((callbacks = RVA(addr, sizeof(DWORD))) && *callbacks)
        {
869
            printf( " %08x", *callbacks );
870 871
            addr += sizeof(DWORD);
        }
872 873 874 875
    }
    printf(" }\n\n");
}

876 877 878 879 880 881 882 883 884 885 886
enum FileSig get_kind_dbg(void)
{
    const WORD*                pw;

    pw = PRD(0, sizeof(WORD));
    if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}

    if (*pw == 0x4944 /* "DI" */) return SIG_DBG;
    return SIG_UNKNOWN;
}

887
void	dbg_dump(void)
888
{
889 890 891 892
    const IMAGE_SEPARATE_DEBUG_HEADER*  separateDebugHead;
    unsigned			        nb_dbg;
    unsigned			        i;
    const IMAGE_DEBUG_DIRECTORY*	debugDir;
893

894
    separateDebugHead = PRD(0, sizeof(separateDebugHead));
895
    if (!separateDebugHead) {printf("Can't grab the separate header, aborting\n"); return;}
896 897

    printf ("Signature:          %.2s (0x%4X)\n",
898
	    (const char*)&separateDebugHead->Signature, separateDebugHead->Signature);
899
    printf ("Flags:              0x%04X\n", separateDebugHead->Flags);
900
    printf ("Machine:            0x%04X (%s)\n",
901 902
	    separateDebugHead->Machine, get_machine_str(separateDebugHead->Machine));
    printf ("Characteristics:    0x%04X\n", separateDebugHead->Characteristics);
903
    printf ("TimeDateStamp:      0x%08X (%s)\n",
904
	    separateDebugHead->TimeDateStamp, get_time_str(separateDebugHead->TimeDateStamp));
905 906 907 908 909 910
    printf ("CheckSum:           0x%08X\n", separateDebugHead->CheckSum);
    printf ("ImageBase:          0x%08X\n", separateDebugHead->ImageBase);
    printf ("SizeOfImage:        0x%08X\n", separateDebugHead->SizeOfImage);
    printf ("NumberOfSections:   0x%08X\n", separateDebugHead->NumberOfSections);
    printf ("ExportedNamesSize:  0x%08X\n", separateDebugHead->ExportedNamesSize);
    printf ("DebugDirectorySize: 0x%08X\n", separateDebugHead->DebugDirectorySize);
911 912

    if (!PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER),
913 914
	     separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER)))
    {printf("Can't get the sections, aborting\n"); return;}
915

916
    dump_sections(separateDebugHead, separateDebugHead + 1, separateDebugHead->NumberOfSections);
917

918
    nb_dbg = separateDebugHead->DebugDirectorySize / sizeof(IMAGE_DEBUG_DIRECTORY);
919
    debugDir = PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER) +
920 921 922 923
		   separateDebugHead->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
		   separateDebugHead->ExportedNamesSize,
		   nb_dbg * sizeof(IMAGE_DEBUG_DIRECTORY));
    if (!debugDir) {printf("Couldn't get the debug directory info, aborting\n");return;}
924

925
    printf("Debug Table (%u directories)\n", nb_dbg);
926

927 928 929 930 931 932 933
    for (i = 0; i < nb_dbg; i++)
    {
	dump_dir_debug_dir(debugDir, i);
	debugDir++;
    }
}

934
static const char *get_resource_type( unsigned int id )
935
{
936
    static const char * const types[] =
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
    {
        NULL,
        "CURSOR",
        "BITMAP",
        "ICON",
        "MENU",
        "DIALOG",
        "STRING",
        "FONTDIR",
        "FONT",
        "ACCELERATOR",
        "RCDATA",
        "MESSAGETABLE",
        "GROUP_CURSOR",
        NULL,
        "GROUP_ICON",
        NULL,
        "VERSION",
        "DLGINCLUDE",
        NULL,
        "PLUGPLAY",
        "VXD",
        "ANICURSOR",
        "ANIICON",
        "HTML"
    };

964
    if ((size_t)id < sizeof(types)/sizeof(types[0])) return types[id];
965 966 967
    return NULL;
}

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
/* dump an ASCII string with proper escaping */
static int dump_strA( const unsigned char *str, size_t len )
{
    static const char escapes[32] = ".......abtnvfr.............e....";
    char buffer[256];
    char *pos = buffer;
    int count = 0;

    for (; len; str++, len--)
    {
        if (pos > buffer + sizeof(buffer) - 8)
        {
            fwrite( buffer, pos - buffer, 1, stdout );
            count += pos - buffer;
            pos = buffer;
        }
        if (*str > 127)  /* hex escape */
        {
            pos += sprintf( pos, "\\x%02x", *str );
            continue;
        }
        if (*str < 32)  /* octal or C escape */
        {
            if (!*str && len == 1) continue;  /* do not output terminating NULL */
            if (escapes[*str] != '.')
                pos += sprintf( pos, "\\%c", escapes[*str] );
            else if (len > 1 && str[1] >= '0' && str[1] <= '7')
                pos += sprintf( pos, "\\%03o", *str );
            else
                pos += sprintf( pos, "\\%o", *str );
            continue;
        }
        if (*str == '\\') *pos++ = '\\';
        *pos++ = *str;
    }
    fwrite( buffer, pos - buffer, 1, stdout );
    count += pos - buffer;
    return count;
}

1008
/* dump a Unicode string with proper escaping */
1009
static int dump_strW( const WCHAR *str, size_t len )
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
{
    static const char escapes[32] = ".......abtnvfr.............e....";
    char buffer[256];
    char *pos = buffer;
    int count = 0;

    for (; len; str++, len--)
    {
        if (pos > buffer + sizeof(buffer) - 8)
        {
            fwrite( buffer, pos - buffer, 1, stdout );
            count += pos - buffer;
            pos = buffer;
        }
        if (*str > 127)  /* hex escape */
        {
            if (len > 1 && str[1] < 128 && isxdigit((char)str[1]))
                pos += sprintf( pos, "\\x%04x", *str );
            else
                pos += sprintf( pos, "\\x%x", *str );
            continue;
        }
        if (*str < 32)  /* octal or C escape */
        {
            if (!*str && len == 1) continue;  /* do not output terminating NULL */
            if (escapes[*str] != '.')
                pos += sprintf( pos, "\\%c", escapes[*str] );
            else if (len > 1 && str[1] >= '0' && str[1] <= '7')
                pos += sprintf( pos, "\\%03o", *str );
            else
                pos += sprintf( pos, "\\%o", *str );
            continue;
        }
        if (*str == '\\') *pos++ = '\\';
        *pos++ = *str;
    }
    fwrite( buffer, pos - buffer, 1, stdout );
    count += pos - buffer;
    return count;
}

/* dump data for a STRING resource */
1052
static void dump_string_data( const WCHAR *ptr, unsigned int size, unsigned int id, const char *prefix )
1053 1054 1055 1056 1057
{
    int i;

    for (i = 0; i < 16 && size; i++)
    {
1058
        unsigned len = *ptr++;
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076

        if (len >= size)
        {
            len = size;
            size = 0;
        }
        else size -= len + 1;

        if (len)
        {
            printf( "%s%04x \"", prefix, (id - 1) * 16 + i );
            dump_strW( ptr, len );
            printf( "\"\n" );
            ptr += len;
        }
    }
}

1077 1078 1079 1080 1081
/* dump data for a MESSAGETABLE resource */
static void dump_msgtable_data( const void *ptr, unsigned int size, unsigned int id, const char *prefix )
{
    const MESSAGE_RESOURCE_DATA *data = ptr;
    const MESSAGE_RESOURCE_BLOCK *block = data->Blocks;
1082
    unsigned i, j;
1083 1084 1085 1086 1087

    for (i = 0; i < data->NumberOfBlocks; i++, block++)
    {
        const MESSAGE_RESOURCE_ENTRY *entry;

1088
        entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)data + block->OffsetToEntries);
1089 1090 1091 1092
        for (j = block->LowId; j <= block->HighId; j++)
        {
            if (entry->Flags & MESSAGE_RESOURCE_UNICODE)
            {
1093
                const WCHAR *str = (const WCHAR *)entry->Text;
1094 1095 1096 1097 1098 1099
                printf( "%s%08x L\"", prefix, j );
                dump_strW( str, strlenW(str) );
                printf( "\"\n" );
            }
            else
            {
Mike McCormack's avatar
Mike McCormack committed
1100
                const char *str = (const char *) entry->Text;
1101
                printf( "%s%08x \"", prefix, j );
Mike McCormack's avatar
Mike McCormack committed
1102
                dump_strA( entry->Text, strlen(str) );
1103 1104
                printf( "\"\n" );
            }
1105
            entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)entry + entry->Length);
1106 1107 1108 1109
        }
    }
}

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
static void dump_dir_resource(void)
{
    const IMAGE_RESOURCE_DIRECTORY *root = get_dir(IMAGE_FILE_RESOURCE_DIRECTORY);
    const IMAGE_RESOURCE_DIRECTORY *namedir;
    const IMAGE_RESOURCE_DIRECTORY *langdir;
    const IMAGE_RESOURCE_DIRECTORY_ENTRY *e1, *e2, *e3;
    const IMAGE_RESOURCE_DIR_STRING_U *string;
    const IMAGE_RESOURCE_DATA_ENTRY *data;
    int i, j, k;

    if (!root) return;

    printf( "Resources:" );

    for (i = 0; i< root->NumberOfNamedEntries + root->NumberOfIdEntries; i++)
    {
1126 1127
        e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
        namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s3.OffsetToDirectory);
1128 1129
        for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
        {
1130 1131
            e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
            langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s3.OffsetToDirectory);
1132 1133
            for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
            {
1134
                e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
1135 1136 1137 1138

                printf( "\n  " );
                if (e1->u1.s1.NameIsString)
                {
1139
                    string = (const IMAGE_RESOURCE_DIR_STRING_U*)((const char *)root + e1->u1.s1.NameOffset);
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
                    dump_unicode_str( string->NameString, string->Length );
                }
                else
                {
                    const char *type = get_resource_type( e1->u1.s2.Id );
                    if (type) printf( "%s", type );
                    else printf( "%04x", e1->u1.s2.Id );
                }

                printf( " Name=" );
                if (e2->u1.s1.NameIsString)
                {
1152
                    string = (const IMAGE_RESOURCE_DIR_STRING_U*) ((const char *)root + e2->u1.s1.NameOffset);
1153 1154 1155 1156 1157 1158
                    dump_unicode_str( string->NameString, string->Length );
                }
                else
                    printf( "%04x", e2->u1.s2.Id );

                printf( " Language=%04x:\n", e3->u1.s2.Id );
1159
                data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
1160 1161
                if (e1->u1.s1.NameIsString)
                {
1162
                    dump_data( RVA( data->OffsetToData, data->Size ), data->Size, "    " );
1163 1164 1165 1166
                }
                else switch(e1->u1.s2.Id)
                {
                case 6:
1167 1168
                    dump_string_data( RVA( data->OffsetToData, data->Size ), data->Size,
                                      e2->u1.s2.Id, "    " );
1169 1170 1171 1172 1173 1174
                    break;
                case 11:
                    dump_msgtable_data( RVA( data->OffsetToData, data->Size ), data->Size,
                                        e2->u1.s2.Id, "    " );
                    break;
                default:
1175
                    dump_data( RVA( data->OffsetToData, data->Size ), data->Size, "    " );
1176 1177
                    break;
                }
1178 1179 1180 1181 1182 1183
            }
        }
    }
    printf( "\n\n" );
}

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
static void dump_debug(void)
{
    const char* stabs = NULL;
    unsigned    szstabs = 0;
    const char* stabstr = NULL;
    unsigned    szstr = 0;
    unsigned    i;
    const IMAGE_SECTION_HEADER*	sectHead;

    sectHead = (const IMAGE_SECTION_HEADER*)
        ((const char*)PE_nt_headers + sizeof(DWORD) +
         sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader);

    for (i = 0; i < PE_nt_headers->FileHeader.NumberOfSections; i++, sectHead++)
    {
        if (!strcmp((const char *)sectHead->Name, ".stab"))
        {
            stabs = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize); 
            szstabs = sectHead->Misc.VirtualSize;
        }
        if (!strncmp((const char *)sectHead->Name, ".stabstr", 8))
        {
            stabstr = RVA(sectHead->VirtualAddress, sectHead->Misc.VirtualSize);
            szstr = sectHead->Misc.VirtualSize;
        }
    }
    if (stabs && stabstr)
        dump_stabs(stabs, szstabs, stabstr, szstr);
}

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
enum FileSig get_kind_exec(void)
{
    const WORD*                pw;
    const DWORD*               pdw;
    const IMAGE_DOS_HEADER*    dh;

    pw = PRD(0, sizeof(WORD));
    if (!pw) {printf("Can't get main signature, aborting\n"); return 0;}

    if (*pw != IMAGE_DOS_SIGNATURE) return SIG_UNKNOWN;

    if ((dh = PRD(0, sizeof(IMAGE_DOS_HEADER))))
    {
        /* the signature is the first DWORD */
        pdw = PRD(dh->e_lfanew, sizeof(DWORD));
        if (pdw)
        {
            if (*pdw == IMAGE_NT_SIGNATURE)                     return SIG_PE;
            if (*(const WORD *)pdw == IMAGE_OS2_SIGNATURE)      return SIG_NE;
            if (*(const WORD *)pdw == IMAGE_VXD_SIGNATURE)      return SIG_LE;
            return SIG_DOS;
        }
    }
    return 0;
}

1240
void pe_dump(void)
1241 1242 1243
{
    int	all = (globals.dumpsect != NULL) && strcmp(globals.dumpsect, "ALL") == 0;

1244 1245
    PE_nt_headers = get_nt_header();
    if (is_fake_dll()) printf( "*** This is a Wine fake DLL ***\n\n" );
1246

1247 1248 1249
    if (globals.do_dumpheader)
    {
	dump_pe_header();
1250
	/* FIXME: should check ptr */
1251
	dump_sections(PRD(0, 1), (const char*)PE_nt_headers + sizeof(DWORD) +
1252 1253
		      sizeof(IMAGE_FILE_HEADER) + PE_nt_headers->FileHeader.SizeOfOptionalHeader,
		      PE_nt_headers->FileHeader.NumberOfSections);
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    }
    else if (!globals.dumpsect)
    {
	/* show at least something here */
	dump_pe_header();
    }

    if (globals.dumpsect)
    {
	if (all || !strcmp(globals.dumpsect, "import"))
1264
        {
1265
	    dump_dir_imported_functions();
1266 1267
	    dump_dir_delay_imported_functions();
        }
1268 1269 1270 1271 1272 1273
	if (all || !strcmp(globals.dumpsect, "export"))
	    dump_dir_exported_functions();
	if (all || !strcmp(globals.dumpsect, "debug"))
	    dump_dir_debug();
	if (all || !strcmp(globals.dumpsect, "resource"))
	    dump_dir_resource();
1274 1275
	if (all || !strcmp(globals.dumpsect, "tls"))
	    dump_dir_tls();
1276 1277
	if (all || !strcmp(globals.dumpsect, "clr"))
	    dump_dir_clr_header();
1278 1279
#if 0
	/* FIXME: not implemented yet */
1280 1281 1282 1283
	if (all || !strcmp(globals.dumpsect, "reloc"))
	    dump_dir_reloc();
#endif
    }
1284 1285
    if (globals.do_debug)
        dump_debug();
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
}

typedef struct _dll_symbol {
    size_t	ordinal;
    char       *symbol;
} dll_symbol;

static dll_symbol *dll_symbols = NULL;
static dll_symbol *dll_current_symbol = NULL;

/* Compare symbols by ordinal for qsort */
static int symbol_cmp(const void *left, const void *right)
{
1299
    return ((const dll_symbol *)left)->ordinal > ((const dll_symbol *)right)->ordinal;
1300 1301 1302 1303 1304 1305 1306
}

/*******************************************************************
 *         dll_close
 *
 * Free resources used by DLL
 */
1307
/* FIXME: Not used yet
1308 1309 1310
static void dll_close (void)
{
    dll_symbol*	ds;
1311 1312 1313

    if (!dll_symbols) {
	fatal("No symbols");
1314
    }
1315 1316 1317 1318 1319
    for (ds = dll_symbols; ds->symbol; ds++)
	free(ds->symbol);
    free (dll_symbols);
    dll_symbols = NULL;
}
1320
*/
1321

1322
static	void	do_grab_sym( void )
1323
{
1324
    const IMAGE_EXPORT_DIRECTORY*exportDir;
1325
    unsigned			i, j;
1326 1327 1328
    const DWORD*		pName;
    const DWORD*		pFunc;
    const WORD* 		pOrdl;
1329
    const char*			ptr;
1330
    DWORD*			map;
1331

1332
    PE_nt_headers = get_nt_header();
1333
    if (!(exportDir = get_dir(IMAGE_FILE_EXPORT_DIRECTORY))) return;
1334

1335 1336 1337 1338
    pName = RVA(exportDir->AddressOfNames, exportDir->NumberOfNames * sizeof(DWORD));
    if (!pName) {printf("Can't grab functions' name table\n"); return;}
    pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
    if (!pOrdl) {printf("Can't grab functions' ordinal table\n"); return;}
1339

1340
    /* dll_close(); */
1341 1342

    if (!(dll_symbols = (dll_symbol *) malloc((exportDir->NumberOfFunctions + 1) *
1343 1344 1345 1346
					      sizeof (dll_symbol))))
	fatal ("Out of memory");
    if (exportDir->AddressOfFunctions != exportDir->NumberOfNames || exportDir->Base > 1)
	globals.do_ordinals = 1;
1347

1348 1349 1350
    /* bit map of used funcs */
    map = calloc(((exportDir->NumberOfFunctions + 31) & ~31) / 32, sizeof(DWORD));
    if (!map) fatal("no memory");
1351

1352
    for (j = 0; j < exportDir->NumberOfNames; j++, pOrdl++)
1353 1354 1355 1356
    {
	map[*pOrdl / 32] |= 1 << (*pOrdl % 32);
	ptr = RVA(*pName++, sizeof(DWORD));
	if (!ptr) ptr = "cant_get_function";
1357
	dll_symbols[j].symbol = strdup(ptr);
1358
	dll_symbols[j].ordinal = exportDir->Base + *pOrdl;
1359
	assert(dll_symbols[j].symbol);
1360 1361 1362
    }
    pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
    if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
1363

1364 1365
    for (i = 0; i < exportDir->NumberOfFunctions; i++)
    {
1366
	if (pFunc[i] && !(map[i / 32] & (1 << (i % 32))))
1367 1368 1369
	{
	    char ordinal_text[256];
	    /* Ordinal only entry */
1370
            snprintf (ordinal_text, sizeof(ordinal_text), "%s_%u",
1371 1372 1373
		      globals.forward_dll ? globals.forward_dll : OUTPUT_UC_DLL_NAME,
		      exportDir->Base + i);
	    str_toupper(ordinal_text);
1374 1375 1376 1377 1378
	    dll_symbols[j].symbol = strdup(ordinal_text);
	    assert(dll_symbols[j].symbol);
	    dll_symbols[j].ordinal = exportDir->Base + i;
	    j++;
	    assert(j <= exportDir->NumberOfFunctions);
1379 1380 1381
	}
    }
    free(map);
1382

1383
    if (NORMAL)
1384
	printf("%u named symbols in DLL, %u total, %d unique (ordinal base = %d)\n",
1385
	       exportDir->NumberOfNames, exportDir->NumberOfFunctions, j, exportDir->Base);
1386

1387
    qsort( dll_symbols, j, sizeof(dll_symbol), symbol_cmp );
1388

1389
    dll_symbols[j].symbol = NULL;
1390

1391 1392 1393 1394 1395 1396 1397 1398
    dll_current_symbol = dll_symbols;
}

/*******************************************************************
 *         dll_open
 *
 * Open a DLL and read in exported symbols
 */
1399
int dll_open (const char *dll_name)
1400
{
1401
    return dump_analysis(dll_name, do_grab_sym, SIG_PE);
1402 1403 1404 1405 1406 1407 1408 1409 1410
}

/*******************************************************************
 *         dll_next_symbol
 *
 * Get next exported symbol from dll
 */
int dll_next_symbol (parsed_symbol * sym)
{
1411
    if (!dll_current_symbol->symbol)
1412
	return 1;
1413

1414
    assert (dll_symbols);
1415

1416 1417 1418 1419 1420
    sym->symbol = strdup (dll_current_symbol->symbol);
    sym->ordinal = dll_current_symbol->ordinal;
    dll_current_symbol++;
    return 0;
}