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