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