dbghelp: Fix read beyond end of field in module_get_debug.
[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 "winternl.h"
32 #include "wine/debug.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(dbghelp);
35
36 /******************************************************************
37  *              pe_load_stabs
38  *
39  * look for stabs information in PE header (it's how the mingw compiler provides 
40  * its debugging information)
41  */
42 static BOOL pe_load_stabs(const struct process* pcs, struct module* module, 
43                           void* mapping, IMAGE_NT_HEADERS* nth)
44 {
45     IMAGE_SECTION_HEADER*       section;
46     int                         i, stabsize = 0, stabstrsize = 0;
47     unsigned int                stabs = 0, stabstr = 0;
48     BOOL                        ret = FALSE;
49
50     section = (IMAGE_SECTION_HEADER*)
51         ((char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
52     for (i = 0; i < nth->FileHeader.NumberOfSections; i++, section++)
53     {
54         if (!strcasecmp((const char*)section->Name, ".stab"))
55         {
56             stabs = section->VirtualAddress;
57             stabsize = section->SizeOfRawData;
58         }
59         else if (!strncasecmp((const char*)section->Name, ".stabstr", 8))
60         {
61             stabstr = section->VirtualAddress;
62             stabstrsize = section->SizeOfRawData;
63         }
64     }
65
66     if (stabstrsize && stabsize)
67     {
68         ret = stabs_parse(module, 
69                           module->module.BaseOfImage - nth->OptionalHeader.ImageBase, 
70                           RtlImageRvaToVa(nth, mapping, stabs, NULL),
71                           stabsize,
72                           RtlImageRvaToVa(nth, mapping, stabstr, NULL),
73                           stabstrsize);
74     }
75
76     TRACE("%s the STABS debug info\n", ret ? "successfully loaded" : "failed to load");
77     return ret;
78 }
79
80 static BOOL CALLBACK dbg_match(const 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", debugstr_a(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 = CreateFileMappingW(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                      debugstr_a(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", debugstr_a(dbg_name), debugstr_a(tmp));
142
143     if (dbg_mapping) UnmapViewOfFile(dbg_mapping);
144     if (hMap) CloseHandle(hMap);
145     if (hFile != INVALID_HANDLE_VALUE) 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                                    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, 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                      debugstr_w(module->module.ModuleName));
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                                       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, mapping, section->VirtualAddress, NULL), 
235                         1, TRUE /* FIXME */, TRUE /* FIXME */);
236     }
237 #endif
238
239     /* Add exported functions */
240     if ((exports = RtlImageDirectoryEntryToData(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, mapping, exports->AddressOfFunctions, NULL);
250         ordinals  = RtlImageRvaToVa(nth, mapping, exports->AddressOfNameOrdinals, NULL);
251         names     = RtlImageRvaToVa(nth, mapping, exports->AddressOfNames, NULL);
252
253         if (functions && ordinals && names)
254         {
255             for (i = 0; i < exports->NumberOfNames; i++)
256             {
257                 if (!names[i]) continue;
258                 symt_new_public(module, NULL,
259                                 RtlImageRvaToVa(nth, 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), "%d", i + exports->Base);
272                 symt_new_public(module, NULL, buffer, base + (DWORD)functions[i], 1,
273                                 TRUE /* FIXME */, TRUE /* FIXME */);
274             }
275         }
276     }
277     /* no real debug info, only entry points */
278     if (module->module.SymType == SymDeferred)
279         module->module.SymType = SymExport;
280     return TRUE;
281 }
282
283 /******************************************************************
284  *              pe_load_debug_info
285  *
286  */
287 BOOL pe_load_debug_info(const struct process* pcs, struct module* module)
288 {
289     BOOL                ret = FALSE;
290     HANDLE              hFile;
291     HANDLE              hMap;
292     void*               mapping;
293     IMAGE_NT_HEADERS*   nth;
294
295     hFile = CreateFileW(module->module.LoadedImageName, GENERIC_READ, FILE_SHARE_READ,
296                         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
297     if (hFile == INVALID_HANDLE_VALUE) return ret;
298     if ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0)
299     {
300         if ((mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
301         {
302             nth = RtlImageNtHeader(mapping);
303
304             if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
305             {
306                 ret = pe_load_stabs(pcs, module, mapping, nth) ||
307                     pe_load_msc_debug_info(pcs, module, mapping, nth);
308                 /* if we still have no debug info (we could only get SymExport at this
309                  * point), then do the SymExport except if we have an ELF container, 
310                  * in which case we'll rely on the export's on the ELF side
311                  */
312             }
313 /* FIXME shouldn't we check that? if (!module_get_debug(pcs, module))l */
314             if (pe_load_export_debug_info(pcs, module, mapping, nth) && !ret)
315                 ret = TRUE;
316             UnmapViewOfFile(mapping);
317         }
318         CloseHandle(hMap);
319     }
320     CloseHandle(hFile);
321
322     return ret;
323 }
324
325 /******************************************************************
326  *              pe_load_native_module
327  *
328  */
329 struct module* pe_load_native_module(struct process* pcs, const WCHAR* name,
330                                      HANDLE hFile, DWORD base, DWORD size)
331 {
332     struct module*      module = NULL;
333     BOOL                opened = FALSE;
334     HANDLE              hMap;
335     WCHAR               loaded_name[MAX_PATH];
336
337     loaded_name[0] = '\0';
338     if (!hFile)
339     {
340
341         assert(name);
342
343         if ((hFile = FindExecutableImageExW(name, pcs->search_path, loaded_name, NULL, NULL)) == NULL)
344             return NULL;
345         opened = TRUE;
346     }
347     else if (name) strcpyW(loaded_name, name);
348     else if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
349         FIXME("Trouble ahead (no module name passed in deferred mode)\n");
350
351     if ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != NULL)
352     {
353         void*   mapping;
354
355         if ((mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
356         {
357             IMAGE_NT_HEADERS*   nth = RtlImageNtHeader(mapping);
358
359             if (nth)
360             {
361                 if (!base) base = nth->OptionalHeader.ImageBase;
362                 if (!size) size = nth->OptionalHeader.SizeOfImage;
363
364                 module = module_new(pcs, loaded_name, DMT_PE, FALSE, base, size,
365                                     nth->FileHeader.TimeDateStamp,
366                                     nth->OptionalHeader.CheckSum);
367                 if (module)
368                 {
369                     if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
370                         module->module.SymType = SymDeferred;
371                     else
372                         pe_load_debug_info(pcs, module);
373                 }
374                 else
375                     ERR("could not load the module '%s'\n", debugstr_w(loaded_name));
376             }
377             UnmapViewOfFile(mapping);
378         }
379         CloseHandle(hMap);
380     }
381     if (opened) CloseHandle(hFile);
382
383     return module;
384 }
385
386 /******************************************************************
387  *              pe_load_nt_header
388  *
389  */
390 BOOL pe_load_nt_header(HANDLE hProc, DWORD base, IMAGE_NT_HEADERS* nth)
391 {
392     IMAGE_DOS_HEADER    dos;
393
394     return ReadProcessMemory(hProc, (char*)base, &dos, sizeof(dos), NULL) &&
395         dos.e_magic == IMAGE_DOS_SIGNATURE &&
396         ReadProcessMemory(hProc, (char*)(base + dos.e_lfanew), 
397                           nth, sizeof(*nth), NULL) &&
398         nth->Signature == IMAGE_NT_SIGNATURE;
399 }
400
401 /******************************************************************
402  *              pe_load_builtin_module
403  *
404  */
405 struct module* pe_load_builtin_module(struct process* pcs, const WCHAR* name,
406                                       DWORD base, DWORD size)
407 {
408     struct module*      module = NULL;
409
410     if (base && pcs->dbg_hdr_addr)
411     {
412         IMAGE_NT_HEADERS    nth;
413
414         if (pe_load_nt_header(pcs->handle, base, &nth))
415         {
416             if (!size) size = nth.OptionalHeader.SizeOfImage;
417             module = module_new(pcs, name, DMT_PE, FALSE, base, size,
418                                 nth.FileHeader.TimeDateStamp,
419                                 nth.OptionalHeader.CheckSum);
420         }
421     }
422     return module;
423 }
424
425 /***********************************************************************
426  *           ImageDirectoryEntryToDataEx (DBGHELP.@)
427  *
428  * Search for specified directory in PE image
429  *
430  * PARAMS
431  *
432  *   base    [in]  Image base address
433  *   image   [in]  TRUE - image has been loaded by loader, FALSE - raw file image
434  *   dir     [in]  Target directory index
435  *   size    [out] Receives directory size
436  *   section [out] Receives pointer to section header of section containing directory data
437  *
438  * RETURNS
439  *   Success: pointer to directory data
440  *   Failure: NULL
441  *
442  */
443 PVOID WINAPI ImageDirectoryEntryToDataEx( PVOID base, BOOLEAN image, USHORT dir, PULONG size, PIMAGE_SECTION_HEADER *section )
444 {
445     const IMAGE_NT_HEADERS *nt;
446     DWORD addr;
447
448     *size = 0;
449
450     if (!(nt = RtlImageNtHeader( base ))) return NULL;
451     if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
452     if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
453
454     *size = nt->OptionalHeader.DataDirectory[dir].Size;
455     if (image || addr < nt->OptionalHeader.SizeOfHeaders)
456     {
457         if (*section) *section = NULL;
458         return (char *)base + addr;
459     }
460
461     return RtlImageRvaToVa( nt, (HMODULE)base, addr, section );
462 }
463
464 /***********************************************************************
465  *         ImageDirectoryEntryToData   (DBGHELP.@)
466  *
467  * NOTES
468  *   See ImageDirectoryEntryToDataEx
469  */
470 PVOID WINAPI ImageDirectoryEntryToData( PVOID base, BOOLEAN image, USHORT dir, PULONG size )
471 {
472     return ImageDirectoryEntryToDataEx( base, image, dir, size, NULL );
473 }