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