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