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