samlib: Add stubbed samlib.dll.
[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         /* FIXME: that's rather drastic, but that will do for now
83          * that's ok if the full file map exists, but we could be less agressive otherwise and
84          * only map the relevant section
85          */
86         if ((mapping = pe_map_full(ism->fmap, &nth)))
87         {
88             fmap->sect[ism->sidx].mapped = RtlImageRvaToVa(nth, mapping,
89                                                            fmap->sect[ism->sidx].shdr.VirtualAddress,
90                                                            NULL);
91             return fmap->sect[ism->sidx].mapped;
92         }
93     }
94     return IMAGE_NO_MAP;
95 }
96
97 /******************************************************************
98  *              pe_find_section
99  *
100  * Finds a section by name (and type) into memory from an PE file
101  * or its alternate if any
102  */
103 BOOL pe_find_section(struct image_file_map* fmap, const char* name,
104                      struct image_section_map* ism)
105 {
106     const char*                 sectname;
107     unsigned                    i;
108     char                        tmp[IMAGE_SIZEOF_SHORT_NAME + 1];
109
110     for (i = 0; i < fmap->u.pe.ntheader.FileHeader.NumberOfSections; i++)
111     {
112         sectname = (const char*)fmap->u.pe.sect[i].shdr.Name;
113         /* long section names start with a '/' (at least on MinGW32) */
114         if (sectname[0] == '/' && fmap->u.pe.strtable)
115             sectname = fmap->u.pe.strtable + atoi(sectname + 1);
116         else
117         {
118             /* the section name may not be null terminated */
119             sectname = memcpy(tmp, sectname, IMAGE_SIZEOF_SHORT_NAME);
120             tmp[IMAGE_SIZEOF_SHORT_NAME] = '\0';
121         }
122         if (!strcasecmp(sectname, name))
123         {
124             ism->fmap = fmap;
125             ism->sidx = i;
126             return TRUE;
127         }
128     }
129     ism->fmap = NULL;
130     ism->sidx = -1;
131
132     return FALSE;
133 }
134
135 /******************************************************************
136  *              pe_unmap_section
137  *
138  * Unmaps a single section from memory
139  */
140 void pe_unmap_section(struct image_section_map* ism)
141 {
142     if (ism->sidx >= 0 && ism->sidx < ism->fmap->u.pe.ntheader.FileHeader.NumberOfSections &&
143         ism->fmap->u.pe.sect[ism->sidx].mapped != IMAGE_NO_MAP)
144     {
145         pe_unmap_full(ism->fmap);
146         ism->fmap->u.pe.sect[ism->sidx].mapped = IMAGE_NO_MAP;
147     }
148 }
149
150 /******************************************************************
151  *              pe_get_map_rva
152  *
153  * Get the RVA of an PE section
154  */
155 DWORD_PTR pe_get_map_rva(const struct image_section_map* ism)
156 {
157     if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.pe.ntheader.FileHeader.NumberOfSections)
158         return 0;
159     return ism->fmap->u.pe.sect[ism->sidx].shdr.VirtualAddress;
160 }
161
162 /******************************************************************
163  *              pe_get_map_size
164  *
165  * Get the size of an PE section
166  */
167 unsigned pe_get_map_size(const struct image_section_map* ism)
168 {
169     if (ism->sidx < 0 || ism->sidx >= ism->fmap->u.pe.ntheader.FileHeader.NumberOfSections)
170         return 0;
171     return ism->fmap->u.pe.sect[ism->sidx].shdr.SizeOfRawData;
172 }
173
174 /******************************************************************
175  *              pe_is_valid_pointer_table
176  *
177  * Checks whether the PointerToSymbolTable and NumberOfSymbols in file_header contain
178  * valid information.
179  */
180 static BOOL pe_is_valid_pointer_table(const IMAGE_NT_HEADERS* nthdr, const void* mapping)
181 {
182     DWORD64     offset;
183
184     /* is the iSym table inside file image ? */
185     offset = (DWORD64)nthdr->FileHeader.PointerToSymbolTable;
186     offset += (DWORD64)nthdr->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL);
187     if (offset > (DWORD64)nthdr->OptionalHeader.SizeOfImage) return FALSE;
188     /* is string table (following iSym table) inside file image ? */
189     offset += *(DWORD*)((const char*)mapping + offset);
190     return offset <= (DWORD64)nthdr->OptionalHeader.SizeOfImage;
191 }
192
193 /******************************************************************
194  *              pe_map_file
195  *
196  * Maps an PE file into memory (and checks it's a real PE file)
197  */
198 static BOOL pe_map_file(HANDLE file, struct image_file_map* fmap, enum module_type mt)
199 {
200     void*       mapping;
201
202     fmap->modtype = mt;
203     fmap->u.pe.hMap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
204     if (fmap->u.pe.hMap == 0) return FALSE;
205     fmap->u.pe.full_count = 0;
206     fmap->u.pe.full_map = NULL;
207     if (!(mapping = pe_map_full(fmap, NULL))) goto error;
208
209     switch (mt)
210     {
211     case DMT_PE:
212         {
213             IMAGE_NT_HEADERS*       nthdr;
214             IMAGE_SECTION_HEADER*   section;
215             unsigned                i;
216
217             if (!(nthdr = RtlImageNtHeader(mapping))) goto error;
218             memcpy(&fmap->u.pe.ntheader, nthdr, sizeof(fmap->u.pe.ntheader));
219             section = (IMAGE_SECTION_HEADER*)
220                 ((char*)&nthdr->OptionalHeader + nthdr->FileHeader.SizeOfOptionalHeader);
221             fmap->u.pe.sect = HeapAlloc(GetProcessHeap(), 0,
222                                         nthdr->FileHeader.NumberOfSections * sizeof(fmap->u.pe.sect[0]));
223             if (!fmap->u.pe.sect) goto error;
224             for (i = 0; i < nthdr->FileHeader.NumberOfSections; i++)
225             {
226                 memcpy(&fmap->u.pe.sect[i].shdr, section + i, sizeof(IMAGE_SECTION_HEADER));
227                 fmap->u.pe.sect[i].mapped = IMAGE_NO_MAP;
228             }
229             if (nthdr->FileHeader.PointerToSymbolTable && nthdr->FileHeader.NumberOfSymbols)
230             {
231                 if (pe_is_valid_pointer_table(nthdr, mapping))
232                 {
233                     /* FIXME ugly: should rather map the relevant content instead of copying it */
234                     const char* src = (const char*)mapping +
235                         nthdr->FileHeader.PointerToSymbolTable +
236                         nthdr->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL);
237                     char* dst;
238                     DWORD sz = *(DWORD*)src;
239
240                     if ((dst = HeapAlloc(GetProcessHeap(), 0, sz)))
241                         memcpy(dst, src, sz);
242                     fmap->u.pe.strtable = dst;
243                 }
244                 else
245                 {
246                     /* we have bad information here, wipe it out */
247                     fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable = 0;
248                     fmap->u.pe.ntheader.FileHeader.NumberOfSymbols = 0;
249                     fmap->u.pe.strtable = NULL;
250                 }
251             }
252             else fmap->u.pe.strtable = NULL;
253         }
254         break;
255     default: assert(0); goto error;
256     }
257     pe_unmap_full(fmap);
258
259     return TRUE;
260 error:
261     pe_unmap_full(fmap);
262     CloseHandle(fmap->u.pe.hMap);
263     return FALSE;
264 }
265
266 /******************************************************************
267  *              pe_unmap_file
268  *
269  * Unmaps an PE file from memory (previously mapped with pe_map_file)
270  */
271 static void pe_unmap_file(struct image_file_map* fmap)
272 {
273     if (fmap->u.pe.hMap != 0)
274     {
275         struct image_section_map  ism;
276         ism.fmap = fmap;
277         for (ism.sidx = 0; ism.sidx < fmap->u.pe.ntheader.FileHeader.NumberOfSections; ism.sidx++)
278         {
279             pe_unmap_section(&ism);
280         }
281         while (fmap->u.pe.full_count) pe_unmap_full(fmap);
282         HeapFree(GetProcessHeap(), 0, fmap->u.pe.sect);
283         HeapFree(GetProcessHeap(), 0, (void*)fmap->u.pe.strtable); /* FIXME ugly (see pe_map_file) */
284         CloseHandle(fmap->u.pe.hMap);
285         fmap->u.pe.hMap = NULL;
286     }
287 }
288
289 /******************************************************************
290  *              pe_map_directory
291  *
292  * Maps a directory content out of a PE file
293  */
294 const char* pe_map_directory(struct module* module, int dirno, DWORD* size)
295 {
296     IMAGE_NT_HEADERS*   nth;
297     void*               mapping;
298
299     if (module->type != DMT_PE || !module->format_info[DFI_PE]) return NULL;
300     if (dirno >= IMAGE_NUMBEROF_DIRECTORY_ENTRIES ||
301         !(mapping = pe_map_full(&module->format_info[DFI_PE]->u.pe_info->fmap, &nth)))
302         return NULL;
303     if (size) *size = nth->OptionalHeader.DataDirectory[dirno].Size;
304     return RtlImageRvaToVa(nth, mapping,
305                            nth->OptionalHeader.DataDirectory[dirno].VirtualAddress, NULL);
306 }
307
308 /******************************************************************
309  *              pe_unmap_directory
310  *
311  * Unmaps a directory content
312  */
313 void pe_unmap_directory(struct image_file_map* fmap, int dirno)
314 {
315     pe_unmap_full(fmap);
316 }
317
318 static void pe_module_remove(struct process* pcs, struct module_format* modfmt)
319 {
320     pe_unmap_file(&modfmt->u.pe_info->fmap);
321     HeapFree(GetProcessHeap(), 0, modfmt);
322 }
323
324 /******************************************************************
325  *              pe_locate_with_coff_symbol_table
326  *
327  * Use the COFF symbol table (if any) from the IMAGE_FILE_HEADER to set the absolute address
328  * of global symbols.
329  * Mingw32 requires this for stabs debug information as address for global variables isn't filled in
330  * (this is similar to what is done in elf_module.c when using the .symtab ELF section)
331  */
332 static BOOL pe_locate_with_coff_symbol_table(struct module* module)
333 {
334     struct image_file_map* fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
335     const IMAGE_SYMBOL* isym;
336     int                 i, numsym, naux;
337     char                tmp[9];
338     const char*         name;
339     struct hash_table_iter      hti;
340     void*               ptr;
341     struct symt_data*   sym;
342     const char*         mapping;
343
344     numsym = fmap->u.pe.ntheader.FileHeader.NumberOfSymbols;
345     if (!fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable || !numsym)
346         return TRUE;
347     if (!(mapping = pe_map_full(fmap, NULL))) return FALSE;
348     isym = (const IMAGE_SYMBOL*)(mapping + fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable);
349
350     for (i = 0; i < numsym; i+= naux, isym += naux)
351     {
352         if (isym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL &&
353             isym->SectionNumber > 0 && isym->SectionNumber <= fmap->u.pe.ntheader.FileHeader.NumberOfSections)
354         {
355             if (isym->N.Name.Short)
356             {
357                 name = memcpy(tmp, isym->N.ShortName, 8);
358                 tmp[8] = '\0';
359             }
360             else name = fmap->u.pe.strtable + isym->N.Name.Long;
361             if (name[0] == '_') name++;
362             hash_table_iter_init(&module->ht_symbols, &hti, name);
363             while ((ptr = hash_table_iter_up(&hti)))
364             {
365                 sym = GET_ENTRY(ptr, struct symt_data, hash_elt);
366                 if (sym->symt.tag == SymTagData &&
367                     (sym->kind == DataIsGlobal || sym->kind == DataIsFileStatic) &&
368                     !strcmp(sym->hash_elt.name, name))
369                 {
370                     TRACE("Changing absolute address for %d.%s: %lx -> %s\n",
371                           isym->SectionNumber, name, sym->u.var.offset,
372                           wine_dbgstr_longlong(module->module.BaseOfImage +
373                                                fmap->u.pe.sect[isym->SectionNumber - 1].shdr.VirtualAddress +
374                                                isym->Value));
375                     sym->u.var.offset = module->module.BaseOfImage +
376                         fmap->u.pe.sect[isym->SectionNumber - 1].shdr.VirtualAddress + isym->Value;
377                     break;
378                 }
379             }
380         }
381         naux = isym->NumberOfAuxSymbols + 1;
382     }
383     pe_unmap_full(fmap);
384     return TRUE;
385 }
386
387 /******************************************************************
388  *              pe_load_coff_symbol_table
389  *
390  * Load public symbols out of the COFF symbol table (if any).
391  */
392 static BOOL pe_load_coff_symbol_table(struct module* module)
393 {
394     struct image_file_map* fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
395     const IMAGE_SYMBOL* isym;
396     int                 i, numsym, naux;
397     const char*         strtable;
398     char                tmp[9];
399     const char*         name;
400     const char*         lastfilename = NULL;
401     struct symt_compiland*   compiland = NULL;
402     const IMAGE_SECTION_HEADER* sect;
403     const char*         mapping;
404
405     numsym = fmap->u.pe.ntheader.FileHeader.NumberOfSymbols;
406     if (!fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable || !numsym)
407         return TRUE;
408     if (!(mapping = pe_map_full(fmap, NULL))) return FALSE;
409     isym = (const IMAGE_SYMBOL*)((const char*)mapping + fmap->u.pe.ntheader.FileHeader.PointerToSymbolTable);
410     /* FIXME: no way to get strtable size */
411     strtable = (const char*)&isym[numsym];
412     sect = IMAGE_FIRST_SECTION(&fmap->u.pe.ntheader);
413
414     for (i = 0; i < numsym; i+= naux, isym += naux)
415     {
416         if (isym->StorageClass == IMAGE_SYM_CLASS_FILE)
417         {
418             lastfilename = (const char*)(isym + 1);
419             compiland = NULL;
420         }
421         if (isym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL &&
422             isym->SectionNumber > 0 && isym->SectionNumber <= fmap->u.pe.ntheader.FileHeader.NumberOfSections)
423         {
424             if (isym->N.Name.Short)
425             {
426                 name = memcpy(tmp, isym->N.ShortName, 8);
427                 tmp[8] = '\0';
428             }
429             else name = strtable + isym->N.Name.Long;
430             if (name[0] == '_') name++;
431
432             if (!compiland && lastfilename)
433                 compiland = symt_new_compiland(module, 0,
434                                                source_new(module, NULL, lastfilename));
435
436             if (!(dbghelp_options & SYMOPT_NO_PUBLICS))
437                 symt_new_public(module, compiland, name,
438                                 module->module.BaseOfImage + sect[isym->SectionNumber - 1].VirtualAddress +
439                                      isym->Value,
440                                 1);
441         }
442         naux = isym->NumberOfAuxSymbols + 1;
443     }
444     module->module.SymType = SymCoff;
445     module->module.LineNumbers = FALSE;
446     module->module.GlobalSymbols = FALSE;
447     module->module.TypeInfo = FALSE;
448     module->module.SourceIndexed = FALSE;
449     module->module.Publics = TRUE;
450     pe_unmap_full(fmap);
451
452     return TRUE;
453 }
454
455 static inline void* pe_get_sect(IMAGE_NT_HEADERS* nth, void* mapping,
456                                 IMAGE_SECTION_HEADER* sect)
457 {
458     return (sect) ? RtlImageRvaToVa(nth, mapping, sect->VirtualAddress, NULL) : NULL;
459 }
460
461 static inline DWORD pe_get_sect_size(IMAGE_SECTION_HEADER* sect)
462 {
463     return (sect) ? sect->SizeOfRawData : 0;
464 }
465
466 /******************************************************************
467  *              pe_load_stabs
468  *
469  * look for stabs information in PE header (it's how the mingw compiler provides 
470  * its debugging information)
471  */
472 static BOOL pe_load_stabs(const struct process* pcs, struct module* module)
473 {
474     struct image_file_map*      fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
475     struct image_section_map    sect_stabs, sect_stabstr;
476     BOOL                        ret = FALSE;
477
478     if (pe_find_section(fmap, ".stab", &sect_stabs) && pe_find_section(fmap, ".stabstr", &sect_stabstr))
479     {
480         const char* stab;
481         const char* stabstr;
482
483         stab = image_map_section(&sect_stabs);
484         stabstr = image_map_section(&sect_stabstr);
485         if (stab != IMAGE_NO_MAP && stabstr != IMAGE_NO_MAP)
486         {
487             ret = stabs_parse(module,
488                               module->module.BaseOfImage - fmap->u.pe.ntheader.OptionalHeader.ImageBase,
489                               stab, image_get_map_size(&sect_stabs),
490                               stabstr, image_get_map_size(&sect_stabstr),
491                               NULL, NULL);
492         }
493         image_unmap_section(&sect_stabs);
494         image_unmap_section(&sect_stabstr);
495         if (ret) pe_locate_with_coff_symbol_table(module);
496     }
497     TRACE("%s the STABS debug info\n", ret ? "successfully loaded" : "failed to load");
498
499     return ret;
500 }
501
502 /******************************************************************
503  *              pe_load_dwarf
504  *
505  * look for dwarf information in PE header (it's also a way for the mingw compiler
506  * to provide its debugging information)
507  */
508 static BOOL pe_load_dwarf(struct module* module)
509 {
510     struct image_file_map*      fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
511     BOOL                        ret = FALSE;
512
513     ret = dwarf2_parse(module,
514                        module->module.BaseOfImage - fmap->u.pe.ntheader.OptionalHeader.ImageBase,
515                        NULL, /* FIXME: some thunks to deal with ? */
516                        fmap);
517     TRACE("%s the DWARF debug info\n", ret ? "successfully loaded" : "failed to load");
518
519     return ret;
520 }
521
522 /******************************************************************
523  *              pe_load_dbg_file
524  *
525  * loads a .dbg file
526  */
527 static BOOL pe_load_dbg_file(const struct process* pcs, struct module* module,
528                              const char* dbg_name, DWORD timestamp)
529 {
530     char                                tmp[MAX_PATH];
531     HANDLE                              hFile = INVALID_HANDLE_VALUE, hMap = 0;
532     const BYTE*                         dbg_mapping = NULL;
533     BOOL                                ret = FALSE;
534
535     TRACE("Processing DBG file %s\n", debugstr_a(dbg_name));
536
537     if (path_find_symbol_file(pcs, dbg_name, NULL, timestamp, 0, tmp, &module->module.DbgUnmatched) &&
538         (hFile = CreateFileA(tmp, GENERIC_READ, FILE_SHARE_READ, NULL,
539                              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE &&
540         ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0) &&
541         ((dbg_mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL))
542     {
543         const IMAGE_SEPARATE_DEBUG_HEADER*      hdr;
544         const IMAGE_SECTION_HEADER*             sectp;
545         const IMAGE_DEBUG_DIRECTORY*            dbg;
546
547         hdr = (const IMAGE_SEPARATE_DEBUG_HEADER*)dbg_mapping;
548         /* section headers come immediately after debug header */
549         sectp = (const IMAGE_SECTION_HEADER*)(hdr + 1);
550         /* and after that and the exported names comes the debug directory */
551         dbg = (const IMAGE_DEBUG_DIRECTORY*)
552             (dbg_mapping + sizeof(*hdr) +
553              hdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
554              hdr->ExportedNamesSize);
555
556         ret = pe_load_debug_directory(pcs, module, dbg_mapping, sectp,
557                                       hdr->NumberOfSections, dbg,
558                                       hdr->DebugDirectorySize / sizeof(*dbg));
559     }
560     else
561         ERR("Couldn't find .DBG file %s (%s)\n", debugstr_a(dbg_name), debugstr_a(tmp));
562
563     if (dbg_mapping) UnmapViewOfFile(dbg_mapping);
564     if (hMap) CloseHandle(hMap);
565     if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile);
566     return ret;
567 }
568
569 /******************************************************************
570  *              pe_load_msc_debug_info
571  *
572  * Process MSC debug information in PE file.
573  */
574 static BOOL pe_load_msc_debug_info(const struct process* pcs, struct module* module)
575 {
576     struct image_file_map*      fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
577     BOOL                        ret = FALSE;
578     const IMAGE_DATA_DIRECTORY* dir;
579     const IMAGE_DEBUG_DIRECTORY*dbg = NULL;
580     int                         nDbg;
581     void*                       mapping;
582     IMAGE_NT_HEADERS*           nth;
583
584     if (!(mapping = pe_map_full(fmap, &nth))) return FALSE;
585     /* Read in debug directory */
586     dir = nth->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_DEBUG;
587     nDbg = dir->Size / sizeof(IMAGE_DEBUG_DIRECTORY);
588     if (!nDbg) goto done;
589
590     dbg = RtlImageRvaToVa(nth, mapping, dir->VirtualAddress, NULL);
591
592     /* Parse debug directory */
593     if (nth->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED)
594     {
595         /* Debug info is stripped to .DBG file */
596         const IMAGE_DEBUG_MISC* misc = (const IMAGE_DEBUG_MISC*)
597             ((const char*)mapping + dbg->PointerToRawData);
598
599         if (nDbg != 1 || dbg->Type != IMAGE_DEBUG_TYPE_MISC ||
600             misc->DataType != IMAGE_DEBUG_MISC_EXENAME)
601         {
602             WINE_ERR("-Debug info stripped, but no .DBG file in module %s\n",
603                      debugstr_w(module->module.ModuleName));
604         }
605         else
606         {
607             ret = pe_load_dbg_file(pcs, module, (const char*)misc->Data, nth->FileHeader.TimeDateStamp);
608         }
609     }
610     else
611     {
612         const IMAGE_SECTION_HEADER *sectp = (const IMAGE_SECTION_HEADER*)((const char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
613         /* Debug info is embedded into PE module */
614         ret = pe_load_debug_directory(pcs, module, mapping, sectp,
615                                       nth->FileHeader.NumberOfSections, dbg, nDbg);
616     }
617 done:
618     pe_unmap_full(fmap);
619     return ret;
620 }
621
622 /***********************************************************************
623  *                      pe_load_export_debug_info
624  */
625 static BOOL pe_load_export_debug_info(const struct process* pcs, struct module* module)
626 {
627     struct image_file_map*              fmap = &module->format_info[DFI_PE]->u.pe_info->fmap;
628     unsigned int                        i;
629     const IMAGE_EXPORT_DIRECTORY*       exports;
630     DWORD                               base = module->module.BaseOfImage;
631     DWORD                               size;
632     IMAGE_NT_HEADERS*                   nth;
633     void*                               mapping;
634
635     if (dbghelp_options & SYMOPT_NO_PUBLICS) return TRUE;
636
637     if (!(mapping = pe_map_full(fmap, &nth))) return FALSE;
638 #if 0
639     /* Add start of DLL (better use the (yet unimplemented) Exe SymTag for this) */
640     /* FIXME: module.ModuleName isn't correctly set yet if it's passed in SymLoadModule */
641     symt_new_public(module, NULL, module->module.ModuleName, base, 1);
642 #endif
643     
644     /* Add entry point */
645     symt_new_public(module, NULL, "EntryPoint", 
646                     base + nth->OptionalHeader.AddressOfEntryPoint, 1);
647 #if 0
648     /* FIXME: we'd better store addresses linked to sections rather than 
649        absolute values */
650     IMAGE_SECTION_HEADER*       section;
651     /* Add start of sections */
652     section = (IMAGE_SECTION_HEADER*)
653         ((char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
654     for (i = 0; i < nth->FileHeader.NumberOfSections; i++, section++) 
655     {
656         symt_new_public(module, NULL, section->Name, 
657                         RtlImageRvaToVa(nth, mapping, section->VirtualAddress, NULL), 1);
658     }
659 #endif
660
661     /* Add exported functions */
662     if ((exports = RtlImageDirectoryEntryToData(mapping, FALSE,
663                                                 IMAGE_DIRECTORY_ENTRY_EXPORT, &size)))
664     {
665         const WORD*             ordinals = NULL;
666         const DWORD_PTR*        functions = NULL;
667         const DWORD*            names = NULL;
668         unsigned int            j;
669         char                    buffer[16];
670
671         functions = RtlImageRvaToVa(nth, mapping, exports->AddressOfFunctions, NULL);
672         ordinals  = RtlImageRvaToVa(nth, mapping, exports->AddressOfNameOrdinals, NULL);
673         names     = RtlImageRvaToVa(nth, mapping, exports->AddressOfNames, NULL);
674
675         if (functions && ordinals && names)
676         {
677             for (i = 0; i < exports->NumberOfNames; i++)
678             {
679                 if (!names[i]) continue;
680                 symt_new_public(module, NULL,
681                                 RtlImageRvaToVa(nth, mapping, names[i], NULL),
682                                 base + functions[ordinals[i]], 1);
683             }
684
685             for (i = 0; i < exports->NumberOfFunctions; i++)
686             {
687                 if (!functions[i]) continue;
688                 /* Check if we already added it with a name */
689                 for (j = 0; j < exports->NumberOfNames; j++)
690                     if ((ordinals[j] == i) && names[j]) break;
691                 if (j < exports->NumberOfNames) continue;
692                 snprintf(buffer, sizeof(buffer), "%d", i + exports->Base);
693                 symt_new_public(module, NULL, buffer, base + (DWORD)functions[i], 1);
694             }
695         }
696     }
697     /* no real debug info, only entry points */
698     if (module->module.SymType == SymDeferred)
699         module->module.SymType = SymExport;
700     pe_unmap_full(fmap);
701
702     return TRUE;
703 }
704
705 /******************************************************************
706  *              pe_load_debug_info
707  *
708  */
709 BOOL pe_load_debug_info(const struct process* pcs, struct module* module)
710 {
711     BOOL                ret = FALSE;
712
713     if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
714     {
715         ret = pe_load_stabs(pcs, module);
716         ret = pe_load_dwarf(module) || ret;
717         ret = pe_load_msc_debug_info(pcs, module) || ret;
718         ret = ret || pe_load_coff_symbol_table(module); /* FIXME */
719         /* if we still have no debug info (we could only get SymExport at this
720          * point), then do the SymExport except if we have an ELF container,
721          * in which case we'll rely on the export's on the ELF side
722          */
723     }
724     /* FIXME shouldn't we check that? if (!module_get_debug(pcs, module)) */
725     if (pe_load_export_debug_info(pcs, module) && !ret)
726         ret = TRUE;
727
728     return ret;
729 }
730
731 /******************************************************************
732  *              pe_load_native_module
733  *
734  */
735 struct module* pe_load_native_module(struct process* pcs, const WCHAR* name,
736                                      HANDLE hFile, DWORD base, DWORD size)
737 {
738     struct module*              module = NULL;
739     BOOL                        opened = FALSE;
740     struct module_format*       modfmt;
741     WCHAR                       loaded_name[MAX_PATH];
742
743     loaded_name[0] = '\0';
744     if (!hFile)
745     {
746         assert(name);
747
748         if ((hFile = FindExecutableImageExW(name, pcs->search_path, loaded_name, NULL, NULL)) == NULL)
749             return NULL;
750         opened = TRUE;
751     }
752     else if (name) strcpyW(loaded_name, name);
753     else if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
754         FIXME("Trouble ahead (no module name passed in deferred mode)\n");
755     if (!(modfmt = HeapAlloc(GetProcessHeap(), 0, sizeof(struct module_format) + sizeof(struct pe_module_info))))
756         return NULL;
757     modfmt->u.pe_info = (struct pe_module_info*)(modfmt + 1);
758     if (pe_map_file(hFile, &modfmt->u.pe_info->fmap, DMT_PE))
759     {
760         if (!base) base = modfmt->u.pe_info->fmap.u.pe.ntheader.OptionalHeader.ImageBase;
761         if (!size) size = modfmt->u.pe_info->fmap.u.pe.ntheader.OptionalHeader.SizeOfImage;
762
763         module = module_new(pcs, loaded_name, DMT_PE, FALSE, base, size,
764                             modfmt->u.pe_info->fmap.u.pe.ntheader.FileHeader.TimeDateStamp,
765                             modfmt->u.pe_info->fmap.u.pe.ntheader.OptionalHeader.CheckSum);
766         if (module)
767         {
768             modfmt->module = module;
769             modfmt->remove = pe_module_remove;
770             modfmt->loc_compute = NULL;
771
772             module->format_info[DFI_PE] = modfmt;
773             if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
774                 module->module.SymType = SymDeferred;
775             else
776                 pe_load_debug_info(pcs, module);
777         }
778         else
779         {
780             ERR("could not load the module '%s'\n", debugstr_w(loaded_name));
781             pe_unmap_file(&modfmt->u.pe_info->fmap);
782         }
783     }
784     if (!module) HeapFree(GetProcessHeap(), 0, modfmt);
785
786     if (opened) CloseHandle(hFile);
787
788     return module;
789 }
790
791 /******************************************************************
792  *              pe_load_nt_header
793  *
794  */
795 BOOL pe_load_nt_header(HANDLE hProc, DWORD64 base, IMAGE_NT_HEADERS* nth)
796 {
797     IMAGE_DOS_HEADER    dos;
798
799     return ReadProcessMemory(hProc, (char*)(DWORD_PTR)base, &dos, sizeof(dos), NULL) &&
800         dos.e_magic == IMAGE_DOS_SIGNATURE &&
801         ReadProcessMemory(hProc, (char*)(DWORD_PTR)(base + dos.e_lfanew),
802                           nth, sizeof(*nth), NULL) &&
803         nth->Signature == IMAGE_NT_SIGNATURE;
804 }
805
806 /******************************************************************
807  *              pe_load_builtin_module
808  *
809  */
810 struct module* pe_load_builtin_module(struct process* pcs, const WCHAR* name,
811                                       DWORD64 base, DWORD64 size)
812 {
813     struct module*      module = NULL;
814
815     if (base && pcs->dbg_hdr_addr)
816     {
817         IMAGE_NT_HEADERS    nth;
818
819         if (pe_load_nt_header(pcs->handle, base, &nth))
820         {
821             if (!size) size = nth.OptionalHeader.SizeOfImage;
822             module = module_new(pcs, name, DMT_PE, FALSE, base, size,
823                                 nth.FileHeader.TimeDateStamp,
824                                 nth.OptionalHeader.CheckSum);
825         }
826     }
827     return module;
828 }
829
830 /***********************************************************************
831  *           ImageDirectoryEntryToDataEx (DBGHELP.@)
832  *
833  * Search for specified directory in PE image
834  *
835  * PARAMS
836  *
837  *   base    [in]  Image base address
838  *   image   [in]  TRUE - image has been loaded by loader, FALSE - raw file image
839  *   dir     [in]  Target directory index
840  *   size    [out] Receives directory size
841  *   section [out] Receives pointer to section header of section containing directory data
842  *
843  * RETURNS
844  *   Success: pointer to directory data
845  *   Failure: NULL
846  *
847  */
848 PVOID WINAPI ImageDirectoryEntryToDataEx( PVOID base, BOOLEAN image, USHORT dir, PULONG size, PIMAGE_SECTION_HEADER *section )
849 {
850     const IMAGE_NT_HEADERS *nt;
851     DWORD addr;
852
853     *size = 0;
854     if (section) *section = NULL;
855
856     if (!(nt = RtlImageNtHeader( base ))) return NULL;
857     if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
858     if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
859
860     *size = nt->OptionalHeader.DataDirectory[dir].Size;
861     if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)base + addr;
862
863     return RtlImageRvaToVa( nt, base, addr, section );
864 }
865
866 /***********************************************************************
867  *         ImageDirectoryEntryToData   (DBGHELP.@)
868  *
869  * NOTES
870  *   See ImageDirectoryEntryToDataEx
871  */
872 PVOID WINAPI ImageDirectoryEntryToData( PVOID base, BOOLEAN image, USHORT dir, PULONG size )
873 {
874     return ImageDirectoryEntryToDataEx( base, image, dir, size, NULL );
875 }