Started implementing support for the SubSystemTib field in the TEB of
[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 SYM_TYPE 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     SYM_TYPE                    sym_type = SymNone;
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         sym_type = stabs_parse(module, mapping, module->module.BaseOfImage, 
70                                stabs, stabsize, stabstr, stabstrsize);
71     }
72     return sym_type;
73 }
74
75 /******************************************************************
76  *              pe_load_dbg_file
77  *
78  * loads a .dbg file
79  */
80 static SYM_TYPE pe_load_dbg_file(const struct process* pcs, struct module* module,
81                                  char* dbg_name, DWORD timestamp)
82 {
83     char                        tmp[MAX_PATH];
84     HANDLE                      hFile, hMap = 0;
85     const BYTE*                 dbg_mapping = NULL;
86     PIMAGE_SEPARATE_DEBUG_HEADER hdr;
87     PIMAGE_DEBUG_DIRECTORY      dbg;
88     SYM_TYPE                    sym_type = -1;
89
90     WINE_TRACE("Processing DBG file %s\n", dbg_name);
91
92     if ((hFile = FindDebugInfoFile(dbg_name, pcs->search_path, tmp)) != NULL &&
93         ((hMap = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0) &&
94         ((dbg_mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL))
95     {
96         hdr = (PIMAGE_SEPARATE_DEBUG_HEADER)dbg_mapping;
97         if (hdr->TimeDateStamp != timestamp)
98         {
99             WINE_ERR("Warning - %s has incorrect internal timestamp\n",
100                      dbg_name);
101             /*
102              * Well, sometimes this happens to DBG files which ARE REALLY the
103              * right .DBG files but nonetheless this check fails. Anyway,
104              * WINDBG (debugger for Windows by Microsoft) loads debug symbols
105              * which have incorrect timestamps.
106              */
107         }
108         dbg = (PIMAGE_DEBUG_DIRECTORY) 
109             (dbg_mapping + sizeof(*hdr) + 
110              hdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
111              hdr->ExportedNamesSize);
112
113         sym_type = pe_load_debug_directory(pcs, module, dbg_mapping, dbg, 
114                                            hdr->DebugDirectorySize / sizeof(*dbg));
115     }
116     else
117     {
118         WINE_ERR("-Unable to peruse .DBG file %s (%s)\n", 
119                  dbg_name, debugstr_a(tmp));
120     }
121     if (dbg_mapping) UnmapViewOfFile((void*)dbg_mapping);
122     if (hMap) CloseHandle(hMap);
123     if (hFile != NULL) CloseHandle(hFile);
124     return sym_type;
125 }
126
127 /******************************************************************
128  *              pe_load_msc_debug_info
129  *
130  * Process MSC debug information in PE file.
131  */
132 static SYM_TYPE pe_load_msc_debug_info(const struct process* pcs, 
133                                        struct module* module,
134                                        const void* mapping, IMAGE_NT_HEADERS* nth)
135 {
136     SYM_TYPE               sym_type = -1;
137     PIMAGE_DATA_DIRECTORY  dir;
138     PIMAGE_DEBUG_DIRECTORY dbg = NULL;
139     int                    nDbg;
140
141     /* Read in debug directory */
142     dir = nth->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_DEBUG;
143     nDbg = dir->Size / sizeof(IMAGE_DEBUG_DIRECTORY);
144     if (!nDbg) return sym_type;
145
146     dbg = (PIMAGE_DEBUG_DIRECTORY)((char*)mapping + dir->VirtualAddress);
147
148     /* Parse debug directory */
149     if (nth->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED)
150     {
151         /* Debug info is stripped to .DBG file */
152         PIMAGE_DEBUG_MISC misc = (PIMAGE_DEBUG_MISC)
153             ((char*)mapping + dbg->PointerToRawData);
154
155         if (nDbg != 1 || dbg->Type != IMAGE_DEBUG_TYPE_MISC ||
156             misc->DataType != IMAGE_DEBUG_MISC_EXENAME)
157         {
158             WINE_ERR("-Debug info stripped, but no .DBG file in module %s\n",
159                      module->module.ModuleName);
160         }
161         else
162         {
163             sym_type = pe_load_dbg_file(pcs, module, misc->Data, nth->FileHeader.TimeDateStamp);
164         }
165     }
166     else
167     {
168         /* Debug info is embedded into PE module */
169         sym_type = pe_load_debug_directory(pcs, module, mapping, dbg, nDbg);
170     }
171
172     return sym_type;
173 }
174
175 /***********************************************************************
176  *                      pe_load_export_debug_info
177  */
178 static SYM_TYPE pe_load_export_debug_info(const struct process* pcs, 
179                                           struct module* module, 
180                                           const void* mapping, IMAGE_NT_HEADERS* nth)
181 {
182     char                        buffer[512];
183     unsigned int                i;
184     IMAGE_DATA_DIRECTORY*       dir;
185     DWORD                       base = module->module.BaseOfImage;
186     ADDRESS                     addr;
187
188     addr.Mode = AddrModeFlat;
189     addr.Segment = 0;
190
191 #if 0
192     /* Add start of DLL (better use the (yet unimplemented) Exe SymTag for this) */
193     /* FIXME: module.ModuleName isn't correctly set yet if it's passed in SymLoadModule */
194     symt_new_public(module, NULL, module->module.ModuleName, base, 0,
195                     TRUE /* FIXME */, TRUE /* FIXME */);
196 #endif
197     
198     /* Add entry point */
199     snprintf(buffer, sizeof(buffer), "%s.EntryPoint", module->module.ModuleName);
200     symt_new_public(module, NULL, buffer, 
201                     base + nth->OptionalHeader.AddressOfEntryPoint, 0,
202                     TRUE /* FIXME */, TRUE /* FIXME */);
203
204 #if 0
205     IMAGE_SECTION_HEADER*       section;
206     /* Add start of sections */
207     section = (IMAGE_SECTION_HEADER*)
208         ((char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
209     for (i = 0; i < nth->FileHeader.NumberOfSections; i++, section++) 
210     {
211         snprintf(buffer, sizeof(buffer), "%s.%s", 
212                  module->module.ModuleName, section->Name);
213         symt_new_public(module, NULL, buffer, base + section->VirtualAddress, 0,
214                         TRUE /* FIXME */, TRUE /* FIXME */);
215     }
216 #endif
217     
218     /* Add exported functions */
219     if ((dir = RtlImageDirectoryEntryToData((void*)mapping, TRUE, 
220                                             IMAGE_DIRECTORY_ENTRY_EXPORT, NULL)))
221     {
222         IMAGE_EXPORT_DIRECTORY* exports;
223         WORD*                   ordinals = NULL;
224         void**                  functions = NULL;
225         DWORD*                  names = NULL;
226         unsigned int            j;
227         
228         exports   = (void*)((char*)mapping + dir->VirtualAddress);
229         functions = (void*)((char*)mapping + exports->AddressOfFunctions);
230         ordinals  = (void*)((char*)mapping + exports->AddressOfNameOrdinals);
231         names     = (void*)((char*)mapping + exports->AddressOfNames);
232             
233         for (i = 0; i < exports->NumberOfNames; i++) 
234         {
235             if (!names[i]) continue;
236             snprintf(buffer, sizeof(buffer), "%s.%s", 
237                      module->module.ModuleName, (char*)base + names[i]);
238             symt_new_public(module, NULL, buffer, 
239                             base + (DWORD)functions[ordinals[i]], 0,
240                             TRUE /* FIXME */, TRUE /* FIXME */);
241         }
242             
243         for (i = 0; i < exports->NumberOfFunctions; i++) 
244         {
245             if (!functions[i]) continue;
246             /* Check if we already added it with a name */
247             for (j = 0; j < exports->NumberOfNames; j++)
248                 if ((ordinals[j] == i) && names[j]) break;
249             if (j < exports->NumberOfNames) continue;
250             snprintf(buffer, sizeof(buffer), "%s.%ld", 
251                      module->module.ModuleName, i + exports->Base);
252             symt_new_public(module, NULL, buffer,  base + (DWORD)functions[i], 0,
253                             TRUE /* FIXME */, TRUE /* FIXME */);
254         }
255     }
256     /* no real debug info, only entry points */
257     return module->module.SymType = SymExport;
258 }
259
260 /******************************************************************
261  *              pe_load_debug_info
262  *
263  */
264 SYM_TYPE pe_load_debug_info(const struct process* pcs, struct module* module)
265 {
266     SYM_TYPE            sym_type = -1;
267     HANDLE              hFile;
268     HANDLE              hMap;
269     void*               mapping;
270     IMAGE_NT_HEADERS*   nth;
271
272     hFile = CreateFileA(module->module.LoadedImageName, GENERIC_READ, FILE_SHARE_READ,
273                         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
274     if (hFile == INVALID_HANDLE_VALUE) return -1;
275     if ((hMap = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0)
276     {
277         if ((mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
278         {
279             nth = RtlImageNtHeader(mapping);
280
281             if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
282             {
283                 sym_type = pe_load_stabs(pcs, module, mapping, nth);
284                 if (sym_type <= SymNone)
285                     sym_type = pe_load_msc_debug_info(pcs, module, mapping, nth);
286                 /* if we still have no debug info (we could only get SymExport at this
287                  * point), then do the SymExport except if we have an ELF container, 
288                  * in which case we'll rely on the export's on the ELF side
289                  */
290             }
291             if (sym_type <= SymNone && !module_get_debug(pcs, module))
292                 sym_type = pe_load_export_debug_info(pcs, module, mapping, nth);
293             UnmapViewOfFile(mapping);
294         }
295         CloseHandle(hMap);
296     }
297     CloseHandle(hFile);
298
299     module->module.SymType = (sym_type >= SymNone) ? sym_type : SymNone;
300     return sym_type;
301 }
302
303 /******************************************************************
304  *              pe_load_module
305  *
306  */
307 struct module* pe_load_module(struct process* pcs, char* name,
308                               HANDLE hFile, DWORD base, DWORD size)
309 {
310     struct module*      module = NULL;
311     BOOL                opened = FALSE;
312     HANDLE              hMap;
313     void*               mapping;
314     char                loaded_name[MAX_PATH];
315
316     loaded_name[0] = '\0';
317     if (!hFile)
318     {
319         if (!name)
320         {
321             /* FIXME SetLastError */
322             return NULL;
323         }
324         if ((hFile = FindExecutableImage(name, NULL, loaded_name)) == NULL)
325             return NULL;
326         opened = TRUE;
327     }
328     else if (name) strcpy(loaded_name, name);
329     else if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
330         FIXME("Trouble ahead (no module name passed in deferred mode)\n");
331     if ((hMap = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0)
332     {
333         if ((mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
334         {
335             IMAGE_NT_HEADERS*   nth = RtlImageNtHeader(mapping);
336
337             if (nth)
338             {
339                 if (!base) base = nth->OptionalHeader.ImageBase;
340                 if (!size) size = nth->OptionalHeader.SizeOfImage;
341             
342                 module = module_new(pcs, loaded_name, DMT_PE, base, size,
343                                     nth->FileHeader.TimeDateStamp, 
344                                     nth->OptionalHeader.CheckSum);
345                 if (module)
346                 {
347                     module->module.SymType = (dbghelp_options & SYMOPT_DEFERRED_LOADS) ? 
348                         SymDeferred : pe_load_debug_info(pcs, module);
349                 }
350             }
351             UnmapViewOfFile(mapping);
352         }
353         CloseHandle(hMap);
354     }
355     if (opened) CloseHandle(hFile);
356
357     return module;
358 }
359
360 /******************************************************************
361  *              pe_load_module_from_pcs
362  *
363  */
364 struct module* pe_load_module_from_pcs(struct process* pcs, const char* name, 
365                                        const char* mod_name, DWORD base, DWORD size)
366 {
367     struct module*      module;
368     const char*         ptr;
369
370     if ((module = module_find_by_name(pcs, name, DMT_PE))) return module;
371     if (mod_name) ptr = mod_name;
372     else
373     {
374         for (ptr = name + strlen(name) - 1; ptr >= name; ptr--)
375         {
376             if (*ptr == '/' || *ptr == '\\')
377             {
378                 ptr++;
379                 break;
380             }
381         }
382     }
383     if (ptr && (module = module_find_by_name(pcs, ptr, DMT_PE))) return module;
384     if (base && pcs->dbg_hdr_addr)
385     {
386         IMAGE_DOS_HEADER    dos;
387         IMAGE_NT_HEADERS    nth;
388
389         if (read_mem(pcs->handle, base, &dos, sizeof(dos)) &&
390             dos.e_magic == IMAGE_DOS_SIGNATURE &&
391             read_mem(pcs->handle, base + dos.e_lfanew, &nth, sizeof(nth)) &&
392             nth.Signature == IMAGE_NT_SIGNATURE)
393         {
394             if (!size) size = nth.OptionalHeader.SizeOfImage;
395             module = module_new(pcs, name, DMT_PE, base, size,
396                                 nth.FileHeader.TimeDateStamp, nth.OptionalHeader.CheckSum);
397         }
398     }
399     return module;
400 }