server: A thread's affinity is restricted to the process affinity.
[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 "wine/port.h"
26
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <assert.h>
31
32 #include "dbghelp_private.h"
33 #include "winternl.h"
34 #include "wine/debug.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                           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, mapping, stabs, NULL),
73                           stabsize,
74                           RtlImageRvaToVa(nth, mapping, stabstr, NULL),
75                           stabstrsize,
76                           NULL, NULL);
77     }
78
79     TRACE("%s the STABS debug info\n", ret ? "successfully loaded" : "failed to load");
80     return ret;
81 }
82
83 /******************************************************************
84  *              pe_load_dbg_file
85  *
86  * loads a .dbg file
87  */
88 static BOOL pe_load_dbg_file(const struct process* pcs, struct module* module,
89                              const char* dbg_name, DWORD timestamp)
90 {
91     char                                tmp[MAX_PATH];
92     HANDLE                              hFile = INVALID_HANDLE_VALUE, hMap = 0;
93     const BYTE*                         dbg_mapping = NULL;
94     BOOL                                ret = FALSE;
95
96     TRACE("Processing DBG file %s\n", debugstr_a(dbg_name));
97
98     if (path_find_symbol_file(pcs, dbg_name, NULL, timestamp, 0, tmp, &module->module.DbgUnmatched) &&
99         (hFile = CreateFileA(tmp, GENERIC_READ, FILE_SHARE_READ, NULL,
100                              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE &&
101         ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0) &&
102         ((dbg_mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL))
103     {
104         const IMAGE_SEPARATE_DEBUG_HEADER*      hdr;
105         const IMAGE_SECTION_HEADER*             sectp;
106         const IMAGE_DEBUG_DIRECTORY*            dbg;
107
108         hdr = (const IMAGE_SEPARATE_DEBUG_HEADER*)dbg_mapping;
109         /* section headers come immediately after debug header */
110         sectp = (const IMAGE_SECTION_HEADER*)(hdr + 1);
111         /* and after that and the exported names comes the debug directory */
112         dbg = (const IMAGE_DEBUG_DIRECTORY*)
113             (dbg_mapping + sizeof(*hdr) +
114              hdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) +
115              hdr->ExportedNamesSize);
116
117         ret = pe_load_debug_directory(pcs, module, dbg_mapping, sectp,
118                                       hdr->NumberOfSections, dbg,
119                                       hdr->DebugDirectorySize / sizeof(*dbg));
120     }
121     else
122         ERR("Couldn't find .DBG file %s (%s)\n", debugstr_a(dbg_name), debugstr_a(tmp));
123
124     if (dbg_mapping) UnmapViewOfFile(dbg_mapping);
125     if (hMap) CloseHandle(hMap);
126     if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile);
127     return ret;
128 }
129
130 /******************************************************************
131  *              pe_load_msc_debug_info
132  *
133  * Process MSC debug information in PE file.
134  */
135 static BOOL pe_load_msc_debug_info(const struct process* pcs, 
136                                    struct module* module,
137                                    void* mapping, const IMAGE_NT_HEADERS* nth)
138 {
139     BOOL                        ret = FALSE;
140     const IMAGE_DATA_DIRECTORY* dir;
141     const IMAGE_DEBUG_DIRECTORY*dbg = NULL;
142     int                         nDbg;
143
144     /* Read in debug directory */
145     dir = nth->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_DEBUG;
146     nDbg = dir->Size / sizeof(IMAGE_DEBUG_DIRECTORY);
147     if (!nDbg) return FALSE;
148
149     dbg = RtlImageRvaToVa(nth, mapping, dir->VirtualAddress, NULL);
150
151     /* Parse debug directory */
152     if (nth->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED)
153     {
154         /* Debug info is stripped to .DBG file */
155         const IMAGE_DEBUG_MISC* misc = (const IMAGE_DEBUG_MISC*)
156             ((const char*)mapping + dbg->PointerToRawData);
157
158         if (nDbg != 1 || dbg->Type != IMAGE_DEBUG_TYPE_MISC ||
159             misc->DataType != IMAGE_DEBUG_MISC_EXENAME)
160         {
161             WINE_ERR("-Debug info stripped, but no .DBG file in module %s\n",
162                      debugstr_w(module->module.ModuleName));
163         }
164         else
165         {
166             ret = pe_load_dbg_file(pcs, module, (const char*)misc->Data, nth->FileHeader.TimeDateStamp);
167         }
168     }
169     else
170     {
171         const IMAGE_SECTION_HEADER *sectp = (const IMAGE_SECTION_HEADER*)((const char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
172         /* Debug info is embedded into PE module */
173         ret = pe_load_debug_directory(pcs, module, mapping, sectp,
174             nth->FileHeader.NumberOfSections, dbg, nDbg);
175     }
176
177     return ret;
178 }
179
180 /***********************************************************************
181  *                      pe_load_export_debug_info
182  */
183 static BOOL pe_load_export_debug_info(const struct process* pcs, 
184                                       struct module* module, 
185                                       void* mapping, const IMAGE_NT_HEADERS* nth)
186 {
187     unsigned int                        i;
188     const IMAGE_EXPORT_DIRECTORY*       exports;
189     DWORD                               base = module->module.BaseOfImage;
190     DWORD                               size;
191
192     if (dbghelp_options & SYMOPT_NO_PUBLICS) return TRUE;
193
194 #if 0
195     /* Add start of DLL (better use the (yet unimplemented) Exe SymTag for this) */
196     /* FIXME: module.ModuleName isn't correctly set yet if it's passed in SymLoadModule */
197     symt_new_public(module, NULL, module->module.ModuleName, base, 1,
198                     TRUE /* FIXME */, TRUE /* FIXME */);
199 #endif
200     
201     /* Add entry point */
202     symt_new_public(module, NULL, "EntryPoint", 
203                     base + nth->OptionalHeader.AddressOfEntryPoint, 1,
204                     TRUE, TRUE);
205 #if 0
206     /* FIXME: we'd better store addresses linked to sections rather than 
207        absolute values */
208     IMAGE_SECTION_HEADER*       section;
209     /* Add start of sections */
210     section = (IMAGE_SECTION_HEADER*)
211         ((char*)&nth->OptionalHeader + nth->FileHeader.SizeOfOptionalHeader);
212     for (i = 0; i < nth->FileHeader.NumberOfSections; i++, section++) 
213     {
214         symt_new_public(module, NULL, section->Name, 
215                         RtlImageRvaToVa(nth, mapping, section->VirtualAddress, NULL), 
216                         1, TRUE /* FIXME */, TRUE /* FIXME */);
217     }
218 #endif
219
220     /* Add exported functions */
221     if ((exports = RtlImageDirectoryEntryToData(mapping, FALSE,
222                                                 IMAGE_DIRECTORY_ENTRY_EXPORT, &size)))
223     {
224         const WORD*             ordinals = NULL;
225         const DWORD_PTR*        functions = NULL;
226         const DWORD*            names = NULL;
227         unsigned int            j;
228         char                    buffer[16];
229
230         functions = RtlImageRvaToVa(nth, mapping, exports->AddressOfFunctions, NULL);
231         ordinals  = RtlImageRvaToVa(nth, mapping, exports->AddressOfNameOrdinals, NULL);
232         names     = RtlImageRvaToVa(nth, mapping, exports->AddressOfNames, NULL);
233
234         if (functions && ordinals && names)
235         {
236             for (i = 0; i < exports->NumberOfNames; i++)
237             {
238                 if (!names[i]) continue;
239                 symt_new_public(module, NULL,
240                                 RtlImageRvaToVa(nth, mapping, names[i], NULL),
241                                 base + functions[ordinals[i]],
242                                 1, TRUE /* FIXME */, TRUE /* FIXME */);
243             }
244
245             for (i = 0; i < exports->NumberOfFunctions; i++)
246             {
247                 if (!functions[i]) continue;
248                 /* Check if we already added it with a name */
249                 for (j = 0; j < exports->NumberOfNames; j++)
250                     if ((ordinals[j] == i) && names[j]) break;
251                 if (j < exports->NumberOfNames) continue;
252                 snprintf(buffer, sizeof(buffer), "%d", i + exports->Base);
253                 symt_new_public(module, NULL, buffer, base + (DWORD)functions[i], 1,
254                                 TRUE /* FIXME */, TRUE /* FIXME */);
255             }
256         }
257     }
258     /* no real debug info, only entry points */
259     if (module->module.SymType == SymDeferred)
260         module->module.SymType = SymExport;
261     return TRUE;
262 }
263
264 /******************************************************************
265  *              pe_load_debug_info
266  *
267  */
268 BOOL pe_load_debug_info(const struct process* pcs, struct module* module)
269 {
270     BOOL                ret = FALSE;
271     HANDLE              hFile;
272     HANDLE              hMap;
273     void*               mapping;
274     IMAGE_NT_HEADERS*   nth;
275
276     hFile = CreateFileW(module->module.LoadedImageName, GENERIC_READ, FILE_SHARE_READ,
277                         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
278     if (hFile == INVALID_HANDLE_VALUE) return ret;
279     if ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != 0)
280     {
281         if ((mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
282         {
283             nth = RtlImageNtHeader(mapping);
284
285             if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
286             {
287                 ret = pe_load_stabs(pcs, module, mapping, nth) ||
288                     pe_load_msc_debug_info(pcs, module, mapping, nth);
289                 /* if we still have no debug info (we could only get SymExport at this
290                  * point), then do the SymExport except if we have an ELF container, 
291                  * in which case we'll rely on the export's on the ELF side
292                  */
293             }
294 /* FIXME shouldn't we check that? if (!module_get_debug(pcs, module))l */
295             if (pe_load_export_debug_info(pcs, module, mapping, nth) && !ret)
296                 ret = TRUE;
297             UnmapViewOfFile(mapping);
298         }
299         CloseHandle(hMap);
300     }
301     CloseHandle(hFile);
302
303     return ret;
304 }
305
306 /******************************************************************
307  *              pe_load_native_module
308  *
309  */
310 struct module* pe_load_native_module(struct process* pcs, const WCHAR* name,
311                                      HANDLE hFile, DWORD base, DWORD size)
312 {
313     struct module*      module = NULL;
314     BOOL                opened = FALSE;
315     HANDLE              hMap;
316     WCHAR               loaded_name[MAX_PATH];
317
318     loaded_name[0] = '\0';
319     if (!hFile)
320     {
321
322         assert(name);
323
324         if ((hFile = FindExecutableImageExW(name, pcs->search_path, loaded_name, NULL, NULL)) == NULL)
325             return NULL;
326         opened = TRUE;
327     }
328     else if (name) strcpyW(loaded_name, name);
329     else if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
330         FIXME("Trouble ahead (no module name passed in deferred mode)\n");
331
332     if ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) != NULL)
333     {
334         void*   mapping;
335
336         if ((mapping = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) != NULL)
337         {
338             IMAGE_NT_HEADERS*   nth = RtlImageNtHeader(mapping);
339
340             if (nth)
341             {
342                 if (!base) base = nth->OptionalHeader.ImageBase;
343                 if (!size) size = nth->OptionalHeader.SizeOfImage;
344
345                 module = module_new(pcs, loaded_name, DMT_PE, FALSE, base, size,
346                                     nth->FileHeader.TimeDateStamp,
347                                     nth->OptionalHeader.CheckSum);
348                 if (module)
349                 {
350                     if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
351                         module->module.SymType = SymDeferred;
352                     else
353                         pe_load_debug_info(pcs, module);
354                 }
355                 else
356                     ERR("could not load the module '%s'\n", debugstr_w(loaded_name));
357             }
358             UnmapViewOfFile(mapping);
359         }
360         CloseHandle(hMap);
361     }
362     if (opened) CloseHandle(hFile);
363
364     return module;
365 }
366
367 /******************************************************************
368  *              pe_load_nt_header
369  *
370  */
371 BOOL pe_load_nt_header(HANDLE hProc, DWORD base, IMAGE_NT_HEADERS* nth)
372 {
373     IMAGE_DOS_HEADER    dos;
374
375     return ReadProcessMemory(hProc, (char*)base, &dos, sizeof(dos), NULL) &&
376         dos.e_magic == IMAGE_DOS_SIGNATURE &&
377         ReadProcessMemory(hProc, (char*)(base + dos.e_lfanew), 
378                           nth, sizeof(*nth), NULL) &&
379         nth->Signature == IMAGE_NT_SIGNATURE;
380 }
381
382 /******************************************************************
383  *              pe_load_builtin_module
384  *
385  */
386 struct module* pe_load_builtin_module(struct process* pcs, const WCHAR* name,
387                                       DWORD base, DWORD size)
388 {
389     struct module*      module = NULL;
390
391     if (base && pcs->dbg_hdr_addr)
392     {
393         IMAGE_NT_HEADERS    nth;
394
395         if (pe_load_nt_header(pcs->handle, base, &nth))
396         {
397             if (!size) size = nth.OptionalHeader.SizeOfImage;
398             module = module_new(pcs, name, DMT_PE, FALSE, base, size,
399                                 nth.FileHeader.TimeDateStamp,
400                                 nth.OptionalHeader.CheckSum);
401         }
402     }
403     return module;
404 }
405
406 /***********************************************************************
407  *           ImageDirectoryEntryToDataEx (DBGHELP.@)
408  *
409  * Search for specified directory in PE image
410  *
411  * PARAMS
412  *
413  *   base    [in]  Image base address
414  *   image   [in]  TRUE - image has been loaded by loader, FALSE - raw file image
415  *   dir     [in]  Target directory index
416  *   size    [out] Receives directory size
417  *   section [out] Receives pointer to section header of section containing directory data
418  *
419  * RETURNS
420  *   Success: pointer to directory data
421  *   Failure: NULL
422  *
423  */
424 PVOID WINAPI ImageDirectoryEntryToDataEx( PVOID base, BOOLEAN image, USHORT dir, PULONG size, PIMAGE_SECTION_HEADER *section )
425 {
426     const IMAGE_NT_HEADERS *nt;
427     DWORD addr;
428
429     *size = 0;
430     if (section) *section = NULL;
431
432     if (!(nt = RtlImageNtHeader( base ))) return NULL;
433     if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
434     if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
435
436     *size = nt->OptionalHeader.DataDirectory[dir].Size;
437     if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)base + addr;
438
439     return RtlImageRvaToVa( nt, base, addr, section );
440 }
441
442 /***********************************************************************
443  *         ImageDirectoryEntryToData   (DBGHELP.@)
444  *
445  * NOTES
446  *   See ImageDirectoryEntryToDataEx
447  */
448 PVOID WINAPI ImageDirectoryEntryToData( PVOID base, BOOLEAN image, USHORT dir, PULONG size )
449 {
450     return ImageDirectoryEntryToDataEx( base, image, dir, size, NULL );
451 }