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