ole32: Fix memory leaks in the storage test.
[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 "winternl.h"
34 #include "wine/debug.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(dbghelp);
37
38 /******************************************************************
39  *              pe_load_symbol_table
40  *
41  * Use the COFF symbol table (if any) from the IMAGE_FILE_HEADER to set the absolute address
42  * of global symbols.
43  * Mingw32 requires this for stabs debug information as address for global variables isn't filled in
44  * (this is similar to what is done in elf_module.c when using the .symtab ELF section)
45  */
46 static BOOL pe_load_symbol_table(struct module* module, IMAGE_NT_HEADERS* nth, void* mapping)
47 {
48     const IMAGE_SYMBOL* isym;
49     int                 i, numsym, naux;
50     const char*         strtable;
51     char                tmp[9];
52     const char*         name;
53     struct hash_table_iter      hti;
54     void*               ptr;
55     struct symt_data*   sym;
56     const IMAGE_SECTION_HEADER* sect;
57
58     numsym = nth->FileHeader.NumberOfSymbols;
59     if (!nth->FileHeader.PointerToSymbolTable || !numsym)
60         return TRUE;
61     isym = (const IMAGE_SYMBOL*)((char*)mapping + nth->FileHeader.PointerToSymbolTable);
62     /* FIXME: no way to get strtable size */
63     strtable = (const char*)&isym[numsym];
64     sect = IMAGE_FIRST_SECTION(nth);
65
66     for (i = 0; i < numsym; i+= naux, isym += naux)
67     {
68         if (isym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL &&
69             isym->SectionNumber > 0 && isym->SectionNumber <= nth->FileHeader.NumberOfSections)
70         {
71             if (isym->N.Name.Short)
72             {
73                 name = memcpy(tmp, isym->N.ShortName, 8);
74                 tmp[8] = '\0';
75             }
76             else name = strtable + isym->N.Name.Long;
77             if (name[0] == '_') name++;
78             hash_table_iter_init(&module->ht_symbols, &hti, name);
79             while ((ptr = hash_table_iter_up(&hti)))
80             {
81                 sym = GET_ENTRY(ptr, struct symt_data, hash_elt);
82                 if (sym->symt.tag == SymTagData &&
83                     (sym->kind == DataIsGlobal || sym->kind == DataIsFileStatic) &&
84                     !strcmp(sym->hash_elt.name, name))
85                 {
86                     TRACE("Changing absolute address for %d.%s: %lx -> %s\n",
87                           isym->SectionNumber, name, sym->u.var.offset,
88                           wine_dbgstr_longlong(module->module.BaseOfImage +
89                                                sect[isym->SectionNumber - 1].VirtualAddress + isym->Value));
90                     sym->u.var.offset = module->module.BaseOfImage +
91                         sect[isym->SectionNumber - 1].VirtualAddress + isym->Value;
92                     break;
93                 }
94             }
95         }
96         naux = isym->NumberOfAuxSymbols + 1;
97     }
98     return TRUE;
99 }
100
101 /******************************************************************
102  *              pe_load_stabs
103  *
104  * look for stabs information in PE header (it's how the mingw compiler provides 
105  * its debugging information)
106  */
107 static BOOL pe_load_stabs(const struct process* pcs, struct module* module, 
108                           void* mapping, IMAGE_NT_HEADERS* nth)
109 {
110     IMAGE_SECTION_HEADER*       section;
111     int                         i, stabsize = 0, stabstrsize = 0;
112     unsigned int                stabs = 0, stabstr = 0;
113     BOOL                        ret = FALSE;
114
115     section = (IMAGE_SECTION_HEADER*)
116         ((char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
117     for (i = 0; i < nth->FileHeader.NumberOfSections; i++, section++)
118     {
119         if (!strcasecmp((const char*)section->Name, ".stab"))
120         {
121             stabs = section->VirtualAddress;
122             stabsize = section->SizeOfRawData;
123         }
124         else if (!strncasecmp((const char*)section->Name, ".stabstr", 8))
125         {
126             stabstr = section->VirtualAddress;
127             stabstrsize = section->SizeOfRawData;
128         }
129     }
130
131     if (stabstrsize && stabsize)
132     {
133         ret = stabs_parse(module, 
134                           module->module.BaseOfImage - nth->OptionalHeader.ImageBase, 
135                           RtlImageRvaToVa(nth, mapping, stabs, NULL),
136                           stabsize,
137                           RtlImageRvaToVa(nth, mapping, stabstr, NULL),
138                           stabstrsize,
139                           NULL, NULL);
140         if (ret) pe_load_symbol_table(module, nth, mapping);
141     }
142
143     TRACE("%s the STABS debug info\n", ret ? "successfully loaded" : "failed to load");
144     return ret;
145 }
146
147 /******************************************************************
148  *              pe_load_dbg_file
149  *
150  * loads a .dbg file
151  */
152 static BOOL pe_load_dbg_file(const struct process* pcs, struct module* module,
153                              const char* dbg_name, DWORD timestamp)
154 {
155     char                                tmp[MAX_PATH];
156     HANDLE                              hFile = INVALID_HANDLE_VALUE, hMap = 0;
157     const BYTE*                         dbg_mapping = NULL;
158     BOOL                                ret = FALSE;
159
160     TRACE("Processing DBG file %s\n", debugstr_a(dbg_name));
161
162     if (path_find_symbol_file(pcs, dbg_name, NULL, timestamp, 0, tmp, &module->module.DbgUnmatched) &&
163         (hFile = CreateFileA(tmp, GENERIC_READ, FILE_SHARE_READ, NULL,
164                              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE &&
165         ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0) &&
166         ((dbg_mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL))
167     {
168         const IMAGE_SEPARATE_DEBUG_HEADER*      hdr;
169         const IMAGE_SECTION_HEADER*             sectp;
170         const IMAGE_DEBUG_DIRECTORY*            dbg;
171
172         hdr = (const IMAGE_SEPARATE_DEBUG_HEADER*)dbg_mapping;
173         /* section headers come immediately after debug header */
174         sectp = (const IMAGE_SECTION_HEADER*)(hdr + 1);
175         /* and after that and the exported names comes the debug directory */
176         dbg = (const IMAGE_DEBUG_DIRECTORY*)
177             (dbg_mapping + sizeof(*hdr) +
178              hdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
179              hdr->ExportedNamesSize);
180
181         ret = pe_load_debug_directory(pcs, module, dbg_mapping, sectp,
182                                       hdr->NumberOfSections, dbg,
183                                       hdr->DebugDirectorySize / sizeof(*dbg));
184     }
185     else
186         ERR("Couldn't find .DBG file %s (%s)\n", debugstr_a(dbg_name), debugstr_a(tmp));
187
188     if (dbg_mapping) UnmapViewOfFile(dbg_mapping);
189     if (hMap) CloseHandle(hMap);
190     if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile);
191     return ret;
192 }
193
194 /******************************************************************
195  *              pe_load_msc_debug_info
196  *
197  * Process MSC debug information in PE file.
198  */
199 static BOOL pe_load_msc_debug_info(const struct process* pcs, 
200                                    struct module* module,
201                                    void* mapping, const IMAGE_NT_HEADERS* nth)
202 {
203     BOOL                        ret = FALSE;
204     const IMAGE_DATA_DIRECTORY* dir;
205     const IMAGE_DEBUG_DIRECTORY*dbg = NULL;
206     int                         nDbg;
207
208     /* Read in debug directory */
209     dir = nth->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_DEBUG;
210     nDbg = dir->Size / sizeof(IMAGE_DEBUG_DIRECTORY);
211     if (!nDbg) return FALSE;
212
213     dbg = RtlImageRvaToVa(nth, mapping, dir->VirtualAddress, NULL);
214
215     /* Parse debug directory */
216     if (nth->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED)
217     {
218         /* Debug info is stripped to .DBG file */
219         const IMAGE_DEBUG_MISC* misc = (const IMAGE_DEBUG_MISC*)
220             ((const char*)mapping + dbg->PointerToRawData);
221
222         if (nDbg != 1 || dbg->Type != IMAGE_DEBUG_TYPE_MISC ||
223             misc->DataType != IMAGE_DEBUG_MISC_EXENAME)
224         {
225             WINE_ERR("-Debug info stripped, but no .DBG file in module %s\n",
226                      debugstr_w(module->module.ModuleName));
227         }
228         else
229         {
230             ret = pe_load_dbg_file(pcs, module, (const char*)misc->Data, nth->FileHeader.TimeDateStamp);
231         }
232     }
233     else
234     {
235         const IMAGE_SECTION_HEADER *sectp = (const IMAGE_SECTION_HEADER*)((const char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
236         /* Debug info is embedded into PE module */
237         ret = pe_load_debug_directory(pcs, module, mapping, sectp,
238             nth->FileHeader.NumberOfSections, dbg, nDbg);
239     }
240
241     return ret;
242 }
243
244 /***********************************************************************
245  *                      pe_load_export_debug_info
246  */
247 static BOOL pe_load_export_debug_info(const struct process* pcs, 
248                                       struct module* module, 
249                                       void* mapping, const IMAGE_NT_HEADERS* nth)
250 {
251     unsigned int                        i;
252     const IMAGE_EXPORT_DIRECTORY*       exports;
253     DWORD                               base = module->module.BaseOfImage;
254     DWORD                               size;
255
256     if (dbghelp_options & SYMOPT_NO_PUBLICS) return TRUE;
257
258 #if 0
259     /* Add start of DLL (better use the (yet unimplemented) Exe SymTag for this) */
260     /* FIXME: module.ModuleName isn't correctly set yet if it's passed in SymLoadModule */
261     symt_new_public(module, NULL, module->module.ModuleName, base, 1,
262                     TRUE /* FIXME */, TRUE /* FIXME */);
263 #endif
264     
265     /* Add entry point */
266     symt_new_public(module, NULL, "EntryPoint", 
267                     base + nth->OptionalHeader.AddressOfEntryPoint, 1,
268                     TRUE, TRUE);
269 #if 0
270     /* FIXME: we'd better store addresses linked to sections rather than 
271        absolute values */
272     IMAGE_SECTION_HEADER*       section;
273     /* Add start of sections */
274     section = (IMAGE_SECTION_HEADER*)
275         ((char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
276     for (i = 0; i < nth->FileHeader.NumberOfSections; i++, section++) 
277     {
278         symt_new_public(module, NULL, section->Name, 
279                         RtlImageRvaToVa(nth, mapping, section->VirtualAddress, NULL), 
280                         1, TRUE /* FIXME */, TRUE /* FIXME */);
281     }
282 #endif
283
284     /* Add exported functions */
285     if ((exports = RtlImageDirectoryEntryToData(mapping, FALSE,
286                                                 IMAGE_DIRECTORY_ENTRY_EXPORT, &size)))
287     {
288         const WORD*             ordinals = NULL;
289         const DWORD_PTR*        functions = NULL;
290         const DWORD*            names = NULL;
291         unsigned int            j;
292         char                    buffer[16];
293
294         functions = RtlImageRvaToVa(nth, mapping, exports->AddressOfFunctions, NULL);
295         ordinals  = RtlImageRvaToVa(nth, mapping, exports->AddressOfNameOrdinals, NULL);
296         names     = RtlImageRvaToVa(nth, mapping, exports->AddressOfNames, NULL);
297
298         if (functions && ordinals && names)
299         {
300             for (i = 0; i < exports->NumberOfNames; i++)
301             {
302                 if (!names[i]) continue;
303                 symt_new_public(module, NULL,
304                                 RtlImageRvaToVa(nth, mapping, names[i], NULL),
305                                 base + functions[ordinals[i]],
306                                 1, TRUE /* FIXME */, TRUE /* FIXME */);
307             }
308
309             for (i = 0; i < exports->NumberOfFunctions; i++)
310             {
311                 if (!functions[i]) continue;
312                 /* Check if we already added it with a name */
313                 for (j = 0; j < exports->NumberOfNames; j++)
314                     if ((ordinals[j] == i) && names[j]) break;
315                 if (j < exports->NumberOfNames) continue;
316                 snprintf(buffer, sizeof(buffer), "%d", i + exports->Base);
317                 symt_new_public(module, NULL, buffer, base + (DWORD)functions[i], 1,
318                                 TRUE /* FIXME */, TRUE /* FIXME */);
319             }
320         }
321     }
322     /* no real debug info, only entry points */
323     if (module->module.SymType == SymDeferred)
324         module->module.SymType = SymExport;
325     return TRUE;
326 }
327
328 /******************************************************************
329  *              pe_load_debug_info
330  *
331  */
332 BOOL pe_load_debug_info(const struct process* pcs, struct module* module)
333 {
334     BOOL                ret = FALSE;
335     HANDLE              hFile;
336     HANDLE              hMap;
337     void*               mapping;
338     IMAGE_NT_HEADERS*   nth;
339
340     hFile = CreateFileW(module->module.LoadedImageName, GENERIC_READ, FILE_SHARE_READ,
341                         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
342     if (hFile == INVALID_HANDLE_VALUE) return ret;
343     if ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0)
344     {
345         if ((mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
346         {
347             nth = RtlImageNtHeader(mapping);
348
349             if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
350             {
351                 ret = pe_load_stabs(pcs, module, mapping, nth) ||
352                     pe_load_msc_debug_info(pcs, module, mapping, nth);
353                 /* if we still have no debug info (we could only get SymExport at this
354                  * point), then do the SymExport except if we have an ELF container, 
355                  * in which case we'll rely on the export's on the ELF side
356                  */
357             }
358 /* FIXME shouldn't we check that? if (!module_get_debug(pcs, module))l */
359             if (pe_load_export_debug_info(pcs, module, mapping, nth) && !ret)
360                 ret = TRUE;
361             UnmapViewOfFile(mapping);
362         }
363         CloseHandle(hMap);
364     }
365     CloseHandle(hFile);
366
367     return ret;
368 }
369
370 /******************************************************************
371  *              pe_load_native_module
372  *
373  */
374 struct module* pe_load_native_module(struct process* pcs, const WCHAR* name,
375                                      HANDLE hFile, DWORD base, DWORD size)
376 {
377     struct module*      module = NULL;
378     BOOL                opened = FALSE;
379     HANDLE              hMap;
380     WCHAR               loaded_name[MAX_PATH];
381
382     loaded_name[0] = '\0';
383     if (!hFile)
384     {
385
386         assert(name);
387
388         if ((hFile = FindExecutableImageExW(name, pcs->search_path, loaded_name, NULL, NULL)) == NULL)
389             return NULL;
390         opened = TRUE;
391     }
392     else if (name) strcpyW(loaded_name, name);
393     else if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
394         FIXME("Trouble ahead (no module name passed in deferred mode)\n");
395
396     if ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != NULL)
397     {
398         void*   mapping;
399
400         if ((mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
401         {
402             IMAGE_NT_HEADERS*   nth = RtlImageNtHeader(mapping);
403
404             if (nth)
405             {
406                 if (!base) base = nth->OptionalHeader.ImageBase;
407                 if (!size) size = nth->OptionalHeader.SizeOfImage;
408
409                 module = module_new(pcs, loaded_name, DMT_PE, FALSE, base, size,
410                                     nth->FileHeader.TimeDateStamp,
411                                     nth->OptionalHeader.CheckSum);
412                 if (module)
413                 {
414                     if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
415                         module->module.SymType = SymDeferred;
416                     else
417                         pe_load_debug_info(pcs, module);
418                 }
419                 else
420                     ERR("could not load the module '%s'\n", debugstr_w(loaded_name));
421             }
422             UnmapViewOfFile(mapping);
423         }
424         CloseHandle(hMap);
425     }
426     if (opened) CloseHandle(hFile);
427
428     return module;
429 }
430
431 /******************************************************************
432  *              pe_load_nt_header
433  *
434  */
435 BOOL pe_load_nt_header(HANDLE hProc, DWORD64 base, IMAGE_NT_HEADERS* nth)
436 {
437     IMAGE_DOS_HEADER    dos;
438
439     return ReadProcessMemory(hProc, (char*)(DWORD_PTR)base, &dos, sizeof(dos), NULL) &&
440         dos.e_magic == IMAGE_DOS_SIGNATURE &&
441         ReadProcessMemory(hProc, (char*)(DWORD_PTR)(base + dos.e_lfanew),
442                           nth, sizeof(*nth), NULL) &&
443         nth->Signature == IMAGE_NT_SIGNATURE;
444 }
445
446 /******************************************************************
447  *              pe_load_builtin_module
448  *
449  */
450 struct module* pe_load_builtin_module(struct process* pcs, const WCHAR* name,
451                                       DWORD64 base, DWORD64 size)
452 {
453     struct module*      module = NULL;
454
455     if (base && pcs->dbg_hdr_addr)
456     {
457         IMAGE_NT_HEADERS    nth;
458
459         if (pe_load_nt_header(pcs->handle, base, &nth))
460         {
461             if (!size) size = nth.OptionalHeader.SizeOfImage;
462             module = module_new(pcs, name, DMT_PE, FALSE, base, size,
463                                 nth.FileHeader.TimeDateStamp,
464                                 nth.OptionalHeader.CheckSum);
465         }
466     }
467     return module;
468 }
469
470 /***********************************************************************
471  *           ImageDirectoryEntryToDataEx (DBGHELP.@)
472  *
473  * Search for specified directory in PE image
474  *
475  * PARAMS
476  *
477  *   base    [in]  Image base address
478  *   image   [in]  TRUE - image has been loaded by loader, FALSE - raw file image
479  *   dir     [in]  Target directory index
480  *   size    [out] Receives directory size
481  *   section [out] Receives pointer to section header of section containing directory data
482  *
483  * RETURNS
484  *   Success: pointer to directory data
485  *   Failure: NULL
486  *
487  */
488 PVOID WINAPI ImageDirectoryEntryToDataEx( PVOID base, BOOLEAN image, USHORT dir, PULONG size, PIMAGE_SECTION_HEADER *section )
489 {
490     const IMAGE_NT_HEADERS *nt;
491     DWORD addr;
492
493     *size = 0;
494     if (section) *section = NULL;
495
496     if (!(nt = RtlImageNtHeader( base ))) return NULL;
497     if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
498     if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
499
500     *size = nt->OptionalHeader.DataDirectory[dir].Size;
501     if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)base + addr;
502
503     return RtlImageRvaToVa( nt, base, addr, section );
504 }
505
506 /***********************************************************************
507  *         ImageDirectoryEntryToData   (DBGHELP.@)
508  *
509  * NOTES
510  *   See ImageDirectoryEntryToDataEx
511  */
512 PVOID WINAPI ImageDirectoryEntryToData( PVOID base, BOOLEAN image, USHORT dir, PULONG size )
513 {
514     return ImageDirectoryEntryToDataEx( base, image, dir, size, NULL );
515 }