pe.c 86.2 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
    case IMAGE_FILE_MACHINE_ARM64:      return "ARM64";
65
    case IMAGE_FILE_MACHINE_ARM:        return "ARM";
66
    case IMAGE_FILE_MACHINE_ARMNT:      return "ARMNT";
67
    case IMAGE_FILE_MACHINE_THUMB:      return "ARM Thumb";
68 69 70 71
    }
    return "???";
}

72
static const void*	RVA(unsigned long rva, unsigned long len)
73 74 75
{
    IMAGE_SECTION_HEADER*	sectHead;
    int				i;
76

77 78
    if (rva == 0) return NULL;

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

90
    return NULL;
91 92
}

93
static const IMAGE_NT_HEADERS32 *get_nt_header( void )
94
{
95 96 97
    const IMAGE_DOS_HEADER *dos;
    dos = PRD(0, sizeof(*dos));
    if (!dos) return NULL;
98
    return PRD(dos->e_lfanew, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER));
99 100
}

101
void print_fake_dll( void )
102
{
103
    static const char builtin_signature[] = "Wine builtin DLL";
104
    static const char fakedll_signature[] = "Wine placeholder DLL";
105
    const IMAGE_DOS_HEADER *dos;
106

107 108 109 110 111 112 113 114
    dos = PRD(0, sizeof(*dos) + 32);
    if (dos && dos->e_lfanew >= sizeof(*dos) + 32)
    {
        if (!memcmp( dos + 1, builtin_signature, sizeof(builtin_signature) ))
            printf( "*** This is a Wine builtin DLL ***\n\n" );
        else if (!memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) ))
            printf( "*** This is a Wine fake DLL ***\n\n" );
    }
115 116
}

117
static const void *get_dir_and_size(unsigned int idx, unsigned int *size)
118
{
119 120
    if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
    {
121
        const IMAGE_OPTIONAL_HEADER64 *opt = (const IMAGE_OPTIONAL_HEADER64*)&PE_nt_headers->OptionalHeader;
122 123 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);
    }
    else
    {
131
        const IMAGE_OPTIONAL_HEADER32 *opt = (const IMAGE_OPTIONAL_HEADER32*)&PE_nt_headers->OptionalHeader;
132 133 134 135 136 137 138
        if (idx >= opt->NumberOfRvaAndSizes)
            return NULL;
        if(size)
            *size = opt->DataDirectory[idx].Size;
        return RVA(opt->DataDirectory[idx].VirtualAddress,
                   opt->DataDirectory[idx].Size);
    }
139 140
}

141
static	const void*	get_dir(unsigned idx)
142
{
143
    return get_dir_and_size(idx, 0);
144 145
}

146
static const char * const DirectoryNames[16] = {
147 148 149
    "EXPORT",		"IMPORT",	"RESOURCE", 	"EXCEPTION",
    "SECURITY", 	"BASERELOC", 	"DEBUG", 	"ARCHITECTURE",
    "GLOBALPTR", 	"TLS", 		"LOAD_CONFIG",	"Bound IAT",
150
    "IAT", 		"Delay IAT",	"CLR Header", ""
151 152
};

153
static const char *get_magic_type(WORD magic)
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
{
    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)
{
173
    printf("  %-34s 0x%-8x     %u\n", title, value, value);
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;
202 203 204 205 206 207 208 209
        case IMAGE_SUBSYSTEM_NATIVE_WINDOWS:           str = "native Win9x driver";  break;
        case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:           str = "Windows CE GUI";       break;
        case IMAGE_SUBSYSTEM_EFI_APPLICATION:          str = "EFI application";      break;
        case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:  str = "EFI driver (boot)";    break;
        case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:       str = "EFI driver (runtime)"; break;
        case IMAGE_SUBSYSTEM_EFI_ROM:                  str = "EFI ROM";              break;
        case IMAGE_SUBSYSTEM_XBOX:                     str = "Xbox application";     break;
        case IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION: str = "Boot application";     break;
210 211 212 213 214 215 216 217
    }
    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)
218 219 220
    X(IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE,          "DYNAMIC_BASE");
    X(IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY,       "FORCE_INTEGRITY");
    X(IMAGE_DLLCHARACTERISTICS_NX_COMPAT,             "NX_COMPAT");
221 222 223 224 225 226 227 228
    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
}

229
static inline void print_datadirectory(DWORD n, const IMAGE_DATA_DIRECTORY *directory)
230 231 232 233 234 235
{
    unsigned i;
    printf("Data Directory\n");

    for (i = 0; i < n && i < 16; i++)
    {
236
        printf("  %-12s rva: 0x%-8x  size: 0x%-8x\n",
237 238 239 240 241
               DirectoryNames[i], directory[i].VirtualAddress,
               directory[i].Size);
    }
}

242
static void dump_optional_header32(const IMAGE_OPTIONAL_HEADER32 *image_oh, UINT header_size)
243
{
244 245 246 247 248 249 250 251
    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;

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    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);
284
    printf("\n");
285 286
}

287
static void dump_optional_header64(const IMAGE_OPTIONAL_HEADER64 *image_oh, UINT header_size)
288
{
289 290 291 292 293 294 295 296
    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;

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    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);
328
    printf("\n");
329 330
}

331
void dump_optional_header(const IMAGE_OPTIONAL_HEADER32 *optionalHeader, UINT header_size)
332
{
333 334 335 336 337 338 339 340 341 342 343 344 345 346
    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;
    }
}
347

348 349
void dump_file_header(const IMAGE_FILE_HEADER *fileHeader)
{
350
    printf("File Header\n");
351 352

    printf("  Machine:                      %04X (%s)\n",
353 354
	   fileHeader->Machine, get_machine_str(fileHeader->Machine));
    printf("  Number of Sections:           %d\n", fileHeader->NumberOfSections);
355
    printf("  TimeDateStamp:                %08X (%s) offset %lu\n",
356
	   fileHeader->TimeDateStamp, get_time_str(fileHeader->TimeDateStamp),
357
	   Offset(&(fileHeader->TimeDateStamp)));
358 359
    printf("  PointerToSymbolTable:         %08X\n", fileHeader->PointerToSymbolTable);
    printf("  NumberOfSymbols:              %08X\n", fileHeader->NumberOfSymbols);
360 361 362 363 364 365 366
    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");
367 368
    X(IMAGE_FILE_AGGRESIVE_WS_TRIM, 	"AGGRESIVE_WS_TRIM");
    X(IMAGE_FILE_LARGE_ADDRESS_AWARE, 	"LARGE_ADDRESS_AWARE");
369 370 371 372
    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");
373 374
    X(IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, 	"REMOVABLE_RUN_FROM_SWAP");
    X(IMAGE_FILE_NET_RUN_FROM_SWAP, 	"NET_RUN_FROM_SWAP");
375 376
    X(IMAGE_FILE_SYSTEM, 		"SYSTEM");
    X(IMAGE_FILE_DLL, 			"DLL");
377
    X(IMAGE_FILE_UP_SYSTEM_ONLY, 	"UP_SYSTEM_ONLY");
378 379 380
    X(IMAGE_FILE_BYTES_REVERSED_HI, 	"BYTES_REVERSED_HI");
#undef X
    printf("\n");
381
}
382

383 384 385 386
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);
387 388
}

389
void dump_section(const IMAGE_SECTION_HEADER *sectHead, const char* strtable)
390
{
391 392 393 394
        unsigned offset;

        /* long section name ? */
        if (strtable && sectHead->Name[0] == '/' &&
395
            ((offset = atoi((const char*)sectHead->Name + 1)) < *(const DWORD*)strtable))
396
            printf("  %.8s (%s)", sectHead->Name, strtable + offset);
397 398 399 400
        else
	    printf("  %-8.8s", sectHead->Name);
	printf("   VirtSize: 0x%08x  VirtAddr:  0x%08x\n",
               sectHead->Misc.VirtualSize, sectHead->VirtualAddress);
401
	printf("    raw data offs:   0x%08x  raw data size: 0x%08x\n",
402
	       sectHead->PointerToRawData, sectHead->SizeOfRawData);
403
	printf("    relocation offs: 0x%08x  relocations:   0x%08x\n",
404
	       sectHead->PointerToRelocations, sectHead->NumberOfRelocations);
405
	printf("    line # offs:     %-8u  line #'s:      %-8u\n",
406
	       sectHead->PointerToLinenumbers, sectHead->NumberOfLinenumbers);
407
	printf("    characteristics: 0x%08x\n", sectHead->Characteristics);
408 409
	printf("    ");
#define X(b,s)	if (sectHead->Characteristics & b) printf("  " s)
410 411 412 413 414 415
/* #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 */
416

417 418 419
	X(IMAGE_SCN_CNT_CODE, 			"CODE");
	X(IMAGE_SCN_CNT_INITIALIZED_DATA, 	"INITIALIZED_DATA");
	X(IMAGE_SCN_CNT_UNINITIALIZED_DATA, 	"UNINITIALIZED_DATA");
420

421 422 423 424 425
	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");
426

427 428 429
/* 						0x00002000 - Reserved */
/* #define IMAGE_SCN_MEM_PROTECTED 		0x00004000 - Obsolete */
	X(IMAGE_SCN_MEM_FARDATA, 		"MEM_FARDATA");
430

431 432 433 434 435
/* #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");
436

437 438
        switch (sectHead->Characteristics & IMAGE_SCN_ALIGN_MASK)
        {
439
#define X2(b,s)	case b: printf("  " s); break
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        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
        }
456

457
	X(IMAGE_SCN_LNK_NRELOC_OVFL, 		"LNK_NRELOC_OVFL");
458

459 460 461 462 463 464 465 466 467
	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");
468 469 470 471 472 473
}

static void dump_sections(const void *base, const void* addr, unsigned num_sect)
{
    const IMAGE_SECTION_HEADER*	sectHead = addr;
    unsigned			i;
474 475 476 477 478 479 480 481 482
    const char*                 strtable;

    if (PE_nt_headers->FileHeader.PointerToSymbolTable && PE_nt_headers->FileHeader.NumberOfSymbols)
    {
        strtable = (const char*)base +
            PE_nt_headers->FileHeader.PointerToSymbolTable +
            PE_nt_headers->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL);
    }
    else strtable = NULL;
483 484 485 486

    printf("Section Table\n");
    for (i = 0; i < num_sect; i++, sectHead++)
    {
487
        dump_section(sectHead, strtable);
488 489 490 491 492 493

        if (globals.do_dump_rawdata)
        {
            dump_data((const unsigned char *)base + sectHead->PointerToRawData, sectHead->SizeOfRawData, "    " );
            printf("\n");
        }
494 495 496 497 498
    }
}

static	void	dump_dir_exported_functions(void)
{
499
    unsigned int size = 0;
500
    const IMAGE_EXPORT_DIRECTORY*exportDir = get_dir_and_size(IMAGE_FILE_EXPORT_DIRECTORY, &size);
501
    unsigned int		i;
502 503 504
    const DWORD*		pFunc;
    const DWORD*		pName;
    const WORD* 		pOrdl;
505
    DWORD*		        funcs;
506

507
    if (!exportDir) return;
508

509 510
    printf("Exports table:\n");
    printf("\n");
511
    printf("  Name:            %s\n", (const char*)RVA(exportDir->Name, sizeof(DWORD)));
512 513
    printf("  Characteristics: %08x\n", exportDir->Characteristics);
    printf("  TimeDateStamp:   %08X %s\n",
514 515
	   exportDir->TimeDateStamp, get_time_str(exportDir->TimeDateStamp));
    printf("  Version:         %u.%02u\n", exportDir->MajorVersion, exportDir->MinorVersion);
516 517 518 519 520 521
    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);
522 523
    printf("\n");
    printf("  Entry Pt  Ordn  Name\n");
524

525 526 527 528
    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));
    pOrdl = RVA(exportDir->AddressOfNameOrdinals, exportDir->NumberOfNames * sizeof(WORD));
529

530 531 532 533
    funcs = calloc( exportDir->NumberOfFunctions, sizeof(*funcs) );
    if (!funcs) fatal("no memory");

    for (i = 0; i < exportDir->NumberOfNames; i++) funcs[pOrdl[i]] = pName[i];
534

535 536
    for (i = 0; i < exportDir->NumberOfFunctions; i++)
    {
537 538 539 540
        if (!pFunc[i]) continue;
        printf("  %08X %5u ", pFunc[i], exportDir->Base + i);
        if (funcs[i])
            printf("%s", get_symbol_str((const char*)RVA(funcs[i], sizeof(DWORD))));
541 542 543 544 545 546 547 548
        else
            printf("<by ordinal>");

        /* check for forwarded function */
        if ((const char *)RVA(pFunc[i],1) >= (const char *)exportDir &&
            (const char *)RVA(pFunc[i],1) < (const char *)exportDir + size)
            printf(" (-> %s)", (const char *)RVA(pFunc[i],1));
        printf("\n");
549
    }
550
    free(funcs);
551 552 553
    printf("\n");
}

554

555
struct runtime_function_x86_64
556 557 558 559 560 561
{
    DWORD BeginAddress;
    DWORD EndAddress;
    DWORD UnwindData;
};

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
struct runtime_function_armnt
{
    DWORD BeginAddress;
    union {
        DWORD UnwindData;
        struct {
            DWORD Flag : 2;
            DWORD FunctionLength : 11;
            DWORD Ret : 2;
            DWORD H : 1;
            DWORD Reg : 3;
            DWORD R : 1;
            DWORD L : 1;
            DWORD C : 1;
            DWORD StackAdjust : 10;
        } DUMMYSTRUCTNAME;
    } DUMMYUNIONNAME;
};

581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
struct runtime_function_arm64
{
    DWORD BeginAddress;
    union
    {
        DWORD UnwindData;
        struct
        {
            DWORD Flag : 2;
            DWORD FunctionLength : 11;
            DWORD RegF : 3;
            DWORD RegI : 4;
            DWORD H : 1;
            DWORD CR : 2;
            DWORD FrameSize : 9;
        } DUMMYSTRUCTNAME;
    } DUMMYUNIONNAME;
};

600 601
union handler_data
{
602
    struct runtime_function_x86_64 chain;
603 604 605 606 607 608 609 610 611 612
    DWORD handler;
};

struct opcode
{
    BYTE offset;
    BYTE code : 4;
    BYTE info : 4;
};

613
struct unwind_info_x86_64
614 615 616 617 618 619 620 621 622 623 624
{
    BYTE version : 3;
    BYTE flags : 5;
    BYTE prolog;
    BYTE count;
    BYTE frame_reg : 4;
    BYTE frame_offset : 4;
    struct opcode opcodes[1];  /* count entries */
    /* followed by union handler_data */
};

625 626
struct unwind_info_armnt
{
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
    DWORD function_length : 18;
    DWORD version : 2;
    DWORD x : 1;
    DWORD e : 1;
    DWORD f : 1;
    DWORD count : 5;
    DWORD words : 4;
};

struct unwind_info_ext_armnt
{
    WORD excount;
    BYTE exwords;
    BYTE reserved;
};

struct unwind_info_epilogue_armnt
{
    DWORD offset : 18;
    DWORD res : 2;
    DWORD cond : 4;
    DWORD index : 8;
649 650
};

651 652 653 654 655 656 657 658 659 660 661 662 663 664
#define UWOP_PUSH_NONVOL     0
#define UWOP_ALLOC_LARGE     1
#define UWOP_ALLOC_SMALL     2
#define UWOP_SET_FPREG       3
#define UWOP_SAVE_NONVOL     4
#define UWOP_SAVE_NONVOL_FAR 5
#define UWOP_SAVE_XMM128     8
#define UWOP_SAVE_XMM128_FAR 9
#define UWOP_PUSH_MACHFRAME  10

#define UNW_FLAG_EHANDLER  1
#define UNW_FLAG_UHANDLER  2
#define UNW_FLAG_CHAININFO 4

665
static void dump_x86_64_unwind_info( const struct runtime_function_x86_64 *function )
666 667 668 669 670
{
    static const char * const reg_names[16] =
        { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
          "r8",  "r9",  "r10", "r11", "r12", "r13", "r14", "r15" };

671
    const union handler_data *handler_data;
672
    const struct unwind_info_x86_64 *info;
673 674 675 676 677
    unsigned int i, count;

    printf( "\nFunction %08x-%08x:\n", function->BeginAddress, function->EndAddress );
    if (function->UnwindData & 1)
    {
678
        const struct runtime_function_x86_64 *next = RVA( function->UnwindData & ~1, sizeof(*next) );
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
        printf( "  -> function %08x-%08x\n", next->BeginAddress, next->EndAddress );
        return;
    }
    info = RVA( function->UnwindData, sizeof(*info) );

    printf( "  unwind info at %08x\n", function->UnwindData );
    if (info->version != 1)
    {
        printf( "    *** unknown version %u\n", info->version );
        return;
    }
    printf( "    flags %x", info->flags );
    if (info->flags & UNW_FLAG_EHANDLER) printf( " EHANDLER" );
    if (info->flags & UNW_FLAG_UHANDLER) printf( " UHANDLER" );
    if (info->flags & UNW_FLAG_CHAININFO) printf( " CHAININFO" );
    printf( "\n    prolog 0x%x bytes\n", info->prolog );

    if (info->frame_reg)
        printf( "    frame register %s offset 0x%x(%%rsp)\n",
                reg_names[info->frame_reg], info->frame_offset * 16 );

    for (i = 0; i < info->count; i++)
    {
        printf( "      0x%02x: ", info->opcodes[i].offset );
        switch (info->opcodes[i].code)
        {
        case UWOP_PUSH_NONVOL:
            printf( "push %%%s\n", reg_names[info->opcodes[i].info] );
            break;
        case UWOP_ALLOC_LARGE:
            if (info->opcodes[i].info)
            {
711
                count = *(const DWORD *)&info->opcodes[i+1];
712 713 714 715
                i += 2;
            }
            else
            {
716
                count = *(const USHORT *)&info->opcodes[i+1] * 8;
717 718 719 720 721 722 723 724 725 726 727 728 729
                i++;
            }
            printf( "sub $0x%x,%%rsp\n", count );
            break;
        case UWOP_ALLOC_SMALL:
            count = (info->opcodes[i].info + 1) * 8;
            printf( "sub $0x%x,%%rsp\n", count );
            break;
        case UWOP_SET_FPREG:
            printf( "lea 0x%x(%%rsp),%s\n",
                    info->frame_offset * 16, reg_names[info->frame_reg] );
            break;
        case UWOP_SAVE_NONVOL:
730
            count = *(const USHORT *)&info->opcodes[i+1] * 8;
731 732 733 734
            printf( "mov %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
            i++;
            break;
        case UWOP_SAVE_NONVOL_FAR:
735
            count = *(const DWORD *)&info->opcodes[i+1];
736 737 738 739
            printf( "mov %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
            i += 2;
            break;
        case UWOP_SAVE_XMM128:
740
            count = *(const USHORT *)&info->opcodes[i+1] * 16;
741 742 743 744
            printf( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
            i++;
            break;
        case UWOP_SAVE_XMM128_FAR:
745
            count = *(const DWORD *)&info->opcodes[i+1];
746 747 748 749 750 751 752 753 754 755 756 757
            printf( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
            i += 2;
            break;
        case UWOP_PUSH_MACHFRAME:
            printf( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
            break;
        default:
            printf( "*** unknown code %u\n", info->opcodes[i].code );
            break;
        }
    }

758
    handler_data = (const union handler_data *)&info->opcodes[(info->count + 1) & ~1];
759 760 761 762 763 764 765 766
    if (info->flags & UNW_FLAG_CHAININFO)
    {
        printf( "    -> function %08x-%08x\n",
                handler_data->chain.BeginAddress, handler_data->chain.EndAddress );
        return;
    }
    if (info->flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER))
        printf( "    handler %08x data at %08x\n", handler_data->handler,
767
                (ULONG)(function->UnwindData + (const char *)(&handler_data->handler + 1) - (const char *)info ));
768 769
}

770
static void dump_armnt_unwind_info( const struct runtime_function_armnt *fnc )
771 772
{
    const struct unwind_info_armnt *info;
773 774 775 776 777 778
    const struct unwind_info_ext_armnt *infoex;
    const struct unwind_info_epilogue_armnt *infoepi;
    unsigned int rva;
    WORD i, count = 0, words = 0;

    if (fnc->u.s.Flag)
779
    {
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
        char intregs[32] = {0}, intregspop[32] = {0}, vfpregs[32] = {0};
        WORD pf = 0, ef = 0, sc = 0;

        printf( "\nFunction %08x-%08x:\n", fnc->BeginAddress & ~1,
                (fnc->BeginAddress & ~1) + fnc->u.s.FunctionLength * 2 );
        printf( "    Flag           %x\n", fnc->u.s.Flag );
        printf( "    FunctionLength %x\n", fnc->u.s.FunctionLength );
        printf( "    Ret            %x\n", fnc->u.s.Ret );
        printf( "    H              %x\n", fnc->u.s.H );
        printf( "    Reg            %x\n", fnc->u.s.Reg );
        printf( "    R              %x\n", fnc->u.s.R );
        printf( "    L              %x\n", fnc->u.s.L );
        printf( "    C              %x\n", fnc->u.s.C );
        printf( "    StackAdjust    %x\n", fnc->u.s.StackAdjust );

        if (fnc->u.s.StackAdjust >= 0x03f4)
        {
            pf = fnc->u.s.StackAdjust & 0x04;
            ef = fnc->u.s.StackAdjust & 0x08;
        }

        if (!fnc->u.s.R && !pf)
        {
            if (fnc->u.s.Reg)
            {
                sprintf(intregs, "r4-r%u", fnc->u.s.Reg + 4);
                sprintf(intregspop, "r4-r%u", fnc->u.s.Reg + 4);
            }
            else
            {
                strcpy(intregs, "r4");
                strcpy(intregspop, "r4");
            }
            sc = fnc->u.s.Reg + 1;
            if (fnc->u.s.C || fnc->u.s.L)
            {
                strcat(intregs, ", ");
817
                if (fnc->u.s.C || (fnc->u.s.L && !fnc->u.s.H))
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
                    strcat(intregspop, ", ");
            }
        }
        else if (fnc->u.s.R && pf)
        {
            if (((~fnc->u.s.StackAdjust) & 3) != 3)
            {
                sprintf(intregs, "r%u-r3", (~fnc->u.s.StackAdjust) & 3);
                sprintf(intregspop, "r%u-r3", (~fnc->u.s.StackAdjust) & 3);
            }
            else
            {
                sprintf(intregs, "r3");
                sprintf(intregspop, "r3");
            }
            sc = 4 - ((~fnc->u.s.StackAdjust) & 3);
            if (fnc->u.s.C || fnc->u.s.L)
            {
                strcat(intregs, ", ");
837
                if (fnc->u.s.C || (fnc->u.s.L && !fnc->u.s.H))
838 839 840 841 842 843 844 845 846 847 848
                    strcat(intregspop, ", ");
            }
        }
        else if (!fnc->u.s.R && pf)
        {
            sprintf(intregs, "r%u-r%u", (~fnc->u.s.StackAdjust) & 3, fnc->u.s.Reg + 4);
            sprintf(intregspop, "r%u-r%u", (~fnc->u.s.StackAdjust) & 3, fnc->u.s.Reg + 4);
            sc = fnc->u.s.Reg + 5 - ((~fnc->u.s.StackAdjust) & 3);
            if (fnc->u.s.C || fnc->u.s.L)
            {
                strcat(intregs, ", ");
849
                if (fnc->u.s.C || (fnc->u.s.L && !fnc->u.s.H))
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
                    strcat(intregspop, ", ");
            }
        }
        else if (fnc->u.s.R && !pf)
        {
            if (!fnc->u.s.C && !fnc->u.s.L)
            {
                strcpy(intregs, "none");
                strcpy(intregspop, "none");
            }
        }

        if (fnc->u.s.C && !fnc->u.s.L)
        {
            strcat(intregs, "r11");
            strcat(intregspop, "r11");
        }
        else if (fnc->u.s.C && fnc->u.s.L)
        {
            strcat(intregs, "r11, lr");
            if (fnc->u.s.H)
                strcat(intregspop, "r11");
            else
                strcat(intregspop, "r11, pc");
        }
        else if (!fnc->u.s.C && fnc->u.s.L)
        {
            strcat(intregs, "lr");
            if (!fnc->u.s.H)
                strcat(intregspop, "pc");
        }

        if (fnc->u.s.R)
        {
            if (fnc->u.s.Reg)
                sprintf(vfpregs, "d8-d%u", fnc->u.s.Reg + 8);
            else
                strcpy(vfpregs, "d8");
        }
        else
            strcpy(vfpregs, "none");

        if (fnc->u.s.H)
            printf( "    Unwind Code\tpush {r0-r3}\n" );

        if (fnc->u.s.R || fnc->u.s.L || fnc->u.s.C || pf)
            printf( "    Unwind Code\tpush {%s}\n", intregs );

        if (fnc->u.s.C && fnc->u.s.R && !fnc->u.s.L && !pf)
            printf( "    Unwind Code\tmov r11, sp\n" );
        else if (fnc->u.s.C && (!fnc->u.s.R || fnc->u.s.L || pf))
        {
            if (fnc->u.s.StackAdjust >= 0x03f4 && !sc)
                printf( "    Unwind Code\tadd r11, sp, #<unknown>\n");
            else if (fnc->u.s.StackAdjust >= 0x03f4)
                printf( "    Unwind Code\tadd r11, sp, #%d\n", sc * 4 );
            else
                printf( "    Unwind Code\tadd r11, sp, #%d\n", fnc->u.s.StackAdjust * 4 );
        }

        if (fnc->u.s.R && fnc->u.s.Reg != 0x07)
            printf( "    Unwind Code\tvpush {%s}\n", vfpregs );

        if (fnc->u.s.StackAdjust < 0x03f4 && !pf)
            printf( "    Unwind Code\tsub sp, sp, #%d\n", fnc->u.s.StackAdjust * 4 );


        if (fnc->u.s.StackAdjust < 0x03f4 && !ef)
            printf( "    Unwind Code\tadd sp, sp, #%d\n", fnc->u.s.StackAdjust * 4 );

        if (fnc->u.s.R && fnc->u.s.Reg != 0x07)
            printf( "    Unwind Code\tvpop {%s}\n", vfpregs );

        if (fnc->u.s.C || !fnc->u.s.R || ef || (fnc->u.s.L && !fnc->u.s.H))
            printf( "    Unwind Code\tpop {%s}\n", intregspop );

        if (fnc->u.s.H && !fnc->u.s.L)
            printf( "    Unwind Code\tadd sp, sp, #16\n" );
        else if (fnc->u.s.H && fnc->u.s.L)
            printf( "    Unwind Code\tldr pc, [sp], #20\n" );

        if (fnc->u.s.Ret == 1)
            printf( "    Unwind Code\tbx <reg>\n" );
        else if (fnc->u.s.Ret == 2)
            printf( "    Unwind Code\tb <address>\n" );

936 937 938
        return;
    }

939 940 941 942
    info = RVA( fnc->u.UnwindData, sizeof(*info) );
    rva = fnc->u.UnwindData + sizeof(*info);
    count = info->count;
    words = info->words;
943

944 945 946 947
    printf( "\nFunction %08x-%08x:\n", fnc->BeginAddress & ~1,
            (fnc->BeginAddress & ~1) + info->function_length * 2 );
    printf( "  unwind info at %08x\n", fnc->u.UnwindData );
    printf( "    Flag           %x\n", fnc->u.s.Flag );
948
    printf( "    FunctionLength %x\n", info->function_length );
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 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 1008 1009 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 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    printf( "    Version        %x\n", info->version );
    printf( "    X              %x\n", info->x );
    printf( "    E              %x\n", info->e );
    printf( "    F              %x\n", info->f );
    printf( "    Count          %x\n", count );
    printf( "    Words          %x\n", words );

    if (!info->count && !info->words)
    {
        infoex = RVA( rva, sizeof(*infoex) );
        rva = rva + sizeof(*infoex);
        count = infoex->excount;
        words = infoex->exwords;
        printf( "    ExtCount       %x\n", count );
        printf( "    ExtWords       %x\n", words );
    }

    if (!info->e)
    {
        infoepi = RVA( rva, count * sizeof(*infoepi) );
        rva = rva + count * sizeof(*infoepi);

        for (i = 0; i < count; i++)
        {
            printf( "    Epilogue Scope %x\n", i );
            printf( "      Offset       %x\n", infoepi[i].offset );
            printf( "      Reserved     %x\n", infoepi[i].res );
            printf( "      Condition    %x\n", infoepi[i].cond );
            printf( "      Index        %x\n", infoepi[i].index );
        }
    }
    else
        infoepi = NULL;

    if (words)
    {
        const unsigned int *codes;
        BYTE b, *bytes;
        BOOL inepilogue = FALSE;

        codes = RVA( rva, words * sizeof(*codes) );
        rva = rva + words * sizeof(*codes);
        bytes = (BYTE*)codes;

        for (b = 0; b < words * sizeof(*codes); b++)
        {
            BYTE code = bytes[b];

            if (info->e && b == count)
            {
                printf( "Epilogue:\n" );
                inepilogue = TRUE;
            }
            else if (!info->e && infoepi)
            {
                for (i = 0; i < count; i++)
                    if (b == infoepi[i].index)
                    {
                        printf( "Epilogue from Scope %x at %08x:\n", i,
                                (fnc->BeginAddress & ~1) + infoepi[i].offset * 2 );
                        inepilogue = TRUE;
                    }
            }

            printf( "    Unwind Code %x\t", code );

            if (code == 0x00)
                printf( "\n" );
            else if (code <= 0x7f)
                printf( "%s sp, sp, #%u\n", inepilogue ? "add" : "sub", code * 4 );
            else if (code <= 0xbf)
            {
                WORD excode, f;
                BOOL first = TRUE;
                BYTE excodes = bytes[++b];

                excode = (code << 8) | excodes;
                printf( "%s {", inepilogue ? "pop" : "push" );

                for (f = 0; f <= 12; f++)
                {
                    if ((excode >> f) & 1)
                    {
                        printf( "%sr%u", first ? "" : ", ", f );
                        first = FALSE;
                    }
                }

                if (excode & 0x2000)
                    printf( "%s%s", first ? "" : ", ", inepilogue ? "pc" : "lr" );

                printf( "}\n" );
            }
            else if (code <= 0xcf)
                if (inepilogue)
                    printf( "mov sp, r%u\n", code & 0x0f );
                else
                    printf( "mov r%u, sp\n", code & 0x0f );
            else if (code <= 0xd7)
                if (inepilogue)
                    printf( "pop {r4-r%u%s}\n", (code & 0x03) + 4, (code & 0x04) ? ", pc" : "" );
                else
                    printf( "push {r4-r%u%s}\n", (code & 0x03) + 4, (code & 0x04) ? ", lr" : "" );
            else if (code <= 0xdf)
                if (inepilogue)
                    printf( "pop {r4-r%u%s}\n", (code & 0x03) + 8, (code & 0x04) ? ", pc" : "" );
                else
                    printf( "push {r4-r%u%s}\n", (code & 0x03) + 8, (code & 0x04) ? ", lr" : "" );
            else if (code <= 0xe7)
                printf( "%s {d8-d%u}\n", inepilogue ? "vpop" : "vpush", (code & 0x07) + 8 );
            else if (code <= 0xeb)
            {
                WORD excode;
                BYTE excodes = bytes[++b];

                excode = (code << 8) | excodes;
                printf( "%s sp, sp, #%u\n", inepilogue ? "addw" : "subw", (excode & 0x03ff) *4 );
            }
            else if (code <= 0xed)
            {
                WORD excode, f;
                BOOL first = TRUE;
                BYTE excodes = bytes[++b];

                excode = (code << 8) | excodes;
                printf( "%s {", inepilogue ? "pop" : "push" );

                for (f = 0; f < 8; f++)
                {
                    if ((excode >> f) & 1)
                    {
                        printf( "%sr%u", first ? "" : ", ", f );
                        first = FALSE;
                    }
                }

                if (excode & 0x0100)
                    printf( "%s%s", first ? "" : ", ", inepilogue ? "pc" : "lr" );

                printf( "}\n" );
            }
            else if (code == 0xee)
                printf( "unknown 16\n" );
            else if (code == 0xef)
            {
                WORD excode;
                BYTE excodes = bytes[++b];

                if (excodes <= 0x0f)
                {
                    excode = (code << 8) | excodes;
                    if (inepilogue)
                        printf( "ldr lr, [sp], #%u\n", (excode & 0x0f) * 4 );
                    else
                        printf( "unknown 32\n" );
                }
                else
                    printf( "unknown 32\n" );
            }
            else if (code <= 0xf4)
                printf( "unknown\n" );
            else if (code <= 0xf6)
            {
                WORD excode, offset = (code == 0xf6) ? 16 : 0;
                BYTE excodes = bytes[++b];

                excode = (code << 8) | excodes;
                printf( "%s {d%u-d%u}\n", inepilogue ? "vpop" : "vpush",
                        ((excode & 0x00f0) >> 4) + offset, (excode & 0x0f) + offset );
            }
            else if (code <= 0xf7)
            {
                unsigned int excode;
                BYTE excodes[2];

                excodes[0] = bytes[++b];
                excodes[1] = bytes[++b];
                excode = (code << 16) | (excodes[0] << 8) | excodes[1];
                printf( "%s sp, sp, #%u\n", inepilogue ? "add" : "sub", (excode & 0xffff) *4 );
            }
            else if (code <= 0xf8)
            {
                unsigned int excode;
                BYTE excodes[3];

                excodes[0] = bytes[++b];
                excodes[1] = bytes[++b];
                excodes[2] = bytes[++b];
                excode = (code << 24) | (excodes[0] << 16) | (excodes[1] << 8) | excodes[2];
                printf( "%s sp, sp, #%u\n", inepilogue ? "add" : "sub", (excode & 0xffffff) * 4 );
            }
            else if (code <= 0xf9)
            {
                unsigned int excode;
                BYTE excodes[2];

                excodes[0] = bytes[++b];
                excodes[1] = bytes[++b];
                excode = (code << 16) | (excodes[0] << 8) | excodes[1];
                printf( "%s sp, sp, #%u\n", inepilogue ? "add" : "sub", (excode & 0xffff) *4 );
            }
            else if (code <= 0xfa)
            {
                unsigned int excode;
                BYTE excodes[3];

                excodes[0] = bytes[++b];
                excodes[1] = bytes[++b];
                excodes[2] = bytes[++b];
                excode = (code << 24) | (excodes[0] << 16) | (excodes[1] << 8) | excodes[2];
                printf( "%s sp, sp, #%u\n", inepilogue ? "add" : "sub", (excode & 0xffffff) * 4 );
            }
            else if (code <= 0xfc)
                printf( "nop\n" );
            else if (code <= 0xfe)
            {
                printf( "(end) nop\n" );
                inepilogue = TRUE;
            }
            else
            {
                printf( "end\n" );
                inepilogue = TRUE;
            }
        }
    }

    if (info->x)
    {
        const unsigned int *handler;

        handler = RVA( rva, sizeof(*handler) );
        rva = rva + sizeof(*handler);

        printf( "    handler %08x data at %08x\n", *handler, rva);
    }
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 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 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
struct unwind_info_arm64
{
    DWORD function_length : 18;
    DWORD version : 2;
    DWORD x : 1;
    DWORD e : 1;
    DWORD epilog : 5;
    DWORD codes : 5;
};

struct unwind_info_ext_arm64
{
    WORD epilog;
    BYTE codes;
    BYTE reserved;
};

struct unwind_info_epilog_arm64
{
    DWORD offset : 18;
    DWORD res : 4;
    DWORD index : 10;
};

static const BYTE code_lengths[256] =
{
/* 00 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 20 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 40 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 60 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 80 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* a0 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* c0 */ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
/* e0 */ 4,1,2,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
};

static void dump_arm64_codes( const BYTE *ptr, unsigned int count )
{
    unsigned int i, j;

    for (i = 0; i < count; i += code_lengths[ptr[i]])
    {
        BYTE len = code_lengths[ptr[i]];
        unsigned int val = ptr[i];
        if (len == 2) val = ptr[i] * 0x100 + ptr[i+1];
        else if (len == 4) val = ptr[i] * 0x1000000 + ptr[i+1] * 0x10000 + ptr[i+2] * 0x100 + ptr[i+3];

        printf( "    %04x: ", i );
        for (j = 0; j < 4; j++)
            if (j < len) printf( "%02x ", ptr[i+j] );
            else printf( "   " );

        if (ptr[i] < 0x20)  /* alloc_s */
        {
            printf( "sub sp,sp,#%#x\n", 16 * (val & 0x1f) );
        }
        else if (ptr[i] < 0x40)  /* save_r19r20_x */
        {
            printf( "stp r19,r20,[sp,-#%#x]!\n", 8 * (val & 0x1f) );
        }
        else if (ptr[i] < 0x80) /* save_fplr */
        {
            printf( "stp r29,lr,[sp,#%#x]\n", 8 * (val & 0x3f) );
        }
        else if (ptr[i] < 0xc0)  /* save_fplr_x */
        {
            printf( "stp r29,lr,[sp,-#%#x]!\n", 8 * (val & 0x3f) + 8 );
        }
        else if (ptr[i] < 0xc8)  /* alloc_m */
        {
            printf( "sub sp,sp,#%#x\n", 16 * (val & 0x7ff) );
        }
        else if (ptr[i] < 0xcc)  /* save_regp */
        {
            int reg = 19 + ((val >> 6) & 0xf);
            printf( "stp r%u,r%u,[sp,#%#x]\n", reg, reg + 1, 8 * (val & 0x3f) );
        }
        else if (ptr[i] < 0xd0)  /* save_regp_x */
        {
            int reg = 19 + ((val >> 6) & 0xf);
            printf( "stp r%u,r%u,[sp,-#%#x]!\n", reg, reg + 1, 8 * (val & 0x3f) + 8 );
        }
        else if (ptr[i] < 0xd4)  /* save_reg */
        {
            int reg = 19 + ((val >> 6) & 0xf);
            printf( "str r%u,[sp,#%#x]\n", reg, 8 * (val & 0x3f) );
        }
        else if (ptr[i] < 0xd6)  /* save_reg_x */
        {
            int reg = 19 + ((val >> 5) & 0xf);
            printf( "str r%u,[sp,-#%#x]!\n", reg, 8 * (val & 0x1f) + 8 );
        }
        else if (ptr[i] < 0xd8)  /* save_lrpair */
        {
            int reg = 19 + 2 * ((val >> 6) & 0x7);
            printf( "stp r%u,lr,[sp,#%#x]\n", reg, 8 * (val & 0x3f) );
        }
        else if (ptr[i] < 0xda)  /* save_fregp */
        {
            int reg = 8 + ((val >> 6) & 0x7);
            printf( "stp d%u,d%u,[sp,#%#x]\n", reg, reg + 1, 8 * (val & 0x3f) );
        }
        else if (ptr[i] < 0xdc)  /* save_fregp_x */
        {
            int reg = 8 + ((val >> 6) & 0x7);
            printf( "stp d%u,d%u,[sp,-#%#x]!\n", reg, reg + 1, 8 * (val & 0x3f) + 8 );
        }
        else if (ptr[i] < 0xde)  /* save_freg */
        {
            int reg = 8 + ((val >> 6) & 0x7);
            printf( "str d%u,[sp,#%#x]\n", reg, 8 * (val & 0x3f) );
        }
        else if (ptr[i] == 0xde)  /* save_freg_x */
        {
            int reg = 8 + ((val >> 5) & 0x7);
            printf( "str d%u,[sp,-#%#x]!\n", reg, 8 * (val & 0x3f) + 8 );
        }
        else if (ptr[i] == 0xe0)  /* alloc_l */
        {
            printf( "sub sp,sp,#%#x\n", 16 * (val & 0xffffff) );
        }
        else if (ptr[i] == 0xe1)  /* set_fp */
        {
            printf( "mov x29,sp\n" );
        }
        else if (ptr[i] == 0xe2)  /* add_fp */
        {
            printf( "add x29,sp,#%#x\n", 8 * (val & 0xff) );
        }
        else if (ptr[i] == 0xe3)  /* nop */
        {
            printf( "nop\n" );
        }
        else if (ptr[i] == 0xe4)  /* end */
        {
            printf( "end\n" );
        }
        else if (ptr[i] == 0xe5)  /* end_c */
        {
            printf( "end_c\n" );
        }
        else if (ptr[i] == 0xe6)  /* save_next */
        {
            printf( "save_next\n" );
        }
        else if (ptr[i] == 0xe7)  /* arithmetic */
        {
            switch ((val >> 4) & 0x0f)
            {
            case 0: printf( "add lr,lr,x28\n" ); break;
            case 1: printf( "add lr,lr,sp\n" ); break;
            case 2: printf( "sub lr,lr,x28\n" ); break;
            case 3: printf( "sub lr,lr,sp\n" ); break;
            case 4: printf( "eor lr,lr,x28\n" ); break;
            case 5: printf( "eor lr,lr,sp\n" ); break;
            case 6: printf( "rol lr,lr,neg x28\n" ); break;
            case 8: printf( "ror lr,lr,x28\n" ); break;
            case 9: printf( "ror lr,lr,sp\n" ); break;
            default:printf( "unknown op\n" ); break;
            }
        }
        else if (ptr[i] == 0xe9)  /* MSFT_OP_TRAP_FRAME */
        {
            printf( "MSFT_OP_TRAP_FRAME\n" );
        }
        else if (ptr[i] == 0xea)  /* MSFT_OP_MACHINE_FRAME */
        {
            printf( "MSFT_OP_MACHINE_FRAME\n" );
        }
        else if (ptr[i] == 0xeb)  /* MSFT_OP_CONTEXT */
        {
            printf( "MSFT_OP_CONTEXT\n" );
        }
        else printf( "??\n");
    }
}

static void dump_arm64_packed_info( const struct runtime_function_arm64 *func )
{
    int i, pos = 0, intsz = func->u.s.RegI * 8, fpsz = func->u.s.RegF * 8, savesz, locsz;

    if (func->u.s.CR == 1) intsz += 8;
    if (func->u.s.RegF) fpsz += 8;

    savesz = ((intsz + fpsz + 8 * 8 * func->u.s.H) + 0xf) & ~0xf;
    locsz = func->u.s.FrameSize * 16 - savesz;

    switch (func->u.s.CR)
    {
    case 3:
        printf( "    %04x:  mov x29,sp\n", pos++ );
        if (locsz <= 512)
        {
            printf( "    %04x:  stp x29,lr,[sp,-#%#x]!\n", pos++, locsz );
            break;
        }
        printf( "    %04x:  stp x29,lr,[sp,0]\n", pos++ );
        /* fall through */
    case 0:
    case 1:
        if (locsz <= 4080)
        {
            printf( "    %04x:  sub sp,sp,#%#x\n", pos++, locsz );
        }
        else
        {
            printf( "    %04x:  sub sp,sp,#%#x\n", pos++, locsz - 4080 );
            printf( "    %04x:  sub sp,sp,#%#x\n", pos++, 4080 );
        }
        break;
    }

    if (func->u.s.H)
    {
        printf( "    %04x:  stp x6,x7,[sp,#%#x]\n", pos++, intsz + fpsz + 48 );
        printf( "    %04x:  stp x4,x5,[sp,#%#x]\n", pos++, intsz + fpsz + 32 );
        printf( "    %04x:  stp x2,x3,[sp,#%#x]\n", pos++, intsz + fpsz + 16 );
        printf( "    %04x:  stp x0,x1,[sp,#%#x]\n", pos++, intsz + fpsz );
    }

    if (func->u.s.RegF)
    {
        if (func->u.s.RegF % 2 == 0)
            printf( "    %04x:  str d%u,[sp,#%#x]\n", pos++, 8 + func->u.s.RegF, intsz + fpsz - 8 );
        for (i = func->u.s.RegF / 2 - 1; i >= 0; i--)
        {
            if (!i && !intsz)
                printf( "    %04x:  stp d8,d9,[sp,-#%#x]!\n", pos++, savesz );
            else
                printf( "    %04x:  stp d%u,d%u,[sp,#%#x]\n", pos++, 8 + 2 * i, 9 + 2 * i, intsz + 16 * i );
        }
    }

    switch (func->u.s.RegI)
    {
    case 0:
        if (func->u.s.CR == 1)
            printf( "    %04x:  str lr,[sp,-#%#x]!\n", pos++, savesz );
        break;
    case 1:
        if (func->u.s.CR == 1)
            printf( "    %04x:  stp x19,lr,[sp,-#%#x]!\n", pos++, savesz );
        else
            printf( "    %04x:  str x19,[sp,-#%#x]!\n", pos++, savesz );
        break;
    default:
        if (func->u.s.RegI % 2)
        {
            if (func->u.s.CR == 1)
                printf( "    %04x:  stp x%u,lr,[sp,#%#x]\n", pos++, 18 + func->u.s.RegI, 8 * func->u.s.RegI - 8 );
            else
                printf( "    %04x:  str x%u,[sp,#%#x]\n", pos++, 18 + func->u.s.RegI, 8 * func->u.s.RegI - 8 );
        }
        else if (func->u.s.CR == 1)
            printf( "    %04x:  str lr,[sp,#%#x]\n", pos++, intsz - 8 );

        for (i = func->u.s.RegI / 2 - 1; i >= 0; i--)
            if (i)
                printf( "    %04x:  stp x%u,x%u,[sp,#%#x]\n", pos++, 19 + 2 * i, 20 + 2 * i, 16 * i );
            else
                printf( "    %04x:  stp x19,x20,[sp,-#%#x]!\n", pos++, savesz );
        break;
    }
    printf( "    %04x:  end\n", pos );
}

static void dump_arm64_unwind_info( const struct runtime_function_arm64 *func )
{
    const struct unwind_info_arm64 *info;
    const struct unwind_info_ext_arm64 *infoex;
    const struct unwind_info_epilog_arm64 *infoepi;
    const BYTE *ptr;
    unsigned int i, rva, codes, epilogs;

    if (func->u.s.Flag)
    {
        printf( "\nFunction %08x-%08x:\n", func->BeginAddress,
                func->BeginAddress + func->u.s.FunctionLength * 4 );
        printf( "    len=%#x flag=%x regF=%u regI=%u H=%u CR=%u frame=%x\n",
                func->u.s.FunctionLength, func->u.s.Flag, func->u.s.RegF, func->u.s.RegI,
                func->u.s.H, func->u.s.CR, func->u.s.FrameSize );
        dump_arm64_packed_info( func );
        return;
    }

    rva = func->u.UnwindData;
    info = RVA( rva, sizeof(*info) );
    rva += sizeof(*info);
    epilogs = info->epilog;
    codes = info->codes;

    if (!codes)
    {
        infoex = RVA( rva, sizeof(*infoex) );
        rva = rva + sizeof(*infoex);
        codes = infoex->codes;
        epilogs = infoex->epilog;
    }
    printf( "\nFunction %08x-%08x:\n",
            func->BeginAddress, func->BeginAddress + info->function_length * 4 );
    printf( "    len=%#x ver=%u X=%u E=%u epilogs=%u codes=%u\n",
            info->function_length, info->version, info->x, info->e, epilogs, codes * 4 );
    if (info->e)
    {
        printf( "    epilog 0: code=%04x\n", info->epilog );
    }
    else
    {
        infoepi = RVA( rva, sizeof(*infoepi) * epilogs );
        rva += sizeof(*infoepi) * epilogs;
        for (i = 0; i < epilogs; i++)
            printf( "    epilog %u: pc=%08x code=%04x\n", i,
                    func->BeginAddress + infoepi[i].offset * 4, infoepi[i].index );
    }
    ptr = RVA( rva, codes * 4);
    rva += codes * 4;
    if (info->x)
    {
        const DWORD *handler = RVA( rva, sizeof(*handler) );
        rva += sizeof(*handler);
        printf( "    handler: %08x data %08x\n", *handler, rva );
    }
    dump_arm64_codes( ptr, codes * 4 );
}

1512 1513 1514
static void dump_dir_exceptions(void)
{
    unsigned int i, size = 0;
1515
    const void *funcs = get_dir_and_size(IMAGE_FILE_EXCEPTION_DIRECTORY, &size);
1516 1517 1518 1519
    const IMAGE_FILE_HEADER *file_header = &PE_nt_headers->FileHeader;

    if (!funcs) return;

1520
    switch (file_header->Machine)
1521
    {
1522
    case IMAGE_FILE_MACHINE_AMD64:
1523 1524 1525
        size /= sizeof(struct runtime_function_x86_64);
        printf( "Exception info (%u functions):\n", size );
        for (i = 0; i < size; i++) dump_x86_64_unwind_info( (struct runtime_function_x86_64*)funcs + i );
1526 1527
        break;
    case IMAGE_FILE_MACHINE_ARMNT:
1528
        size /= sizeof(struct runtime_function_armnt);
1529
        printf( "Exception info (%u functions):\n", size );
1530
        for (i = 0; i < size; i++) dump_armnt_unwind_info( (struct runtime_function_armnt*)funcs + i );
1531 1532 1533 1534 1535 1536 1537 1538
        break;
    case IMAGE_FILE_MACHINE_ARM64:
        size /= sizeof(struct runtime_function_arm64);
        printf( "Exception info (%u functions):\n", size );
        for (i = 0; i < size; i++) dump_arm64_unwind_info( (struct runtime_function_arm64*)funcs + i );
        break;
    default:
        printf( "Exception information not supported for %s binaries\n",
1539
                 get_machine_str(file_header->Machine));
1540 1541
        break;
    }
1542 1543 1544
}


1545
static void dump_image_thunk_data64(const IMAGE_THUNK_DATA64 *il, DWORD thunk_rva)
1546 1547
{
    /* FIXME: This does not properly handle large images */
1548
    const IMAGE_IMPORT_BY_NAME* iibn;
1549
    for (; il->u1.Ordinal; il++, thunk_rva += sizeof(LONGLONG))
1550 1551
    {
        if (IMAGE_SNAP_BY_ORDINAL64(il->u1.Ordinal))
1552
            printf("  %08x  %4u  <by ordinal>\n", thunk_rva, (DWORD)IMAGE_ORDINAL64(il->u1.Ordinal));
1553 1554 1555
        else
        {
            iibn = RVA((DWORD)il->u1.AddressOfData, sizeof(DWORD));
1556
            if (!iibn)
1557 1558
                printf("Can't grab import by name info, skipping to next ordinal\n");
            else
1559
                printf("  %08x  %4u  %s\n", thunk_rva, iibn->Hint, iibn->Name);
1560 1561 1562 1563
        }
    }
}

1564
static void dump_image_thunk_data32(const IMAGE_THUNK_DATA32 *il, int offset, DWORD thunk_rva)
1565
{
1566
    const IMAGE_IMPORT_BY_NAME* iibn;
1567
    for (; il->u1.Ordinal; il++, thunk_rva += sizeof(DWORD))
1568 1569
    {
        if (IMAGE_SNAP_BY_ORDINAL32(il->u1.Ordinal))
1570
            printf("  %08x  %4u  <by ordinal>\n", thunk_rva, IMAGE_ORDINAL32(il->u1.Ordinal));
1571 1572
        else
        {
1573
            iibn = RVA((DWORD)il->u1.AddressOfData - offset, sizeof(DWORD));
1574
            if (!iibn)
1575 1576
                printf("Can't grab import by name info, skipping to next ordinal\n");
            else
1577
                printf("  %08x  %4u  %s\n", thunk_rva, iibn->Hint, iibn->Name);
1578 1579 1580 1581
        }
    }
}

1582 1583
static	void	dump_dir_imported_functions(void)
{
1584 1585
    unsigned directorySize;
    const IMAGE_IMPORT_DESCRIPTOR* importDesc = get_dir_and_size(IMAGE_FILE_IMPORT_DIRECTORY, &directorySize);
1586

1587
    if (!importDesc)	return;
1588

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

1591
    for (;;)
1592
    {
1593
	const IMAGE_THUNK_DATA32*	il;
1594

1595 1596
        if (!importDesc->Name || !importDesc->FirstThunk) break;

1597
	printf("  offset %08lx %s\n", Offset(importDesc), (const char*)RVA(importDesc->Name, sizeof(DWORD)));
1598
	printf("  Hint/Name Table: %08X\n", (DWORD)importDesc->u.OriginalFirstThunk);
1599
	printf("  TimeDateStamp:   %08X (%s)\n",
1600
	       importDesc->TimeDateStamp, get_time_str(importDesc->TimeDateStamp));
1601 1602
	printf("  ForwarderChain:  %08X\n", importDesc->ForwarderChain);
	printf("  First thunk RVA: %08X\n", (DWORD)importDesc->FirstThunk);
1603

1604
	printf("   Thunk    Ordn  Name\n");
1605 1606 1607

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

1610 1611
	if (!il)
            printf("Can't grab thunk data, going to next imported DLL\n");
1612
        else
1613 1614
        {
            if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1615
                dump_image_thunk_data64((const IMAGE_THUNK_DATA64*)il, importDesc->FirstThunk);
1616
            else
1617
                dump_image_thunk_data32(il, 0, importDesc->FirstThunk);
1618 1619
            printf("\n");
        }
1620 1621 1622 1623 1624
	importDesc++;
    }
    printf("\n");
}

1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
static void dump_dir_loadconfig(void)
{
    const IMAGE_LOAD_CONFIG_DIRECTORY32 *loadcfg32 = get_dir(IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG);
    const IMAGE_LOAD_CONFIG_DIRECTORY64 *loadcfg64 = (void*)loadcfg32;

    if (!loadcfg32) return;

    printf( "Loadconfig\n" );
    print_dword( "Size",                                loadcfg32->Size );
    print_dword( "TimeDateStamp",                       loadcfg32->TimeDateStamp );
    print_word(  "MajorVersion",                        loadcfg32->MajorVersion );
    print_word(  "MinorVersion",                        loadcfg32->MinorVersion );
    print_dword( "GlobalFlagsClear",                    loadcfg32->GlobalFlagsClear );
    print_dword( "GlobalFlagsSet",                      loadcfg32->GlobalFlagsSet );
    print_dword( "CriticalSectionDefaultTimeout",       loadcfg32->CriticalSectionDefaultTimeout );

    if(PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
    {
        print_longlong( "DeCommitFreeBlockThreshold",   loadcfg64->DeCommitFreeBlockThreshold );
        print_longlong( "DeCommitTotalFreeThreshold",   loadcfg64->DeCommitTotalFreeThreshold );
        print_longlong( "MaximumAllocationSize",        loadcfg64->MaximumAllocationSize );
        print_longlong( "VirtualMemoryThreshold",       loadcfg64->VirtualMemoryThreshold );
        print_dword(    "ProcessHeapFlags",             loadcfg64->ProcessHeapFlags );
        print_longlong( "ProcessAffinityMask",          loadcfg64->ProcessAffinityMask );
        print_word(     "CSDVersion",                   loadcfg64->CSDVersion );
        print_word(     "Reserved",                     loadcfg64->Reserved1 );
        print_longlong( "SecurityCookie",               loadcfg64->SecurityCookie );
        print_longlong( "SEHandlerTable",               loadcfg64->SEHandlerTable );
        print_longlong( "SEHandlerCount",               loadcfg64->SEHandlerCount );
    }
    else
    {
        print_dword( "DeCommitFreeBlockThreshold",      loadcfg32->DeCommitFreeBlockThreshold );
        print_dword( "DeCommitTotalFreeThreshold",      loadcfg32->DeCommitTotalFreeThreshold );
        print_dword( "MaximumAllocationSize",           loadcfg32->MaximumAllocationSize );
        print_dword( "VirtualMemoryThreshold",          loadcfg32->VirtualMemoryThreshold );
        print_dword( "ProcessHeapFlags",                loadcfg32->ProcessHeapFlags );
        print_dword( "ProcessAffinityMask",             loadcfg32->ProcessAffinityMask );
        print_word(  "CSDVersion",                      loadcfg32->CSDVersion );
        print_word(  "Reserved",                        loadcfg32->Reserved1 );
        print_dword( "SecurityCookie",                  loadcfg32->SecurityCookie );
        print_dword( "SEHandlerTable",                  loadcfg32->SEHandlerTable );
        print_dword( "SEHandlerCount",                  loadcfg32->SEHandlerCount );
    }
}

1671 1672
static void dump_dir_delay_imported_functions(void)
{
1673
    unsigned  directorySize;
1674
    const IMAGE_DELAYLOAD_DESCRIPTOR *importDesc = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT, &directorySize);
1675 1676 1677

    if (!importDesc) return;

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

1680
    for (;;)
1681
    {
1682
        const IMAGE_THUNK_DATA32*       il;
1683
        int                             offset = (importDesc->Attributes.AllAttributes & 1) ? 0 : PE_nt_headers->OptionalHeader.ImageBase;
1684

1685
        if (!importDesc->DllNameRVA || !importDesc->ImportAddressTableRVA || !importDesc->ImportNameTableRVA) break;
1686

1687 1688 1689
        printf("  grAttrs %08x offset %08lx %s\n", importDesc->Attributes.AllAttributes, Offset(importDesc),
               (const char *)RVA(importDesc->DllNameRVA - offset, sizeof(DWORD)));
        printf("  Hint/Name Table: %08x\n", importDesc->ImportNameTableRVA);
1690
        printf("  Address Table:   %08x\n", importDesc->ImportAddressTableRVA);
1691
        printf("  TimeDateStamp:   %08X (%s)\n",
1692
               importDesc->TimeDateStamp, get_time_str(importDesc->TimeDateStamp));
1693

1694
        printf("   Thunk    Ordn  Name\n");
1695

1696
        il = RVA(importDesc->ImportNameTableRVA - offset, sizeof(DWORD));
1697 1698 1699 1700

        if (!il)
            printf("Can't grab thunk data, going to next imported DLL\n");
        else
1701 1702
        {
            if (PE_nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
1703
                dump_image_thunk_data64((const IMAGE_THUNK_DATA64 *)il, importDesc->ImportAddressTableRVA);
1704
            else
1705
                dump_image_thunk_data32(il, offset, importDesc->ImportAddressTableRVA);
1706 1707
            printf("\n");
        }
1708 1709 1710 1711 1712
        importDesc++;
    }
    printf("\n");
}

1713
static	void	dump_dir_debug_dir(const IMAGE_DEBUG_DIRECTORY* idd, int idx)
1714 1715
{
    const	char*	str;
1716

1717
    printf("Directory %02u\n", idx + 1);
1718 1719
    printf("  Characteristics:   %08X\n", idd->Characteristics);
    printf("  TimeDateStamp:     %08X %s\n",
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
	   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;
1736
    case IMAGE_DEBUG_TYPE_CLSID:	str = "CLSID"; 	break;
1737 1738 1739 1740
    case IMAGE_DEBUG_TYPE_VC_FEATURE:  str = "VC_FEATURE"; break;
    case IMAGE_DEBUG_TYPE_POGO:        str = "POGO";       break;
    case IMAGE_DEBUG_TYPE_ILTCG:       str = "ILTCG";      break;
    case IMAGE_DEBUG_TYPE_MPX:         str = "MPX";        break;
1741
    case IMAGE_DEBUG_TYPE_REPRO:       str = "REPRO";      break;
1742
    }
1743 1744 1745 1746
    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);
1747

1748 1749
    switch (idd->Type)
    {
1750
    case IMAGE_DEBUG_TYPE_UNKNOWN:
1751
	break;
1752
    case IMAGE_DEBUG_TYPE_COFF:
1753 1754
	dump_coff(idd->PointerToRawData, idd->SizeOfData,
                  IMAGE_FIRST_SECTION(PE_nt_headers));
1755 1756 1757 1758
	break;
    case IMAGE_DEBUG_TYPE_CODEVIEW:
	dump_codeview(idd->PointerToRawData, idd->SizeOfData);
	break;
1759
    case IMAGE_DEBUG_TYPE_FPO:
1760
	dump_frame_pointer_omission(idd->PointerToRawData, idd->SizeOfData);
1761 1762 1763
	break;
    case IMAGE_DEBUG_TYPE_MISC:
    {
1764
	const IMAGE_DEBUG_MISC* misc = PRD(idd->PointerToRawData, idd->SizeOfData);
1765
	if (!misc) {printf("Can't get misc debug information\n"); break;}
1766
	printf("    DataType:          %u (%s)\n",
1767
	       misc->DataType,
1768
	       (misc->DataType == IMAGE_DEBUG_MISC_EXENAME) ? "Exe name" : "Unknown");
1769
	printf("    Length:            %u\n", misc->Length);
1770 1771 1772 1773
	printf("    Unicode:           %s\n", misc->Unicode ? "Yes" : "No");
	printf("    Data:              %s\n", misc->Data);
    }
    break;
1774
    default: break;
1775 1776 1777 1778 1779 1780 1781
    }
    printf("\n");
}

static void	dump_dir_debug(void)
{
    unsigned			nb_dbg, i;
1782
    const IMAGE_DEBUG_DIRECTORY*debugDir = get_dir_and_size(IMAGE_FILE_DEBUG_DIRECTORY, &nb_dbg);
1783

1784 1785
    nb_dbg /= sizeof(*debugDir);
    if (!debugDir || !nb_dbg) return;
1786

1787
    printf("Debug Table (%u directories)\n", nb_dbg);
1788

1789 1790 1791 1792 1793 1794 1795 1796
    for (i = 0; i < nb_dbg; i++)
    {
	dump_dir_debug_dir(debugDir, i);
	debugDir++;
    }
    printf("\n");
}

1797
static inline void print_clrflags(const char *title, DWORD value)
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
{
    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 );
1825
    print_dword( "EntryPointToken", dir->u.EntryPointToken );
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
    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");
}

1838 1839 1840 1841 1842
static void dump_dir_reloc(void)
{
    unsigned int i, size = 0;
    const USHORT *relocs;
    const IMAGE_BASE_RELOCATION *rel = get_dir_and_size(IMAGE_DIRECTORY_ENTRY_BASERELOC, &size);
1843
    const IMAGE_BASE_RELOCATION *end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + size);
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
    static const char * const names[] =
    {
        "BASED_ABSOLUTE",
        "BASED_HIGH",
        "BASED_LOW",
        "BASED_HIGHLOW",
        "BASED_HIGHADJ",
        "BASED_MIPS_JMPADDR",
        "BASED_SECTION",
        "BASED_REL",
        "unknown 8",
        "BASED_IA64_IMM64",
        "BASED_DIR64",
        "BASED_HIGH3ADJ",
        "unknown 12",
        "unknown 13",
        "unknown 14",
        "unknown 15"
    };

    if (!rel) return;

    printf( "Relocations\n" );
    while (rel < end - 1 && rel->SizeOfBlock)
    {
        printf( "  Page %x\n", rel->VirtualAddress );
        relocs = (const USHORT *)(rel + 1);
        i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT);
        while (i--)
        {
            USHORT offset = *relocs & 0xfff;
            int type = *relocs >> 12;
            printf( "    off %04x type %s\n", offset, names[type] );
            relocs++;
        }
        rel = (const IMAGE_BASE_RELOCATION *)relocs;
    }
    printf("\n");
}

1884 1885
static void dump_dir_tls(void)
{
1886
    IMAGE_TLS_DIRECTORY64 dir;
1887
    const DWORD *callbacks;
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
    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;
    }
1903

1904
    /* FIXME: This does not properly handle large images */
1905
    printf( "Thread Local Storage\n" );
1906
    printf( "  Raw data        %08x-%08x (data size %x zero fill size %x)\n",
1907 1908 1909
            (DWORD)dir.StartAddressOfRawData, (DWORD)dir.EndAddressOfRawData,
            (DWORD)(dir.EndAddressOfRawData - dir.StartAddressOfRawData),
            (DWORD)dir.SizeOfZeroFill );
1910 1911 1912
    printf( "  Index address   %08x\n", (DWORD)dir.AddressOfIndex );
    printf( "  Characteristics %08x\n", dir.Characteristics );
    printf( "  Callbacks       %08x -> {", (DWORD)dir.AddressOfCallBacks );
1913
    if (dir.AddressOfCallBacks)
1914
    {
1915
        DWORD   addr = (DWORD)dir.AddressOfCallBacks - PE_nt_headers->OptionalHeader.ImageBase;
1916 1917
        while ((callbacks = RVA(addr, sizeof(DWORD))) && *callbacks)
        {
1918
            printf( " %08x", *callbacks );
1919 1920
            addr += sizeof(DWORD);
        }
1921 1922 1923 1924
    }
    printf(" }\n\n");
}

1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
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;
}

1936
void	dbg_dump(void)
1937
{
1938 1939 1940 1941
    const IMAGE_SEPARATE_DEBUG_HEADER*  separateDebugHead;
    unsigned			        nb_dbg;
    unsigned			        i;
    const IMAGE_DEBUG_DIRECTORY*	debugDir;
1942

1943
    separateDebugHead = PRD(0, sizeof(*separateDebugHead));
1944
    if (!separateDebugHead) {printf("Can't grab the separate header, aborting\n"); return;}
1945 1946

    printf ("Signature:          %.2s (0x%4X)\n",
1947
	    (const char*)&separateDebugHead->Signature, separateDebugHead->Signature);
1948
    printf ("Flags:              0x%04X\n", separateDebugHead->Flags);
1949
    printf ("Machine:            0x%04X (%s)\n",
1950 1951
	    separateDebugHead->Machine, get_machine_str(separateDebugHead->Machine));
    printf ("Characteristics:    0x%04X\n", separateDebugHead->Characteristics);
1952
    printf ("TimeDateStamp:      0x%08X (%s)\n",
1953
	    separateDebugHead->TimeDateStamp, get_time_str(separateDebugHead->TimeDateStamp));
1954 1955 1956 1957 1958 1959
    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);
1960 1961

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

1965
    dump_sections(separateDebugHead, separateDebugHead + 1, separateDebugHead->NumberOfSections);
1966

1967
    nb_dbg = separateDebugHead->DebugDirectorySize / sizeof(IMAGE_DEBUG_DIRECTORY);
1968
    debugDir = PRD(sizeof(IMAGE_SEPARATE_DEBUG_HEADER) +
1969 1970 1971 1972
		   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;}
1973

1974
    printf("Debug Table (%u directories)\n", nb_dbg);
1975

1976 1977 1978 1979 1980 1981 1982
    for (i = 0; i < nb_dbg; i++)
    {
	dump_dir_debug_dir(debugDir, i);
	debugDir++;
    }
}

1983
static const char *get_resource_type( unsigned int id )
1984
{
1985
    static const char * const types[] =
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
    {
        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",
2010 2011
        "HTML",
        "RT_MANIFEST"
2012 2013
    };

2014
    if ((size_t)id < ARRAY_SIZE(types)) return types[id];
2015 2016 2017
    return NULL;
}

2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
/* 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;
}

2058
/* dump a Unicode string with proper escaping */
2059
static int dump_strW( const WCHAR *str, size_t len )
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
{
    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 */
2102
static void dump_string_data( const WCHAR *ptr, unsigned int size, unsigned int id, const char *prefix )
2103 2104 2105 2106 2107
{
    int i;

    for (i = 0; i < 16 && size; i++)
    {
2108
        unsigned len = *ptr++;
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126

        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;
        }
    }
}

2127 2128 2129 2130 2131
/* 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;
2132
    unsigned i, j;
2133 2134 2135 2136 2137

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

2138
        entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)data + block->OffsetToEntries);
2139 2140 2141 2142
        for (j = block->LowId; j <= block->HighId; j++)
        {
            if (entry->Flags & MESSAGE_RESOURCE_UNICODE)
            {
2143
                const WCHAR *str = (const WCHAR *)entry->Text;
2144 2145 2146 2147 2148 2149
                printf( "%s%08x L\"", prefix, j );
                dump_strW( str, strlenW(str) );
                printf( "\"\n" );
            }
            else
            {
Mike McCormack's avatar
Mike McCormack committed
2150
                const char *str = (const char *) entry->Text;
2151
                printf( "%s%08x \"", prefix, j );
Mike McCormack's avatar
Mike McCormack committed
2152
                dump_strA( entry->Text, strlen(str) );
2153 2154
                printf( "\"\n" );
            }
2155
            entry = (const MESSAGE_RESOURCE_ENTRY *)((const char *)entry + entry->Length);
2156 2157 2158 2159
        }
    }
}

2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
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++)
    {
2176
        e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
2177
        namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s2.OffsetToDirectory);
2178 2179
        for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
        {
2180
            e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
2181
            langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s2.OffsetToDirectory);
2182 2183
            for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
            {
2184
                e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
2185 2186

                printf( "\n  " );
2187
                if (e1->u.s.NameIsString)
2188
                {
2189
                    string = (const IMAGE_RESOURCE_DIR_STRING_U*)((const char *)root + e1->u.s.NameOffset);
2190 2191 2192 2193
                    dump_unicode_str( string->NameString, string->Length );
                }
                else
                {
2194
                    const char *type = get_resource_type( e1->u.Id );
2195
                    if (type) printf( "%s", type );
2196
                    else printf( "%04x", e1->u.Id );
2197 2198 2199
                }

                printf( " Name=" );
2200
                if (e2->u.s.NameIsString)
2201
                {
2202
                    string = (const IMAGE_RESOURCE_DIR_STRING_U*) ((const char *)root + e2->u.s.NameOffset);
2203 2204 2205
                    dump_unicode_str( string->NameString, string->Length );
                }
                else
2206
                    printf( "%04x", e2->u.Id );
2207

2208
                printf( " Language=%04x:\n", e3->u.Id );
2209
                data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
2210
                if (e1->u.s.NameIsString)
2211
                {
2212
                    dump_data( RVA( data->OffsetToData, data->Size ), data->Size, "    " );
2213
                }
2214
                else switch(e1->u.Id)
2215 2216
                {
                case 6:
2217
                    dump_string_data( RVA( data->OffsetToData, data->Size ), data->Size,                                      e2->u.Id, "    " );
2218 2219 2220
                    break;
                case 11:
                    dump_msgtable_data( RVA( data->OffsetToData, data->Size ), data->Size,
2221
                                        e2->u.Id, "    " );
2222 2223
                    break;
                default:
2224
                    dump_data( RVA( data->OffsetToData, data->Size ), data->Size, "    " );
2225 2226
                    break;
                }
2227 2228 2229 2230 2231 2232
            }
        }
    }
    printf( "\n\n" );
}

2233 2234 2235 2236 2237 2238 2239 2240 2241
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;

2242
    sectHead = IMAGE_FIRST_SECTION(PE_nt_headers);
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260

    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);
}

2261 2262 2263 2264 2265 2266 2267 2268
static void dump_symbol_table(void)
{
    const IMAGE_SYMBOL* sym;
    int                 numsym;

    numsym = PE_nt_headers->FileHeader.NumberOfSymbols;
    if (!PE_nt_headers->FileHeader.PointerToSymbolTable || !numsym)
        return;
2269
    sym = PRD(PE_nt_headers->FileHeader.PointerToSymbolTable,
2270 2271 2272 2273 2274 2275
                                   sizeof(*sym) * numsym);
    if (!sym) return;

    dump_coff_symbol_table(sym, numsym, IMAGE_FIRST_SECTION(PE_nt_headers));
}

2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
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;
        }
2297
        return SIG_DOS;
2298
    }
2299
    return SIG_UNKNOWN;
2300 2301
}

2302
void pe_dump(void)
2303 2304 2305
{
    int	all = (globals.dumpsect != NULL) && strcmp(globals.dumpsect, "ALL") == 0;

2306
    PE_nt_headers = get_nt_header();
2307
    print_fake_dll();
2308

2309 2310 2311
    if (globals.do_dumpheader)
    {
	dump_pe_header();
2312
	/* FIXME: should check ptr */
2313
	dump_sections(PRD(0, 1), IMAGE_FIRST_SECTION(PE_nt_headers),
2314
		      PE_nt_headers->FileHeader.NumberOfSections);
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
    }
    else if (!globals.dumpsect)
    {
	/* show at least something here */
	dump_pe_header();
    }

    if (globals.dumpsect)
    {
	if (all || !strcmp(globals.dumpsect, "import"))
2325
        {
2326
	    dump_dir_imported_functions();
2327 2328
	    dump_dir_delay_imported_functions();
        }
2329 2330 2331 2332 2333 2334
	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();
2335 2336
	if (all || !strcmp(globals.dumpsect, "tls"))
	    dump_dir_tls();
2337 2338
	if (all || !strcmp(globals.dumpsect, "loadcfg"))
	    dump_dir_loadconfig();
2339 2340
	if (all || !strcmp(globals.dumpsect, "clr"))
	    dump_dir_clr_header();
2341 2342
	if (all || !strcmp(globals.dumpsect, "reloc"))
	    dump_dir_reloc();
2343 2344
	if (all || !strcmp(globals.dumpsect, "except"))
	    dump_dir_exceptions();
2345
    }
2346 2347
    if (globals.do_symbol_table)
        dump_symbol_table();
2348 2349
    if (globals.do_debug)
        dump_debug();
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
}

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)
{
2363
    return ((const dll_symbol *)left)->ordinal > ((const dll_symbol *)right)->ordinal;
2364 2365 2366 2367 2368 2369 2370
}

/*******************************************************************
 *         dll_close
 *
 * Free resources used by DLL
 */
2371
/* FIXME: Not used yet
2372 2373 2374
static void dll_close (void)
{
    dll_symbol*	ds;
2375 2376 2377

    if (!dll_symbols) {
	fatal("No symbols");
2378
    }
2379 2380 2381 2382 2383
    for (ds = dll_symbols; ds->symbol; ds++)
	free(ds->symbol);
    free (dll_symbols);
    dll_symbols = NULL;
}
2384
*/
2385

2386
static	void	do_grab_sym( void )
2387
{
2388
    const IMAGE_EXPORT_DIRECTORY*exportDir;
2389
    unsigned			i, j;
2390 2391 2392
    const DWORD*		pName;
    const DWORD*		pFunc;
    const WORD* 		pOrdl;
2393
    const char*			ptr;
2394
    DWORD*			map;
2395

2396
    PE_nt_headers = get_nt_header();
2397
    if (!(exportDir = get_dir(IMAGE_FILE_EXPORT_DIRECTORY))) return;
2398

2399 2400 2401 2402
    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;}
2403 2404
    pFunc = RVA(exportDir->AddressOfFunctions, exportDir->NumberOfFunctions * sizeof(DWORD));
    if (!pFunc) {printf("Can't grab functions' address table\n"); return;}
2405

2406
    /* dll_close(); */
2407

2408
    if (!(dll_symbols = malloc((exportDir->NumberOfFunctions + 1) * sizeof(dll_symbol))))
2409
	fatal ("Out of memory");
2410

2411 2412 2413
    /* bit map of used funcs */
    map = calloc(((exportDir->NumberOfFunctions + 31) & ~31) / 32, sizeof(DWORD));
    if (!map) fatal("no memory");
2414

2415
    for (j = 0; j < exportDir->NumberOfNames; j++, pOrdl++)
2416 2417 2418 2419
    {
	map[*pOrdl / 32] |= 1 << (*pOrdl % 32);
	ptr = RVA(*pName++, sizeof(DWORD));
	if (!ptr) ptr = "cant_get_function";
2420
	dll_symbols[j].symbol = strdup(ptr);
2421
	dll_symbols[j].ordinal = exportDir->Base + *pOrdl;
2422
	assert(dll_symbols[j].symbol);
2423
    }
2424

2425 2426
    for (i = 0; i < exportDir->NumberOfFunctions; i++)
    {
2427
	if (pFunc[i] && !(map[i / 32] & (1 << (i % 32))))
2428 2429 2430
	{
	    char ordinal_text[256];
	    /* Ordinal only entry */
2431
            snprintf (ordinal_text, sizeof(ordinal_text), "%s_%u",
2432 2433 2434
		      globals.forward_dll ? globals.forward_dll : OUTPUT_UC_DLL_NAME,
		      exportDir->Base + i);
	    str_toupper(ordinal_text);
2435 2436 2437 2438 2439
	    dll_symbols[j].symbol = strdup(ordinal_text);
	    assert(dll_symbols[j].symbol);
	    dll_symbols[j].ordinal = exportDir->Base + i;
	    j++;
	    assert(j <= exportDir->NumberOfFunctions);
2440 2441 2442
	}
    }
    free(map);
2443

2444
    if (NORMAL)
2445
	printf("%u named symbols in DLL, %u total, %d unique (ordinal base = %d)\n",
2446
	       exportDir->NumberOfNames, exportDir->NumberOfFunctions, j, exportDir->Base);
2447

2448
    qsort( dll_symbols, j, sizeof(dll_symbol), symbol_cmp );
2449

2450
    dll_symbols[j].symbol = NULL;
2451

2452 2453 2454 2455 2456 2457 2458 2459
    dll_current_symbol = dll_symbols;
}

/*******************************************************************
 *         dll_open
 *
 * Open a DLL and read in exported symbols
 */
2460
BOOL dll_open (const char *dll_name)
2461
{
2462
    return dump_analysis(dll_name, do_grab_sym, SIG_PE);
2463 2464 2465 2466 2467 2468 2469
}

/*******************************************************************
 *         dll_next_symbol
 *
 * Get next exported symbol from dll
 */
2470
BOOL dll_next_symbol (parsed_symbol * sym)
2471
{
2472
    if (!dll_current_symbol || !dll_current_symbol->symbol)
2473
       return FALSE;
2474
     assert (dll_symbols);
2475 2476 2477
    sym->symbol = strdup (dll_current_symbol->symbol);
    sym->ordinal = dll_current_symbol->ordinal;
    dll_current_symbol++;
2478
    return TRUE;
2479
}