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