Update the address of the Free Software Foundation.
[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,      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 <stdlib.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <assert.h>
29
30 #include "dbghelp_private.h"
31 #include "winreg.h"
32 #include "winternl.h"
33 #include "wine/debug.h"
34 #include "winnls.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                           const 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, (void*)mapping, stabs, NULL),
73                           stabsize,
74                           RtlImageRvaToVa(nth, (void*)mapping, stabstr, NULL),
75                           stabstrsize);
76     }
77     return ret;
78 }
79
80 static BOOL CALLBACK dbg_match(char* file, void* user)
81 {
82     /* accept first file */
83     return FALSE;
84 }
85
86 /******************************************************************
87  *              pe_load_dbg_file
88  *
89  * loads a .dbg file
90  */
91 static BOOL pe_load_dbg_file(const struct process* pcs, struct module* module,
92                              const char* dbg_name, DWORD timestamp)
93 {
94     char                                tmp[MAX_PATH];
95     HANDLE                              hFile = INVALID_HANDLE_VALUE, hMap = 0;
96     const BYTE*                         dbg_mapping = NULL;
97     const IMAGE_SEPARATE_DEBUG_HEADER*  hdr;
98     const IMAGE_DEBUG_DIRECTORY*        dbg;
99     BOOL                                ret = FALSE;
100
101     WINE_TRACE("Processing DBG file %s\n", dbg_name);
102
103     if (SymFindFileInPath(pcs->handle, NULL, (char*)dbg_name, 
104                           NULL, 0, 0, 0,
105                           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 = CreateFileMappingA(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                      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", dbg_name, debugstr_a(tmp));
144
145     if (dbg_mapping) UnmapViewOfFile((void*)dbg_mapping);
146     if (hMap) CloseHandle(hMap);
147     if (hFile != NULL) 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                                    const 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, (void*)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                      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                                       const 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, (void*)mapping, section->VirtualAddress, NULL), 
237                         1, TRUE /* FIXME */, TRUE /* FIXME */);
238     }
239 #endif
240
241     /* Add exported functions */
242     if ((exports = RtlImageDirectoryEntryToData((void*)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, (void*)mapping, exports->AddressOfFunctions, NULL);
252         ordinals  = RtlImageRvaToVa(nth, (void*)mapping, exports->AddressOfNameOrdinals, NULL);
253         names     = RtlImageRvaToVa(nth, (void*)mapping, exports->AddressOfNames, NULL);
254
255         for (i = 0; i < exports->NumberOfNames; i++) 
256         {
257             if (!names[i]) continue;
258             symt_new_public(module, NULL, 
259                             RtlImageRvaToVa(nth, (void*)mapping, names[i], NULL),
260                             base + functions[ordinals[i]], 
261                             1, TRUE /* FIXME */, TRUE /* FIXME */);
262         }
263             
264         for (i = 0; i < exports->NumberOfFunctions; i++) 
265         {
266             if (!functions[i]) continue;
267             /* Check if we already added it with a name */
268             for (j = 0; j < exports->NumberOfNames; j++)
269                 if ((ordinals[j] == i) && names[j]) break;
270             if (j < exports->NumberOfNames) continue;
271             snprintf(buffer, sizeof(buffer), "%ld", i + exports->Base);
272             symt_new_public(module, NULL, buffer, base + (DWORD)functions[i], 1,
273                             TRUE /* FIXME */, TRUE /* FIXME */);
274         }
275     }
276     /* no real debug info, only entry points */
277     if (module->module.SymType == SymDeferred)
278         module->module.SymType = SymExport;
279     return TRUE;
280 }
281
282 /******************************************************************
283  *              pe_load_debug_info
284  *
285  */
286 BOOL pe_load_debug_info(const struct process* pcs, struct module* module)
287 {
288     BOOL                ret = FALSE;
289     HANDLE              hFile;
290     HANDLE              hMap;
291     void*               mapping;
292     IMAGE_NT_HEADERS*   nth;
293
294     hFile = CreateFileA(module->module.LoadedImageName, GENERIC_READ, FILE_SHARE_READ,
295                         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
296     if (hFile == INVALID_HANDLE_VALUE) return ret;
297     if ((hMap = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0)
298     {
299         if ((mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
300         {
301             nth = RtlImageNtHeader(mapping);
302
303             if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
304             {
305                 ret = pe_load_stabs(pcs, module, mapping, nth) ||
306                     pe_load_msc_debug_info(pcs, module, mapping, nth);
307                 /* if we still have no debug info (we could only get SymExport at this
308                  * point), then do the SymExport except if we have an ELF container, 
309                  * in which case we'll rely on the export's on the ELF side
310                  */
311             }
312 /* FIXME shouldn't we check that? if (!module_get_debug(pcs, module))l */
313             if (pe_load_export_debug_info(pcs, module, mapping, nth) && !ret)
314                 ret = TRUE;
315             UnmapViewOfFile(mapping);
316         }
317         CloseHandle(hMap);
318     }
319     CloseHandle(hFile);
320
321     return ret;
322 }
323
324 /******************************************************************
325  *              pe_load_module
326  *
327  */
328 struct module* pe_load_module(struct process* pcs, const char* name,
329                               HANDLE hFile, DWORD base, DWORD size)
330 {
331     struct module*      module = NULL;
332     BOOL                opened = FALSE;
333     HANDLE              hMap;
334     void*               mapping;
335     char                loaded_name[MAX_PATH];
336
337     loaded_name[0] = '\0';
338     if (!hFile)
339     {
340         unsigned len = WideCharToMultiByte(CP_ACP,0, pcs->search_path, -1, NULL, 0, NULL, NULL);
341         char* sp;
342
343         if (!name)
344         {
345             /* FIXME SetLastError */
346             return NULL;
347         }
348         sp = HeapAlloc(GetProcessHeap(), 0, len);
349         if (!sp) return FALSE;
350         WideCharToMultiByte(CP_ACP,0, pcs->search_path, -1, sp, len, NULL, NULL);
351
352         if ((hFile = FindExecutableImage(name, sp, loaded_name)) == NULL)
353             return NULL;
354         opened = TRUE;
355     }
356     else if (name) strcpy(loaded_name, name);
357     else if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
358         FIXME("Trouble ahead (no module name passed in deferred mode)\n");
359     if (!(module = module_find_by_name(pcs, loaded_name, DMT_PE)) &&
360         (hMap = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != NULL)
361     {
362         if ((mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
363         {
364             IMAGE_NT_HEADERS*   nth = RtlImageNtHeader(mapping);
365
366             if (nth)
367             {
368                 if (!base) base = nth->OptionalHeader.ImageBase;
369                 if (!size) size = nth->OptionalHeader.SizeOfImage;
370             
371                 module = module_new(pcs, loaded_name, DMT_PE, FALSE, base, size,
372                                     nth->FileHeader.TimeDateStamp, 
373                                     nth->OptionalHeader.CheckSum);
374                 if (module)
375                 {
376                     if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
377                         module->module.SymType = SymDeferred;
378                     else
379                         pe_load_debug_info(pcs, module);
380                 }
381             }
382             UnmapViewOfFile(mapping);
383         }
384         CloseHandle(hMap);
385     }
386     if (opened) CloseHandle(hFile);
387
388     return module;
389 }
390
391 /******************************************************************
392  *              pe_load_nt_header
393  *
394  */
395 BOOL pe_load_nt_header(HANDLE hProc, DWORD base, IMAGE_NT_HEADERS* nth)
396 {
397     IMAGE_DOS_HEADER    dos;
398
399     return ReadProcessMemory(hProc, (char*)base, &dos, sizeof(dos), NULL) &&
400         dos.e_magic == IMAGE_DOS_SIGNATURE &&
401         ReadProcessMemory(hProc, (char*)(base + dos.e_lfanew), 
402                           nth, sizeof(*nth), NULL) &&
403         nth->Signature == IMAGE_NT_SIGNATURE;
404 }
405
406 /******************************************************************
407  *              pe_load_module_from_pcs
408  *
409  */
410 struct module* pe_load_module_from_pcs(struct process* pcs, const char* name, 
411                                        const char* mod_name, DWORD base, DWORD size)
412 {
413     struct module*      module;
414     const char*         ptr;
415
416     if ((module = module_find_by_name(pcs, name, DMT_PE))) return module;
417     if (mod_name) ptr = mod_name;
418     else
419     {
420         for (ptr = name + strlen(name) - 1; ptr >= name; ptr--)
421         {
422             if (*ptr == '/' || *ptr == '\\')
423             {
424                 ptr++;
425                 break;
426             }
427         }
428     }
429     if (ptr && (module = module_find_by_name(pcs, ptr, DMT_PE))) return module;
430     if (base)
431     {
432         if (pcs->dbg_hdr_addr)
433         {
434             IMAGE_NT_HEADERS    nth;
435
436             if (pe_load_nt_header(pcs->handle, base, &nth))
437             {
438                 if (!size) size = nth.OptionalHeader.SizeOfImage;
439                 module = module_new(pcs, name, DMT_PE, FALSE, base, size,
440                                     nth.FileHeader.TimeDateStamp, nth.OptionalHeader.CheckSum);
441             }
442         } else if (size)
443             module = module_new(pcs, name, DMT_PE, FALSE, base, size, 0 /* FIXME */, 0 /* FIXME */);
444     }
445     return module;
446 }