pe_module.c 31.9 KB
Newer Older
1 2 3 4 5
/*
 * File pe_module.c - handle PE module information
 *
 * Copyright (C) 1996,      Eric Youngdale.
 * Copyright (C) 1999-2000, Ulrich Weigand.
6
 * Copyright (C) 2004-2007, Eric Pouech.
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * 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
20
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 22 23 24
 *
 */

#include "config.h"
25 26
#include "wine/port.h"

27 28 29 30 31 32
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>

#include "dbghelp_private.h"
33
#include "image_private.h"
34 35 36 37 38
#include "winternl.h"
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(dbghelp);

39 40 41 42 43
struct pe_module_info
{
    struct image_file_map       fmap;
};

44
static void* pe_map_full(struct image_file_map* fmap, IMAGE_NT_HEADERS** nth)
45
{
46
    if (!fmap->u.pe.full_map)
47
    {
48
        fmap->u.pe.full_map = MapViewOfFile(fmap->u.pe.hMap, FILE_MAP_READ, 0, 0, 0);
49
    }
50
    if (fmap->u.pe.full_map)
51
    {
52 53 54
        if (nth) *nth = RtlImageNtHeader(fmap->u.pe.full_map);
        fmap->u.pe.full_count++;
        return fmap->u.pe.full_map;
55 56 57 58
    }
    return IMAGE_NO_MAP;
}

59
static void pe_unmap_full(struct image_file_map* fmap)
60
{
61
    if (fmap->u.pe.full_count && !--fmap->u.pe.full_count)
62
    {
63 64
        UnmapViewOfFile(fmap->u.pe.full_map);
        fmap->u.pe.full_map = NULL;
65 66 67 68 69 70 71 72
    }
}

/******************************************************************
 *		pe_map_section
 *
 * Maps a single section into memory from an PE file
 */
73
const char* pe_map_section(struct image_section_map* ism)
74 75
{
    void*       mapping;
76
    struct pe_file_map* fmap = &ism->fmap->u.pe;
77

78 79
    if (ism->sidx >= 0 && ism->sidx < fmap->ntheader.FileHeader.NumberOfSections &&
        fmap->sect[ism->sidx].mapped == IMAGE_NO_MAP)
80 81
    {
        IMAGE_NT_HEADERS*       nth;
82 83 84 85 86 87 88 89

        if (fmap->sect[ism->sidx].shdr.Misc.VirtualSize > fmap->sect[ism->sidx].shdr.SizeOfRawData)
        {
            FIXME("Section %ld: virtual (0x%x) > raw (0x%x) size - not supported\n",
                  ism->sidx, fmap->sect[ism->sidx].shdr.Misc.VirtualSize,
                  fmap->sect[ism->sidx].shdr.SizeOfRawData);
            return IMAGE_NO_MAP;
        }
90
        /* FIXME: that's rather drastic, but that will do for now
91
         * that's ok if the full file map exists, but we could be less aggressive otherwise and
92 93
         * only map the relevant section
         */
94
        if ((mapping = pe_map_full(ism->fmap, &nth)))
95
        {
96 97 98 99
            fmap->sect[ism->sidx].mapped = RtlImageRvaToVa(nth, mapping,
                                                           fmap->sect[ism->sidx].shdr.VirtualAddress,
                                                           NULL);
            return fmap->sect[ism->sidx].mapped;
100 101 102 103 104 105 106 107 108 109 110
        }
    }
    return IMAGE_NO_MAP;
}

/******************************************************************
 *		pe_find_section
 *
 * Finds a section by name (and type) into memory from an PE file
 * or its alternate if any
 */
111 112
BOOL pe_find_section(struct image_file_map* fmap, const char* name,
                     struct image_section_map* ism)
113 114 115 116 117
{
    const char*                 sectname;
    unsigned                    i;
    char                        tmp[IMAGE_SIZEOF_SHORT_NAME + 1];

118
    for (i = 0; i < fmap->u.pe.ntheader.FileHeader.NumberOfSections; i++)
119
    {
120
        sectname = (const char*)fmap->u.pe.sect[i].shdr.Name;
121
        /* long section names start with a '/' (at least on MinGW32) */
122 123
        if (sectname[0] == '/' && fmap->u.pe.strtable)
            sectname = fmap->u.pe.strtable + atoi(sectname + 1);
124 125 126 127 128 129 130 131
        else
        {
            /* the section name may not be null terminated */
            sectname = memcpy(tmp, sectname, IMAGE_SIZEOF_SHORT_NAME);
            tmp[IMAGE_SIZEOF_SHORT_NAME] = '\0';
        }
        if (!strcasecmp(sectname, name))
        {
132 133
            ism->fmap = fmap;
            ism->sidx = i;
134 135 136
            return TRUE;
        }
    }
137 138 139
    ism->fmap = NULL;
    ism->sidx = -1;

140 141 142 143 144 145 146 147
    return FALSE;
}

/******************************************************************
 *		pe_unmap_section
 *
 * Unmaps a single section from memory
 */
148
void pe_unmap_section(struct image_section_map* ism)
149
{
150 151
    if (ism->sidx >= 0 && ism->sidx < ism->fmap->u.pe.ntheader.FileHeader.NumberOfSections &&
        ism->fmap->u.pe.sect[ism->sidx].mapped != IMAGE_NO_MAP)
152
    {
153 154
        pe_unmap_full(ism->fmap);
        ism->fmap->u.pe.sect[ism->sidx].mapped = IMAGE_NO_MAP;
155 156 157
    }
}

158 159 160 161 162 163 164 165 166 167 168 169
/******************************************************************
 *		pe_get_map_rva
 *
 * Get the RVA of an PE section
 */
DWORD_PTR pe_get_map_rva(const struct image_section_map* ism)
{
    if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.pe.ntheader.FileHeader.NumberOfSections)
        return 0;
    return ism->fmap->u.pe.sect[ism->sidx].shdr.VirtualAddress;
}

170 171 172
/******************************************************************
 *		pe_get_map_size
 *
173
 * Get the size of a PE section
174
 */
175
unsigned pe_get_map_size(const struct image_section_map* ism)
176
{
177
    if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.pe.ntheader.FileHeader.NumberOfSections)
178
        return 0;
179
    return ism->fmap->u.pe.sect[ism->sidx].shdr.Misc.VirtualSize;
180 181
}

182 183 184 185 186 187
/******************************************************************
 *		pe_is_valid_pointer_table
 *
 * Checks whether the PointerToSymbolTable and NumberOfSymbols in file_header contain
 * valid information.
 */
188
static BOOL pe_is_valid_pointer_table(const IMAGE_NT_HEADERS* nthdr, const void* mapping, DWORD64 sz)
189 190 191
{
    DWORD64     offset;

192
    /* is the iSym table inside file size ? (including first DWORD of string table, which is its size) */
193
    offset = (DWORD64)nthdr->FileHeader.PointerToSymbolTable;
194 195
    offset += (DWORD64)nthdr->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL);
    if (offset + sizeof(DWORD) > sz) return FALSE;
196
    /* is string table (following iSym table) inside file size ? */
197
    offset += *(DWORD*)((const char*)mapping + offset);
198
    return offset <= sz;
199 200
}

201 202 203 204 205
/******************************************************************
 *		pe_map_file
 *
 * Maps an PE file into memory (and checks it's a real PE file)
 */
206
static BOOL pe_map_file(HANDLE file, struct image_file_map* fmap, enum module_type mt)
207 208 209
{
    void*       mapping;

210 211 212 213 214
    fmap->modtype = mt;
    fmap->u.pe.hMap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
    if (fmap->u.pe.hMap == 0) return FALSE;
    fmap->u.pe.full_count = 0;
    fmap->u.pe.full_map = NULL;
215 216 217 218 219 220 221 222 223 224 225
    if (!(mapping = pe_map_full(fmap, NULL))) goto error;

    switch (mt)
    {
    case DMT_PE:
        {
            IMAGE_NT_HEADERS*       nthdr;
            IMAGE_SECTION_HEADER*   section;
            unsigned                i;

            if (!(nthdr = RtlImageNtHeader(mapping))) goto error;
226
            memcpy(&fmap->u.pe.ntheader, nthdr, sizeof(fmap->u.pe.ntheader));
227 228 229 230 231 232
            switch (nthdr->OptionalHeader.Magic)
            {
            case 0x10b: fmap->addr_size = 32; break;
            case 0x20b: fmap->addr_size = 64; break;
            default: return FALSE;
            }
233 234
            section = (IMAGE_SECTION_HEADER*)
                ((char*)&nthdr->OptionalHeader + nthdr->FileHeader.SizeOfOptionalHeader);
235 236 237
            fmap->u.pe.sect = HeapAlloc(GetProcessHeap(), 0,
                                        nthdr->FileHeader.NumberOfSections * sizeof(fmap->u.pe.sect[0]));
            if (!fmap->u.pe.sect) goto error;
238 239
            for (i = 0; i < nthdr->FileHeader.NumberOfSections; i++)
            {
240 241
                memcpy(&fmap->u.pe.sect[i].shdr, section + i, sizeof(IMAGE_SECTION_HEADER));
                fmap->u.pe.sect[i].mapped = IMAGE_NO_MAP;
242 243 244
            }
            if (nthdr->FileHeader.PointerToSymbolTable && nthdr->FileHeader.NumberOfSymbols)
            {
245 246 247
                LARGE_INTEGER li;

                if (GetFileSizeEx(file, &li) && pe_is_valid_pointer_table(nthdr, mapping, li.QuadPart))
248 249 250 251 252 253 254 255 256 257 258 259 260 261
                {
                    /* FIXME ugly: should rather map the relevant content instead of copying it */
                    const char* src = (const char*)mapping +
                        nthdr->FileHeader.PointerToSymbolTable +
                        nthdr->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL);
                    char* dst;
                    DWORD sz = *(DWORD*)src;

                    if ((dst = HeapAlloc(GetProcessHeap(), 0, sz)))
                        memcpy(dst, src, sz);
                    fmap->u.pe.strtable = dst;
                }
                else
                {
262
                    WARN("Bad coff table... wipping out\n");
263 264 265 266 267
                    /* we have bad information here, wipe it out */
                    fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable = 0;
                    fmap->u.pe.ntheader.FileHeader.NumberOfSymbols = 0;
                    fmap->u.pe.strtable = NULL;
                }
268
            }
269
            else fmap->u.pe.strtable = NULL;
270 271 272 273 274 275 276 277 278
        }
        break;
    default: assert(0); goto error;
    }
    pe_unmap_full(fmap);

    return TRUE;
error:
    pe_unmap_full(fmap);
279
    CloseHandle(fmap->u.pe.hMap);
280 281 282 283 284 285 286 287
    return FALSE;
}

/******************************************************************
 *		pe_unmap_file
 *
 * Unmaps an PE file from memory (previously mapped with pe_map_file)
 */
288
static void pe_unmap_file(struct image_file_map* fmap)
289
{
290
    if (fmap->u.pe.hMap != 0)
291
    {
292 293 294
        struct image_section_map  ism;
        ism.fmap = fmap;
        for (ism.sidx = 0; ism.sidx < fmap->u.pe.ntheader.FileHeader.NumberOfSections; ism.sidx++)
295
        {
296
            pe_unmap_section(&ism);
297
        }
298 299 300 301
        while (fmap->u.pe.full_count) pe_unmap_full(fmap);
        HeapFree(GetProcessHeap(), 0, fmap->u.pe.sect);
        HeapFree(GetProcessHeap(), 0, (void*)fmap->u.pe.strtable); /* FIXME ugly (see pe_map_file) */
        CloseHandle(fmap->u.pe.hMap);
302
        fmap->u.pe.hMap = NULL;
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 328 329 330 331 332 333 334
/******************************************************************
 *		pe_map_directory
 *
 * Maps a directory content out of a PE file
 */
const char* pe_map_directory(struct module* module, int dirno, DWORD* size)
{
    IMAGE_NT_HEADERS*   nth;
    void*               mapping;

    if (module->type != DMT_PE || !module->format_info[DFI_PE]) return NULL;
    if (dirno >= IMAGE_NUMBEROF_DIRECTORY_ENTRIES ||
        !(mapping = pe_map_full(&module->format_info[DFI_PE]->u.pe_info->fmap, &nth)))
        return NULL;
    if (size) *size = nth->OptionalHeader.DataDirectory[dirno].Size;
    return RtlImageRvaToVa(nth, mapping,
                           nth->OptionalHeader.DataDirectory[dirno].VirtualAddress, NULL);
}

/******************************************************************
 *		pe_unmap_directory
 *
 * Unmaps a directory content
 */
void pe_unmap_directory(struct image_file_map* fmap, int dirno)
{
    pe_unmap_full(fmap);
}

335
static void pe_module_remove(struct process* pcs, struct module_format* modfmt)
336
{
337 338
    pe_unmap_file(&modfmt->u.pe_info->fmap);
    HeapFree(GetProcessHeap(), 0, modfmt);
339 340
}

341
/******************************************************************
342
 *		pe_locate_with_coff_symbol_table
343 344 345 346 347 348
 *
 * Use the COFF symbol table (if any) from the IMAGE_FILE_HEADER to set the absolute address
 * of global symbols.
 * Mingw32 requires this for stabs debug information as address for global variables isn't filled in
 * (this is similar to what is done in elf_module.c when using the .symtab ELF section)
 */
349
static BOOL pe_locate_with_coff_symbol_table(struct module* module)
350
{
351
    struct image_file_map* fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
352 353 354 355 356 357 358
    const IMAGE_SYMBOL* isym;
    int                 i, numsym, naux;
    char                tmp[9];
    const char*         name;
    struct hash_table_iter      hti;
    void*               ptr;
    struct symt_data*   sym;
359
    const char*         mapping;
360

361 362
    numsym = fmap->u.pe.ntheader.FileHeader.NumberOfSymbols;
    if (!fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable || !numsym)
363
        return TRUE;
364
    if (!(mapping = pe_map_full(fmap, NULL))) return FALSE;
365
    isym = (const IMAGE_SYMBOL*)(mapping + fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable);
366 367 368 369

    for (i = 0; i < numsym; i+= naux, isym += naux)
    {
        if (isym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL &&
370
            isym->SectionNumber > 0 && isym->SectionNumber <= fmap->u.pe.ntheader.FileHeader.NumberOfSections)
371 372 373 374 375 376
        {
            if (isym->N.Name.Short)
            {
                name = memcpy(tmp, isym->N.ShortName, 8);
                tmp[8] = '\0';
            }
377
            else name = fmap->u.pe.strtable + isym->N.Name.Long;
378 379 380 381 382 383 384
            if (name[0] == '_') name++;
            hash_table_iter_init(&module->ht_symbols, &hti, name);
            while ((ptr = hash_table_iter_up(&hti)))
            {
                sym = GET_ENTRY(ptr, struct symt_data, hash_elt);
                if (sym->symt.tag == SymTagData &&
                    (sym->kind == DataIsGlobal || sym->kind == DataIsFileStatic) &&
385
                    sym->u.var.kind == loc_absolute &&
386 387 388 389 390
                    !strcmp(sym->hash_elt.name, name))
                {
                    TRACE("Changing absolute address for %d.%s: %lx -> %s\n",
                          isym->SectionNumber, name, sym->u.var.offset,
                          wine_dbgstr_longlong(module->module.BaseOfImage +
391
                                               fmap->u.pe.sect[isym->SectionNumber - 1].shdr.VirtualAddress +
392
                                               isym->Value));
393
                    sym->u.var.offset = module->module.BaseOfImage +
394
                        fmap->u.pe.sect[isym->SectionNumber - 1].shdr.VirtualAddress + isym->Value;
395 396 397 398 399 400
                    break;
                }
            }
        }
        naux = isym->NumberOfAuxSymbols + 1;
    }
401
    pe_unmap_full(fmap);
402 403 404
    return TRUE;
}

405 406 407 408 409
/******************************************************************
 *		pe_load_coff_symbol_table
 *
 * Load public symbols out of the COFF symbol table (if any).
 */
410
static BOOL pe_load_coff_symbol_table(struct module* module)
411
{
412
    struct image_file_map* fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
413 414 415 416 417 418 419 420
    const IMAGE_SYMBOL* isym;
    int                 i, numsym, naux;
    const char*         strtable;
    char                tmp[9];
    const char*         name;
    const char*         lastfilename = NULL;
    struct symt_compiland*   compiland = NULL;
    const IMAGE_SECTION_HEADER* sect;
421
    const char*         mapping;
422

423 424
    numsym = fmap->u.pe.ntheader.FileHeader.NumberOfSymbols;
    if (!fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable || !numsym)
425
        return TRUE;
426
    if (!(mapping = pe_map_full(fmap, NULL))) return FALSE;
427
    isym = (const IMAGE_SYMBOL*)((const char*)mapping + fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable);
428 429
    /* FIXME: no way to get strtable size */
    strtable = (const char*)&isym[numsym];
430
    sect = IMAGE_FIRST_SECTION(RtlImageNtHeader((HMODULE)mapping));
431 432 433 434 435 436 437 438 439

    for (i = 0; i < numsym; i+= naux, isym += naux)
    {
        if (isym->StorageClass == IMAGE_SYM_CLASS_FILE)
        {
            lastfilename = (const char*)(isym + 1);
            compiland = NULL;
        }
        if (isym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL &&
440
            isym->SectionNumber > 0 && isym->SectionNumber <= fmap->u.pe.ntheader.FileHeader.NumberOfSections)
441 442 443 444 445 446 447 448 449 450 451 452
        {
            if (isym->N.Name.Short)
            {
                name = memcpy(tmp, isym->N.ShortName, 8);
                tmp[8] = '\0';
            }
            else name = strtable + isym->N.Name.Long;
            if (name[0] == '_') name++;

            if (!compiland && lastfilename)
                compiland = symt_new_compiland(module, 0,
                                               source_new(module, NULL, lastfilename));
453 454 455 456 457 458

            if (!(dbghelp_options & SYMOPT_NO_PUBLICS))
                symt_new_public(module, compiland, name,
                                module->module.BaseOfImage + sect[isym->SectionNumber - 1].VirtualAddress +
                                     isym->Value,
                                1);
459 460 461 462 463 464 465 466 467
        }
        naux = isym->NumberOfAuxSymbols + 1;
    }
    module->module.SymType = SymCoff;
    module->module.LineNumbers = FALSE;
    module->module.GlobalSymbols = FALSE;
    module->module.TypeInfo = FALSE;
    module->module.SourceIndexed = FALSE;
    module->module.Publics = TRUE;
468
    pe_unmap_full(fmap);
469 470 471 472

    return TRUE;
}

473 474 475 476 477 478
/******************************************************************
 *		pe_load_stabs
 *
 * look for stabs information in PE header (it's how the mingw compiler provides 
 * its debugging information)
 */
479
static BOOL pe_load_stabs(const struct process* pcs, struct module* module)
480
{
481
    struct image_file_map*      fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
482
    struct image_section_map    sect_stabs, sect_stabstr;
483
    BOOL                        ret = FALSE;
484

485
    if (pe_find_section(fmap, ".stab", &sect_stabs) && pe_find_section(fmap, ".stabstr", &sect_stabstr))
486
    {
487 488 489
        const char* stab;
        const char* stabstr;

490 491
        stab = image_map_section(&sect_stabs);
        stabstr = image_map_section(&sect_stabstr);
492 493 494
        if (stab != IMAGE_NO_MAP && stabstr != IMAGE_NO_MAP)
        {
            ret = stabs_parse(module,
495 496 497
                              module->module.BaseOfImage - fmap->u.pe.ntheader.OptionalHeader.ImageBase,
                              stab, image_get_map_size(&sect_stabs),
                              stabstr, image_get_map_size(&sect_stabstr),
498 499
                              NULL, NULL);
        }
500 501
        image_unmap_section(&sect_stabs);
        image_unmap_section(&sect_stabstr);
502
        if (ret) pe_locate_with_coff_symbol_table(module);
503
    }
504
    TRACE("%s the STABS debug info\n", ret ? "successfully loaded" : "failed to load");
505 506 507 508 509 510 511 512 513 514

    return ret;
}

/******************************************************************
 *		pe_load_dwarf
 *
 * look for dwarf information in PE header (it's also a way for the mingw compiler
 * to provide its debugging information)
 */
515
static BOOL pe_load_dwarf(struct module* module)
516
{
517
    struct image_file_map*      fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
518
    BOOL                        ret = FALSE;
519

520 521 522 523
    ret = dwarf2_parse(module,
                       module->module.BaseOfImage - fmap->u.pe.ntheader.OptionalHeader.ImageBase,
                       NULL, /* FIXME: some thunks to deal with ? */
                       fmap);
524 525
    TRACE("%s the DWARF debug info\n", ret ? "successfully loaded" : "failed to load");

526
    return ret;
527 528 529 530 531 532 533
}

/******************************************************************
 *		pe_load_dbg_file
 *
 * loads a .dbg file
 */
534 535
static BOOL pe_load_dbg_file(const struct process* pcs, struct module* module,
                             const char* dbg_name, DWORD timestamp)
536
{
537
    char                                tmp[MAX_PATH];
538
    HANDLE                              hFile = INVALID_HANDLE_VALUE, hMap = 0;
539
    const BYTE*                         dbg_mapping = NULL;
540
    BOOL                                ret = FALSE;
541

542
    TRACE("Processing DBG file %s\n", debugstr_a(dbg_name));
543

544
    if (path_find_symbol_file(pcs, dbg_name, NULL, timestamp, 0, tmp, &module->module.DbgUnmatched) &&
545
        (hFile = CreateFileA(tmp, GENERIC_READ, FILE_SHARE_READ, NULL,
546
                             OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE &&
547
        ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0) &&
548 549
        ((dbg_mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL))
    {
550 551 552
        const IMAGE_SEPARATE_DEBUG_HEADER*      hdr;
        const IMAGE_SECTION_HEADER*             sectp;
        const IMAGE_DEBUG_DIRECTORY*            dbg;
553

554 555 556 557 558 559 560 561 562 563 564 565
        hdr = (const IMAGE_SEPARATE_DEBUG_HEADER*)dbg_mapping;
        /* section headers come immediately after debug header */
        sectp = (const IMAGE_SECTION_HEADER*)(hdr + 1);
        /* and after that and the exported names comes the debug directory */
        dbg = (const IMAGE_DEBUG_DIRECTORY*)
            (dbg_mapping + sizeof(*hdr) +
             hdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
             hdr->ExportedNamesSize);

        ret = pe_load_debug_directory(pcs, module, dbg_mapping, sectp,
                                      hdr->NumberOfSections, dbg,
                                      hdr->DebugDirectorySize / sizeof(*dbg));
566 567
    }
    else
568
        ERR("Couldn't find .DBG file %s (%s)\n", debugstr_a(dbg_name), debugstr_a(tmp));
569

570
    if (dbg_mapping) UnmapViewOfFile(dbg_mapping);
571
    if (hMap) CloseHandle(hMap);
572
    if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile);
573
    return ret;
574 575 576 577 578 579 580
}

/******************************************************************
 *		pe_load_msc_debug_info
 *
 * Process MSC debug information in PE file.
 */
581
static BOOL pe_load_msc_debug_info(const struct process* pcs, struct module* module)
582
{
583
    struct image_file_map*      fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
584
    BOOL                        ret = FALSE;
585 586 587
    const IMAGE_DATA_DIRECTORY* dir;
    const IMAGE_DEBUG_DIRECTORY*dbg = NULL;
    int                         nDbg;
588 589
    void*                       mapping;
    IMAGE_NT_HEADERS*           nth;
590

591
    if (!(mapping = pe_map_full(fmap, &nth))) return FALSE;
592 593 594
    /* Read in debug directory */
    dir = nth->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_DEBUG;
    nDbg = dir->Size / sizeof(IMAGE_DEBUG_DIRECTORY);
595
    if (!nDbg) goto done;
596

597
    dbg = RtlImageRvaToVa(nth, mapping, dir->VirtualAddress, NULL);
598 599 600 601 602

    /* Parse debug directory */
    if (nth->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED)
    {
        /* Debug info is stripped to .DBG file */
603 604
        const IMAGE_DEBUG_MISC* misc = (const IMAGE_DEBUG_MISC*)
            ((const char*)mapping + dbg->PointerToRawData);
605 606 607 608

        if (nDbg != 1 || dbg->Type != IMAGE_DEBUG_TYPE_MISC ||
            misc->DataType != IMAGE_DEBUG_MISC_EXENAME)
        {
609 610
            ERR("-Debug info stripped, but no .DBG file in module %s\n",
                debugstr_w(module->module.ModuleName));
611 612 613
        }
        else
        {
Mike McCormack's avatar
Mike McCormack committed
614
            ret = pe_load_dbg_file(pcs, module, (const char*)misc->Data, nth->FileHeader.TimeDateStamp);
615 616 617 618
        }
    }
    else
    {
619
        const IMAGE_SECTION_HEADER *sectp = (const IMAGE_SECTION_HEADER*)((const char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
620
        /* Debug info is embedded into PE module */
621
        ret = pe_load_debug_directory(pcs, module, mapping, sectp,
622
                                      nth->FileHeader.NumberOfSections, dbg, nDbg);
623
    }
624 625
done:
    pe_unmap_full(fmap);
626
    return ret;
627 628 629 630 631
}

/***********************************************************************
 *			pe_load_export_debug_info
 */
632
static BOOL pe_load_export_debug_info(const struct process* pcs, struct module* module)
633
{
634
    struct image_file_map*              fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
635 636 637 638
    unsigned int 		        i;
    const IMAGE_EXPORT_DIRECTORY* 	exports;
    DWORD			        base = module->module.BaseOfImage;
    DWORD                               size;
639 640
    IMAGE_NT_HEADERS*                   nth;
    void*                               mapping;
641

642
    if (dbghelp_options & SYMOPT_NO_PUBLICS) return TRUE;
643

644
    if (!(mapping = pe_map_full(fmap, &nth))) return FALSE;
645 646 647
#if 0
    /* Add start of DLL (better use the (yet unimplemented) Exe SymTag for this) */
    /* FIXME: module.ModuleName isn't correctly set yet if it's passed in SymLoadModule */
648
    symt_new_public(module, NULL, module->module.ModuleName, base, 1);
649 650 651
#endif
    
    /* Add entry point */
652
    symt_new_public(module, NULL, "EntryPoint", 
653
                    base + nth->OptionalHeader.AddressOfEntryPoint, 1);
654
#if 0
655 656
    /* FIXME: we'd better store addresses linked to sections rather than 
       absolute values */
657 658 659 660 661 662
    IMAGE_SECTION_HEADER*       section;
    /* Add start of sections */
    section = (IMAGE_SECTION_HEADER*)
        ((char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
    for (i = 0; i < nth->FileHeader.NumberOfSections; i++, section++) 
    {
663
	symt_new_public(module, NULL, section->Name, 
664
                        RtlImageRvaToVa(nth, mapping, section->VirtualAddress, NULL), 1);
665 666
    }
#endif
667

668
    /* Add exported functions */
669
    if ((exports = RtlImageDirectoryEntryToData(mapping, FALSE,
670
                                                IMAGE_DIRECTORY_ENTRY_EXPORT, &size)))
671
    {
672 673 674 675 676 677
        const WORD*             ordinals = NULL;
        const DWORD_PTR*	functions = NULL;
        const DWORD*		names = NULL;
        unsigned int		j;
        char			buffer[16];

678 679 680
        functions = RtlImageRvaToVa(nth, mapping, exports->AddressOfFunctions, NULL);
        ordinals  = RtlImageRvaToVa(nth, mapping, exports->AddressOfNameOrdinals, NULL);
        names     = RtlImageRvaToVa(nth, mapping, exports->AddressOfNames, NULL);
681

682
        if (functions && ordinals && names)
683
        {
684 685 686 687
            for (i = 0; i < exports->NumberOfNames; i++)
            {
                if (!names[i]) continue;
                symt_new_public(module, NULL,
688
                                RtlImageRvaToVa(nth, mapping, names[i], NULL),
689
                                base + functions[ordinals[i]], 1);
690 691 692 693 694 695 696 697 698 699
            }

            for (i = 0; i < exports->NumberOfFunctions; i++)
            {
                if (!functions[i]) continue;
                /* Check if we already added it with a name */
                for (j = 0; j < exports->NumberOfNames; j++)
                    if ((ordinals[j] == i) && names[j]) break;
                if (j < exports->NumberOfNames) continue;
                snprintf(buffer, sizeof(buffer), "%d", i + exports->Base);
700
                symt_new_public(module, NULL, buffer, base + (DWORD)functions[i], 1);
701
            }
702 703 704
        }
    }
    /* no real debug info, only entry points */
705 706
    if (module->module.SymType == SymDeferred)
        module->module.SymType = SymExport;
707 708
    pe_unmap_full(fmap);

709
    return TRUE;
710 711 712 713 714 715
}

/******************************************************************
 *		pe_load_debug_info
 *
 */
716
BOOL pe_load_debug_info(const struct process* pcs, struct module* module)
717 718 719 720 721
{
    BOOL                ret = FALSE;

    if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
    {
722 723 724 725
        ret = pe_load_stabs(pcs, module);
        ret = pe_load_dwarf(module) || ret;
        ret = pe_load_msc_debug_info(pcs, module) || ret;
        ret = ret || pe_load_coff_symbol_table(module); /* FIXME */
726 727 728 729 730
        /* if we still have no debug info (we could only get SymExport at this
         * point), then do the SymExport except if we have an ELF container,
         * in which case we'll rely on the export's on the ELF side
         */
    }
731 732
    /* FIXME shouldn't we check that? if (!module_get_debug(pcs, module)) */
    if (pe_load_export_debug_info(pcs, module) && !ret)
733 734 735 736 737
        ret = TRUE;

    return ret;
}

738
/******************************************************************
739
 *		pe_load_native_module
740 741
 *
 */
742
struct module* pe_load_native_module(struct process* pcs, const WCHAR* name,
743
                                     HANDLE hFile, DWORD64 base, DWORD size)
744
{
745 746
    struct module*              module = NULL;
    BOOL                        opened = FALSE;
747
    struct module_format*       modfmt;
748
    WCHAR                       loaded_name[MAX_PATH];
749 750 751 752

    loaded_name[0] = '\0';
    if (!hFile)
    {
753
        assert(name);
Eric Pouech's avatar
Eric Pouech committed
754

755
        if ((hFile = FindExecutableImageExW(name, pcs->search_path, loaded_name, NULL, NULL)) == NULL)
756 757 758
            return NULL;
        opened = TRUE;
    }
759
    else if (name) strcpyW(loaded_name, name);
760 761
    else if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
        FIXME("Trouble ahead (no module name passed in deferred mode)\n");
762
    if (!(modfmt = HeapAlloc(GetProcessHeap(), 0, sizeof(struct module_format) + sizeof(struct pe_module_info))))
763
        return NULL;
764 765
    modfmt->u.pe_info = (struct pe_module_info*)(modfmt + 1);
    if (pe_map_file(hFile, &modfmt->u.pe_info->fmap, DMT_PE))
766
    {
767 768
        if (!base) base = modfmt->u.pe_info->fmap.u.pe.ntheader.OptionalHeader.ImageBase;
        if (!size) size = modfmt->u.pe_info->fmap.u.pe.ntheader.OptionalHeader.SizeOfImage;
769

770
        module = module_new(pcs, loaded_name, DMT_PE, FALSE, base, size,
771 772
                            modfmt->u.pe_info->fmap.u.pe.ntheader.FileHeader.TimeDateStamp,
                            modfmt->u.pe_info->fmap.u.pe.ntheader.OptionalHeader.CheckSum);
773
        if (module)
774
        {
775 776 777 778 779
            modfmt->module = module;
            modfmt->remove = pe_module_remove;
            modfmt->loc_compute = NULL;

            module->format_info[DFI_PE] = modfmt;
780 781 782
            if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
                module->module.SymType = SymDeferred;
            else
783
                pe_load_debug_info(pcs, module);
784
            module->reloc_delta = base - modfmt->u.pe_info->fmap.u.pe.ntheader.OptionalHeader.ImageBase;
785 786 787 788
        }
        else
        {
            ERR("could not load the module '%s'\n", debugstr_w(loaded_name));
789
            pe_unmap_file(&modfmt->u.pe_info->fmap);
790 791
        }
    }
792
    if (!module) HeapFree(GetProcessHeap(), 0, modfmt);
793

794 795 796 797 798
    if (opened) CloseHandle(hFile);

    return module;
}

799 800 801 802
/******************************************************************
 *		pe_load_nt_header
 *
 */
803
BOOL pe_load_nt_header(HANDLE hProc, DWORD64 base, IMAGE_NT_HEADERS* nth)
804 805 806
{
    IMAGE_DOS_HEADER    dos;

807
    return ReadProcessMemory(hProc, (char*)(DWORD_PTR)base, &dos, sizeof(dos), NULL) &&
808
        dos.e_magic == IMAGE_DOS_SIGNATURE &&
809
        ReadProcessMemory(hProc, (char*)(DWORD_PTR)(base + dos.e_lfanew),
810 811 812 813
                          nth, sizeof(*nth), NULL) &&
        nth->Signature == IMAGE_NT_SIGNATURE;
}

814
/******************************************************************
815
 *		pe_load_builtin_module
816 817
 *
 */
818
struct module* pe_load_builtin_module(struct process* pcs, const WCHAR* name,
819
                                      DWORD64 base, DWORD64 size)
820
{
821
    struct module*      module = NULL;
822

823
    if (base && pcs->dbg_hdr_addr)
824
    {
825
        IMAGE_NT_HEADERS    nth;
826

827 828 829
        if (pe_load_nt_header(pcs->handle, base, &nth))
        {
            if (!size) size = nth.OptionalHeader.SizeOfImage;
830
            module = module_new(pcs, name, DMT_PE, FALSE, base, size,
831 832 833
                                nth.FileHeader.TimeDateStamp,
                                nth.OptionalHeader.CheckSum);
        }
834 835 836
    }
    return module;
}
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861

/***********************************************************************
 *           ImageDirectoryEntryToDataEx (DBGHELP.@)
 *
 * Search for specified directory in PE image
 *
 * PARAMS
 *
 *   base    [in]  Image base address
 *   image   [in]  TRUE - image has been loaded by loader, FALSE - raw file image
 *   dir     [in]  Target directory index
 *   size    [out] Receives directory size
 *   section [out] Receives pointer to section header of section containing directory data
 *
 * RETURNS
 *   Success: pointer to directory data
 *   Failure: NULL
 *
 */
PVOID WINAPI ImageDirectoryEntryToDataEx( PVOID base, BOOLEAN image, USHORT dir, PULONG size, PIMAGE_SECTION_HEADER *section )
{
    const IMAGE_NT_HEADERS *nt;
    DWORD addr;

    *size = 0;
862
    if (section) *section = NULL;
863 864 865 866 867 868

    if (!(nt = RtlImageNtHeader( base ))) return NULL;
    if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
    if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;

    *size = nt->OptionalHeader.DataDirectory[dir].Size;
869
    if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)base + addr;
870

871
    return RtlImageRvaToVa( nt, base, addr, section );
872 873 874 875 876 877 878 879 880 881 882 883
}

/***********************************************************************
 *         ImageDirectoryEntryToData   (DBGHELP.@)
 *
 * NOTES
 *   See ImageDirectoryEntryToDataEx
 */
PVOID WINAPI ImageDirectoryEntryToData( PVOID base, BOOLEAN image, USHORT dir, PULONG size )
{
    return ImageDirectoryEntryToDataEx( base, image, dir, size, NULL );
}