jscript: Don't pass 'this' argument to DISPID_VALUE of pure IDispatch interfaces.
[wine] / dlls / dbghelp / pe_module.c
1 /*
2  * File pe_module.c - handle PE module information
3  *
4  * Copyright (C) 1996,      Eric Youngdale.
5  * Copyright (C) 1999-2000, Ulrich Weigand.
6  * Copyright (C) 2004-2007, Eric Pouech.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * 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 #include "wine/port.h"
26
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <assert.h>
31
32 #include "dbghelp_private.h"
33 #include "image_private.h"
34 #include "winternl.h"
35 #include "wine/debug.h"
36
37 WINE_DEFAULT_DEBUG_CHANNEL(dbghelp);
38
39 struct pe_module_info
40 {
41     struct image_file_map       fmap;
42 };
43
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         if (nth) *nth = RtlImageNtHeader(fmap->u.pe.full_map);
53         fmap->u.pe.full_count++;
54         return fmap->u.pe.full_map;
55     }
56     return IMAGE_NO_MAP;
57 }
58
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         UnmapViewOfFile(fmap->u.pe.full_map);
64         fmap->u.pe.full_map = NULL;
65     }
66 }
67
68 /******************************************************************
69  *              pe_map_section
70  *
71  * Maps a single section into memory from an PE file
72  */
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     if (ism->sidx >= 0 && ism->sidx < fmap->ntheader.FileHeader.NumberOfSections &&
79         fmap->sect[ism->sidx].mapped == IMAGE_NO_MAP)
80     {
81         IMAGE_NT_HEADERS*       nth;
82
83         if (fmap->sect[ism->sidx].shdr.Misc.VirtualSize > fmap->sect[ism->sidx].shdr.SizeOfRawData)
84         {
85             FIXME("Section %ld: virtual (0x%x) > raw (0x%x) size - not supported\n",
86                   ism->sidx, fmap->sect[ism->sidx].shdr.Misc.VirtualSize,
87                   fmap->sect[ism->sidx].shdr.SizeOfRawData);
88             return IMAGE_NO_MAP;
89         }
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          * only map the relevant section
93          */
94         if ((mapping = pe_map_full(ism->fmap, &nth)))
95         {
96             fmap->sect[ism->sidx].mapped = RtlImageRvaToVa(nth, mapping,
97                                                            fmap->sect[ism->sidx].shdr.VirtualAddress,
98                                                            NULL);
99             return fmap->sect[ism->sidx].mapped;
100         }
101     }
102     return IMAGE_NO_MAP;
103 }
104
105 /******************************************************************
106  *              pe_find_section
107  *
108  * Finds a section by name (and type) into memory from an PE file
109  * or its alternate if any
110  */
111 BOOL pe_find_section(struct image_file_map* fmap, const char* name,
112                      struct image_section_map* ism)
113 {
114     const char*                 sectname;
115     unsigned                    i;
116     char                        tmp[IMAGE_SIZEOF_SHORT_NAME + 1];
117
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         if (sectname[0] == '/' && fmap->u.pe.strtable)
123             sectname = fmap->u.pe.strtable + atoi(sectname + 1);
124         else
125         {
126             /* the section name may not be null terminated */
127             sectname = memcpy(tmp, sectname, IMAGE_SIZEOF_SHORT_NAME);
128             tmp[IMAGE_SIZEOF_SHORT_NAME] = '\0';
129         }
130         if (!strcasecmp(sectname, name))
131         {
132             ism->fmap = fmap;
133             ism->sidx = i;
134             return TRUE;
135         }
136     }
137     ism->fmap = NULL;
138     ism->sidx = -1;
139
140     return FALSE;
141 }
142
143 /******************************************************************
144  *              pe_unmap_section
145  *
146  * Unmaps a single section from memory
147  */
148 void pe_unmap_section(struct image_section_map* ism)
149 {
150     if (ism->sidx >= 0 && ism->sidx < ism->fmap->u.pe.ntheader.FileHeader.NumberOfSections &&
151         ism->fmap->u.pe.sect[ism->sidx].mapped != IMAGE_NO_MAP)
152     {
153         pe_unmap_full(ism->fmap);
154         ism->fmap->u.pe.sect[ism->sidx].mapped = IMAGE_NO_MAP;
155     }
156 }
157
158 /******************************************************************
159  *              pe_get_map_rva
160  *
161  * Get the RVA of an PE section
162  */
163 DWORD_PTR pe_get_map_rva(const struct image_section_map* ism)
164 {
165     if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.pe.ntheader.FileHeader.NumberOfSections)
166         return 0;
167     return ism->fmap->u.pe.sect[ism->sidx].shdr.VirtualAddress;
168 }
169
170 /******************************************************************
171  *              pe_get_map_size
172  *
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  *              pe_is_valid_pointer_table
184  *
185  * Checks whether the PointerToSymbolTable and NumberOfSymbols in file_header contain
186  * valid information.
187  */
188 static BOOL pe_is_valid_pointer_table(const IMAGE_NT_HEADERS* nthdr, const void* mapping, DWORD64 sz)
189 {
190     DWORD64     offset;
191
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     offset += (DWORD64)nthdr->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL);
195     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  *              pe_map_file
203  *
204  * Maps an PE file into memory (and checks it's a real PE file)
205  */
206 static BOOL pe_map_file(HANDLE file, struct image_file_map* fmap, enum module_type mt)
207 {
208     void*       mapping;
209
210     fmap->modtype = mt;
211     fmap->u.pe.hMap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
212     if (fmap->u.pe.hMap == 0) return FALSE;
213     fmap->u.pe.full_count = 0;
214     fmap->u.pe.full_map = NULL;
215     if (!(mapping = pe_map_full(fmap, NULL))) goto error;
216
217     switch (mt)
218     {
219     case DMT_PE:
220         {
221             IMAGE_NT_HEADERS*       nthdr;
222             IMAGE_SECTION_HEADER*   section;
223             unsigned                i;
224
225             if (!(nthdr = RtlImageNtHeader(mapping))) goto error;
226             memcpy(&fmap->u.pe.ntheader, nthdr, sizeof(fmap->u.pe.ntheader));
227             switch (nthdr->OptionalHeader.Magic)
228             {
229             case 0x10b: fmap->addr_size = 32; break;
230             case 0x20b: fmap->addr_size = 64; break;
231             default: return FALSE;
232             }
233             section = (IMAGE_SECTION_HEADER*)
234                 ((char*)&nthdr->OptionalHeader + nthdr->FileHeader.SizeOfOptionalHeader);
235             fmap->u.pe.sect = HeapAlloc(GetProcessHeap(), 0,
236                                         nthdr->FileHeader.NumberOfSections * sizeof(fmap->u.pe.sect[0]));
237             if (!fmap->u.pe.sect) goto error;
238             for (i = 0; i < nthdr->FileHeader.NumberOfSections; i++)
239             {
240                 memcpy(&fmap->u.pe.sect[i].shdr, section + i, sizeof(IMAGE_SECTION_HEADER));
241                 fmap->u.pe.sect[i].mapped = IMAGE_NO_MAP;
242             }
243             if (nthdr->FileHeader.PointerToSymbolTable && nthdr->FileHeader.NumberOfSymbols)
244             {
245                 LARGE_INTEGER li;
246
247                 if (GetFileSizeEx(file, &li) && pe_is_valid_pointer_table(nthdr, mapping, li.QuadPart))
248                 {
249                     /* FIXME ugly: should rather map the relevant content instead of copying it */
250                     const char* src = (const char*)mapping +
251                         nthdr->FileHeader.PointerToSymbolTable +
252                         nthdr->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL);
253                     char* dst;
254                     DWORD sz = *(DWORD*)src;
255
256                     if ((dst = HeapAlloc(GetProcessHeap(), 0, sz)))
257                         memcpy(dst, src, sz);
258                     fmap->u.pe.strtable = dst;
259                 }
260                 else
261                 {
262                     WARN("Bad coff table... wipping out\n");
263                     /* we have bad information here, wipe it out */
264                     fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable = 0;
265                     fmap->u.pe.ntheader.FileHeader.NumberOfSymbols = 0;
266                     fmap->u.pe.strtable = NULL;
267                 }
268             }
269             else fmap->u.pe.strtable = NULL;
270         }
271         break;
272     default: assert(0); goto error;
273     }
274     pe_unmap_full(fmap);
275
276     return TRUE;
277 error:
278     pe_unmap_full(fmap);
279     CloseHandle(fmap->u.pe.hMap);
280     return FALSE;
281 }
282
283 /******************************************************************
284  *              pe_unmap_file
285  *
286  * Unmaps an PE file from memory (previously mapped with pe_map_file)
287  */
288 static void pe_unmap_file(struct image_file_map* fmap)
289 {
290     if (fmap->u.pe.hMap != 0)
291     {
292         struct image_section_map  ism;
293         ism.fmap = fmap;
294         for (ism.sidx = 0; ism.sidx < fmap->u.pe.ntheader.FileHeader.NumberOfSections; ism.sidx++)
295         {
296             pe_unmap_section(&ism);
297         }
298         while (fmap->u.pe.full_count) pe_unmap_full(fmap);
299         HeapFree(GetProcessHeap(), 0, fmap->u.pe.sect);
300         HeapFree(GetProcessHeap(), 0, (void*)fmap->u.pe.strtable); /* FIXME ugly (see pe_map_file) */
301         CloseHandle(fmap->u.pe.hMap);
302         fmap->u.pe.hMap = NULL;
303     }
304 }
305
306 /******************************************************************
307  *              pe_map_directory
308  *
309  * Maps a directory content out of a PE file
310  */
311 const char* pe_map_directory(struct module* module, int dirno, DWORD* size)
312 {
313     IMAGE_NT_HEADERS*   nth;
314     void*               mapping;
315
316     if (module->type != DMT_PE || !module->format_info[DFI_PE]) return NULL;
317     if (dirno >= IMAGE_NUMBEROF_DIRECTORY_ENTRIES ||
318         !(mapping = pe_map_full(&module->format_info[DFI_PE]->u.pe_info->fmap, &nth)))
319         return NULL;
320     if (size) *size = nth->OptionalHeader.DataDirectory[dirno].Size;
321     return RtlImageRvaToVa(nth, mapping,
322                            nth->OptionalHeader.DataDirectory[dirno].VirtualAddress, NULL);
323 }
324
325 /******************************************************************
326  *              pe_unmap_directory
327  *
328  * Unmaps a directory content
329  */
330 void pe_unmap_directory(struct image_file_map* fmap, int dirno)
331 {
332     pe_unmap_full(fmap);
333 }
334
335 static void pe_module_remove(struct process* pcs, struct module_format* modfmt)
336 {
337     pe_unmap_file(&modfmt->u.pe_info->fmap);
338     HeapFree(GetProcessHeap(), 0, modfmt);
339 }
340
341 /******************************************************************
342  *              pe_locate_with_coff_symbol_table
343  *
344  * Use the COFF symbol table (if any) from the IMAGE_FILE_HEADER to set the absolute address
345  * of global symbols.
346  * Mingw32 requires this for stabs debug information as address for global variables isn't filled in
347  * (this is similar to what is done in elf_module.c when using the .symtab ELF section)
348  */
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     const IMAGE_SYMBOL* isym;
353     int                 i, numsym, naux;
354     char                tmp[9];
355     const char*         name;
356     struct hash_table_iter      hti;
357     void*               ptr;
358     struct symt_data*   sym;
359     const char*         mapping;
360
361     numsym = fmap->u.pe.ntheader.FileHeader.NumberOfSymbols;
362     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     for (i = 0; i < numsym; i+= naux, isym += naux)
368     {
369         if (isym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL &&
370             isym->SectionNumber > 0 && isym->SectionNumber <= fmap->u.pe.ntheader.FileHeader.NumberOfSections)
371         {
372             if (isym->N.Name.Short)
373             {
374                 name = memcpy(tmp, isym->N.ShortName, 8);
375                 tmp[8] = '\0';
376             }
377             else name = fmap->u.pe.strtable + isym->N.Name.Long;
378             if (name[0] == '_') name++;
379             hash_table_iter_init(&module->ht_symbols, &hti, name);
380             while ((ptr = hash_table_iter_up(&hti)))
381             {
382                 sym = GET_ENTRY(ptr, struct symt_data, hash_elt);
383                 if (sym->symt.tag == SymTagData &&
384                     (sym->kind == DataIsGlobal || sym->kind == DataIsFileStatic) &&
385                     sym->u.var.kind == loc_absolute &&
386                     !strcmp(sym->hash_elt.name, name))
387                 {
388                     TRACE("Changing absolute address for %d.%s: %lx -> %s\n",
389                           isym->SectionNumber, name, sym->u.var.offset,
390                           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                     break;
396                 }
397             }
398         }
399         naux = isym->NumberOfAuxSymbols + 1;
400     }
401     pe_unmap_full(fmap);
402     return TRUE;
403 }
404
405 /******************************************************************
406  *              pe_load_coff_symbol_table
407  *
408  * Load public symbols out of the COFF symbol table (if any).
409  */
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     const IMAGE_SYMBOL* isym;
414     int                 i, numsym, naux;
415     const char*         strtable;
416     char                tmp[9];
417     const char*         name;
418     const char*         lastfilename = NULL;
419     struct symt_compiland*   compiland = NULL;
420     const IMAGE_SECTION_HEADER* sect;
421     const char*         mapping;
422
423     numsym = fmap->u.pe.ntheader.FileHeader.NumberOfSymbols;
424     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     /* FIXME: no way to get strtable size */
429     strtable = (const char*)&isym[numsym];
430     sect = IMAGE_FIRST_SECTION(RtlImageNtHeader((HMODULE)mapping));
431
432     for (i = 0; i < numsym; i+= naux, isym += naux)
433     {
434         if (isym->StorageClass == IMAGE_SYM_CLASS_FILE)
435         {
436             lastfilename = (const char*)(isym + 1);
437             compiland = NULL;
438         }
439         if (isym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL &&
440             isym->SectionNumber > 0 && isym->SectionNumber <= fmap->u.pe.ntheader.FileHeader.NumberOfSections)
441         {
442             if (isym->N.Name.Short)
443             {
444                 name = memcpy(tmp, isym->N.ShortName, 8);
445                 tmp[8] = '\0';
446             }
447             else name = strtable + isym->N.Name.Long;
448             if (name[0] == '_') name++;
449
450             if (!compiland && lastfilename)
451                 compiland = symt_new_compiland(module, 0,
452                                                source_new(module, NULL, lastfilename));
453
454             if (!(dbghelp_options & SYMOPT_NO_PUBLICS))
455                 symt_new_public(module, compiland, name,
456                                 module->module.BaseOfImage + sect[isym->SectionNumber - 1].VirtualAddress +
457                                      isym->Value,
458                                 1);
459         }
460         naux = isym->NumberOfAuxSymbols + 1;
461     }
462     module->module.SymType = SymCoff;
463     module->module.LineNumbers = FALSE;
464     module->module.GlobalSymbols = FALSE;
465     module->module.TypeInfo = FALSE;
466     module->module.SourceIndexed = FALSE;
467     module->module.Publics = TRUE;
468     pe_unmap_full(fmap);
469
470     return TRUE;
471 }
472
473 /******************************************************************
474  *              pe_load_stabs
475  *
476  * look for stabs information in PE header (it's how the mingw compiler provides 
477  * its debugging information)
478  */
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         const char* stab;
488         const char* stabstr;
489
490         stab = image_map_section(&sect_stabs);
491         stabstr = image_map_section(&sect_stabstr);
492         if (stab != IMAGE_NO_MAP && stabstr != IMAGE_NO_MAP)
493         {
494             ret = stabs_parse(module,
495                               module->module.BaseOfImage - fmap->u.pe.ntheader.OptionalHeader.ImageBase,
496                               stab, image_get_map_size(&sect_stabs),
497                               stabstr, image_get_map_size(&sect_stabstr),
498                               NULL, NULL);
499         }
500         image_unmap_section(&sect_stabs);
501         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     return ret;
507 }
508
509 /******************************************************************
510  *              pe_load_dwarf
511  *
512  * look for dwarf information in PE header (it's also a way for the mingw compiler
513  * to provide its debugging information)
514  */
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     ret = dwarf2_parse(module,
521                        module->module.BaseOfImage - fmap->u.pe.ntheader.OptionalHeader.ImageBase,
522                        NULL, /* FIXME: some thunks to deal with ? */
523                        fmap);
524     TRACE("%s the DWARF debug info\n", ret ? "successfully loaded" : "failed to load");
525
526     return ret;
527 }
528
529 /******************************************************************
530  *              pe_load_dbg_file
531  *
532  * loads a .dbg file
533  */
534 static BOOL pe_load_dbg_file(const struct process* pcs, struct module* module,
535                              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         ((dbg_mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL))
549     {
550         const IMAGE_SEPARATE_DEBUG_HEADER*      hdr;
551         const IMAGE_SECTION_HEADER*             sectp;
552         const IMAGE_DEBUG_DIRECTORY*            dbg;
553
554         hdr = (const IMAGE_SEPARATE_DEBUG_HEADER*)dbg_mapping;
555         /* section headers come immediately after debug header */
556         sectp = (const IMAGE_SECTION_HEADER*)(hdr + 1);
557         /* and after that and the exported names comes the debug directory */
558         dbg = (const IMAGE_DEBUG_DIRECTORY*)
559             (dbg_mapping + sizeof(*hdr) +
560              hdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
561              hdr->ExportedNamesSize);
562
563         ret = pe_load_debug_directory(pcs, module, dbg_mapping, sectp,
564                                       hdr->NumberOfSections, dbg,
565                                       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  *              pe_load_msc_debug_info
578  *
579  * Process MSC debug information in PE file.
580  */
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     const IMAGE_DATA_DIRECTORY* dir;
586     const IMAGE_DEBUG_DIRECTORY*dbg = NULL;
587     int                         nDbg;
588     void*                       mapping;
589     IMAGE_NT_HEADERS*           nth;
590
591     if (!(mapping = pe_map_full(fmap, &nth))) return FALSE;
592     /* Read in debug directory */
593     dir = nth->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_DEBUG;
594     nDbg = dir->Size / sizeof(IMAGE_DEBUG_DIRECTORY);
595     if (!nDbg) goto done;
596
597     dbg = RtlImageRvaToVa(nth, mapping, dir->VirtualAddress, NULL);
598
599     /* Parse debug directory */
600     if (nth->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED)
601     {
602         /* Debug info is stripped to .DBG file */
603         const IMAGE_DEBUG_MISC* misc = (const IMAGE_DEBUG_MISC*)
604             ((const char*)mapping + dbg->PointerToRawData);
605
606         if (nDbg != 1 || dbg->Type != IMAGE_DEBUG_TYPE_MISC ||
607             misc->DataType != IMAGE_DEBUG_MISC_EXENAME)
608         {
609             ERR("-Debug info stripped, but no .DBG file in module %s\n",
610                 debugstr_w(module->module.ModuleName));
611         }
612         else
613         {
614             ret = pe_load_dbg_file(pcs, module, (const char*)misc->Data, nth->FileHeader.TimeDateStamp);
615         }
616     }
617     else
618     {
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 done:
625     pe_unmap_full(fmap);
626     return ret;
627 }
628
629 /***********************************************************************
630  *                      pe_load_export_debug_info
631  */
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     unsigned int                        i;
636     const IMAGE_EXPORT_DIRECTORY*       exports;
637     DWORD                               base = module->module.BaseOfImage;
638     DWORD                               size;
639     IMAGE_NT_HEADERS*                   nth;
640     void*                               mapping;
641
642     if (dbghelp_options & SYMOPT_NO_PUBLICS) return TRUE;
643
644     if (!(mapping = pe_map_full(fmap, &nth))) return FALSE;
645 #if 0
646     /* Add start of DLL (better use the (yet unimplemented) Exe SymTag for this) */
647     /* 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 #endif
650     
651     /* Add entry point */
652     symt_new_public(module, NULL, "EntryPoint", 
653                     base + nth->OptionalHeader.AddressOfEntryPoint, 1);
654 #if 0
655     /* FIXME: we'd better store addresses linked to sections rather than 
656        absolute values */
657     IMAGE_SECTION_HEADER*       section;
658     /* Add start of sections */
659     section = (IMAGE_SECTION_HEADER*)
660         ((char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
661     for (i = 0; i < nth->FileHeader.NumberOfSections; i++, section++) 
662     {
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         const WORD*             ordinals = NULL;
673         const DWORD_PTR*        functions = NULL;
674         const DWORD*            names = NULL;
675         unsigned int            j;
676         char                    buffer[16];
677
678         functions = RtlImageRvaToVa(nth, mapping, exports->AddressOfFunctions, NULL);
679         ordinals  = RtlImageRvaToVa(nth, mapping, exports->AddressOfNameOrdinals, NULL);
680         names     = RtlImageRvaToVa(nth, mapping, exports->AddressOfNames, NULL);
681
682         if (functions && ordinals && names)
683         {
684             for (i = 0; i < exports->NumberOfNames; i++)
685             {
686                 if (!names[i]) continue;
687                 symt_new_public(module, NULL,
688                                 RtlImageRvaToVa(nth, mapping, names[i], NULL),
689                                 base + functions[ordinals[i]], 1);
690             }
691
692             for (i = 0; i < exports->NumberOfFunctions; i++)
693             {
694                 if (!functions[i]) continue;
695                 /* Check if we already added it with a name */
696                 for (j = 0; j < exports->NumberOfNames; j++)
697                     if ((ordinals[j] == i) && names[j]) break;
698                 if (j < exports->NumberOfNames) continue;
699                 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     if (module->module.SymType == SymDeferred)
706         module->module.SymType = SymExport;
707     pe_unmap_full(fmap);
708
709     return TRUE;
710 }
711
712 /******************************************************************
713  *              pe_load_debug_info
714  *
715  */
716 BOOL pe_load_debug_info(const struct process* pcs, struct module* module)
717 {
718     BOOL                ret = FALSE;
719
720     if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
721     {
722         ret = pe_load_stabs(pcs, module);
723         ret = pe_load_dwarf(module) || ret;
724         ret = pe_load_msc_debug_info(pcs, module) || ret;
725         ret = ret || pe_load_coff_symbol_table(module); /* FIXME */
726         /* if we still have no debug info (we could only get SymExport at this
727          * point), then do the SymExport except if we have an ELF container,
728          * in which case we'll rely on the export's on the ELF side
729          */
730     }
731     /* FIXME shouldn't we check that? if (!module_get_debug(pcs, module)) */
732     if (pe_load_export_debug_info(pcs, module) && !ret)
733         ret = TRUE;
734
735     return ret;
736 }
737
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     struct module*              module = NULL;
746     BOOL                        opened = FALSE;
747     struct module_format*       modfmt;
748     WCHAR                       loaded_name[MAX_PATH];
749
750     loaded_name[0] = '\0';
751     if (!hFile)
752     {
753         assert(name);
754
755         if ((hFile = FindExecutableImageExW(name, pcs->search_path, loaded_name, NULL, NULL)) == NULL)
756             return NULL;
757         opened = TRUE;
758     }
759     else if (name) strcpyW(loaded_name, name);
760     else if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
761         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     modfmt->u.pe_info = (struct pe_module_info*)(modfmt + 1);
765     if (pe_map_file(hFile, &modfmt->u.pe_info->fmap, DMT_PE))
766     {
767         if (!base) base = modfmt->u.pe_info->fmap.u.pe.ntheader.OptionalHeader.ImageBase;
768         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                             modfmt->u.pe_info->fmap.u.pe.ntheader.FileHeader.TimeDateStamp,
772                             modfmt->u.pe_info->fmap.u.pe.ntheader.OptionalHeader.CheckSum);
773         if (module)
774         {
775             modfmt->module = module;
776             modfmt->remove = pe_module_remove;
777             modfmt->loc_compute = NULL;
778
779             module->format_info[DFI_PE] = modfmt;
780             if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
781                 module->module.SymType = SymDeferred;
782             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         else
787         {
788             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     if (opened) CloseHandle(hFile);
795
796     return module;
797 }
798
799 /******************************************************************
800  *              pe_load_nt_header
801  *
802  */
803 BOOL pe_load_nt_header(HANDLE hProc, DWORD64 base, IMAGE_NT_HEADERS* nth)
804 {
805     IMAGE_DOS_HEADER    dos;
806
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                           nth, sizeof(*nth), NULL) &&
811         nth->Signature == IMAGE_NT_SIGNATURE;
812 }
813
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         if (pe_load_nt_header(pcs->handle, base, &nth))
828         {
829             if (!size) size = nth.OptionalHeader.SizeOfImage;
830             module = module_new(pcs, name, DMT_PE, FALSE, base, size,
831                                 nth.FileHeader.TimeDateStamp,
832                                 nth.OptionalHeader.CheckSum);
833         }
834     }
835     return module;
836 }
837
838 /***********************************************************************
839  *           ImageDirectoryEntryToDataEx (DBGHELP.@)
840  *
841  * Search for specified directory in PE image
842  *
843  * PARAMS
844  *
845  *   base    [in]  Image base address
846  *   image   [in]  TRUE - image has been loaded by loader, FALSE - raw file image
847  *   dir     [in]  Target directory index
848  *   size    [out] Receives directory size
849  *   section [out] Receives pointer to section header of section containing directory data
850  *
851  * RETURNS
852  *   Success: pointer to directory data
853  *   Failure: NULL
854  *
855  */
856 PVOID WINAPI ImageDirectoryEntryToDataEx( PVOID base, BOOLEAN image, USHORT dir, PULONG size, PIMAGE_SECTION_HEADER *section )
857 {
858     const IMAGE_NT_HEADERS *nt;
859     DWORD addr;
860
861     *size = 0;
862     if (section) *section = NULL;
863
864     if (!(nt = RtlImageNtHeader( base ))) return NULL;
865     if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
866     if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
867
868     *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  *         ImageDirectoryEntryToData   (DBGHELP.@)
876  *
877  * NOTES
878  *   See ImageDirectoryEntryToDataEx
879  */
880 PVOID WINAPI ImageDirectoryEntryToData( PVOID base, BOOLEAN image, USHORT dir, PULONG size )
881 {
882     return ImageDirectoryEntryToDataEx( base, image, dir, size, NULL );
883 }