1 /**************************************************************************
2  *
3  * Copyright 2009 VMware, Inc.
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sub license, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial portions
16  * of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21  * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
22  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25  *
26  **************************************************************************/
27 
28 /**
29  * @file
30  * Symbol lookup.
31  *
32  * @author Jose Fonseca <jfonseca@vmware.com>
33  */
34 
35 #include "util/compiler.h"
36 #include "util/u_thread.h"
37 #include "util/simple_mtx.h"
38 #include "util/u_string.h"
39 
40 #include "util/u_debug.h"
41 #include "u_debug_symbol.h"
42 #include "util/hash_table.h"
43 
44 
45 #if DETECT_OS_WINDOWS
46 
47 #include <windows.h>
48 #include <stddef.h>
49 
50 #include "dbghelp.h"
51 
52 
53 /**
54  * SymInitialize() must be called once for each process (in this case, the
55  * current process), before any of the other functions can be called.
56  */
57 static BOOL g_bSymInitialized = false;
58 
59 
60 /**
61  * Lookup the address of a DbgHelp function.
62  */
63 static FARPROC WINAPI
getDbgHelpProcAddress(LPCSTR lpProcName)64 getDbgHelpProcAddress(LPCSTR lpProcName)
65 {
66    static HMODULE hModule = NULL;
67 
68    if (!hModule) {
69       static bool bail = false;
70 
71       if (bail) {
72          return NULL;
73       }
74 
75 #if DETECT_CC_GCC
76       /*
77        * DbgHelp does not understand the debug information generated by MinGW toolchain.
78        *
79        * mgwhelp.dll is a dbghelp.dll look-alike replacement, which is able to
80        * understand MinGW symbols, including on 64-bit builds.
81        */
82       if (!hModule) {
83          hModule = LoadLibraryA("mgwhelp.dll");
84          if (!hModule) {
85             _debug_printf("warning: mgwhelp.dll not found: symbol names will not be resolved\n"
86                           "warning: download it from https://github.com/jrfonseca/drmingw/#mgwhelp\n");
87          }
88       }
89 #endif
90 
91       /*
92        * Fallback to the real DbgHelp.
93        */
94       if (!hModule) {
95          hModule = LoadLibraryA("dbghelp.dll");
96       }
97 
98       if (!hModule) {
99          bail = true;
100          return NULL;
101       }
102    }
103 
104    return GetProcAddress(hModule, lpProcName);
105 }
106 
107 
108 /**
109  * Generic macro to dispatch a DbgHelp functions.
110  */
111 #define DBGHELP_DISPATCH(_name, _ret_type, _ret_default, _arg_types, _arg_names) \
112    static _ret_type WINAPI \
113    j_##_name _arg_types \
114    { \
115       typedef BOOL (WINAPI *PFN) _arg_types; \
116       static PFN pfn = NULL; \
117       if (!pfn) { \
118          pfn = (PFN) getDbgHelpProcAddress(#_name); \
119          if (!pfn) { \
120             return _ret_default; \
121          } \
122       } \
123       return pfn _arg_names; \
124    }
125 
126 DBGHELP_DISPATCH(SymInitialize,
127                  BOOL, 0,
128                  (HANDLE hProcess, PSTR UserSearchPath, BOOL fInvadeProcess),
129                  (hProcess, UserSearchPath, fInvadeProcess))
130 
131 DBGHELP_DISPATCH(SymSetOptions,
132                  DWORD, false,
133                  (DWORD SymOptions),
134                  (SymOptions))
135 
136 #ifndef _GAMING_XBOX
137 DBGHELP_DISPATCH(SymFromAddr,
138                  BOOL, false,
139                  (HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol),
140                  (hProcess, Address, Displacement, Symbol))
141 #endif
142 
143 DBGHELP_DISPATCH(SymGetLineFromAddr64,
144                  BOOL, false,
145                  (HANDLE hProcess, DWORD64 dwAddr, PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line),
146                  (hProcess, dwAddr, pdwDisplacement, Line))
147 
148 DBGHELP_DISPATCH(SymCleanup, BOOL, false, (HANDLE hProcess), (hProcess))
149 
150 
151 #undef DBGHELP_DISPATCH
152 
153 
154 static inline bool
debug_symbol_name_dbghelp(const void * addr,char * buf,unsigned size)155 debug_symbol_name_dbghelp(const void *addr, char* buf, unsigned size)
156 {
157 #ifndef _GAMING_XBOX
158    DWORD64 dwAddr = (DWORD64)(uintptr_t)addr;
159    HANDLE hProcess = GetCurrentProcess();
160 
161    /* General purpose buffer, to back pSymbol and other temporary stuff.
162     * Must not be too memory hungry here to avoid stack overflows.
163     */
164    CHAR buffer[512];
165 
166    PSYMBOL_INFO pSymbol = (PSYMBOL_INFO) buffer;
167    DWORD64 dwDisplacement = 0;  /* Displacement of the input address, relative to the start of the symbol */
168    DWORD dwLineDisplacement = 0;
169    IMAGEHLP_LINE64 Line;
170 
171    memset(pSymbol, 0, sizeof *pSymbol);
172    pSymbol->SizeOfStruct = sizeof *pSymbol;
173    pSymbol->MaxNameLen = sizeof buffer - offsetof(SYMBOL_INFO, Name);
174 
175    if (!g_bSymInitialized) {
176       /* Some components (e.g. Java) will init dbghelp before we're loaded, causing the "invade process"
177        * option to be invalid when attempting to re-init. But without it, we'd have to manually
178        * load symbols for all modules in the stack. For simplicity, we can just uninit and then
179        * re-"invade".
180        */
181       if (debug_get_bool_option("GALLIUM_SYMBOL_FORCE_REINIT", false))
182          j_SymCleanup(hProcess);
183 
184       j_SymSetOptions(/* SYMOPT_UNDNAME | */ SYMOPT_LOAD_LINES);
185       if (j_SymInitialize(hProcess, NULL, true)) {
186          g_bSymInitialized = true;
187       }
188    }
189 
190    /* Lookup symbol name */
191    if (!g_bSymInitialized ||
192        !j_SymFromAddr(hProcess, dwAddr, &dwDisplacement, pSymbol)) {
193       /*
194        * We couldn't obtain symbol information.  At least tell which module the address belongs.
195        */
196 
197       HMODULE hModule = NULL;
198 
199       if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
200                              (LPCTSTR)addr,
201                              &hModule)) {
202          return false;
203       }
204 
205       if (GetModuleFileNameA(hModule, buffer, sizeof buffer) == sizeof buffer) {
206          return false;
207       }
208       snprintf(buf, size, "%p at %s+0x%lx",
209                addr, buffer,
210                (unsigned long)((uintptr_t)addr - (uintptr_t)hModule));
211 
212       return true;
213    }
214 
215    /*
216     * Try to get filename and line number.
217     */
218    memset(&Line, 0, sizeof Line);
219    Line.SizeOfStruct = sizeof Line;
220    if (!j_SymGetLineFromAddr64(hProcess, dwAddr, &dwLineDisplacement, &Line)) {
221       Line.FileName = NULL;
222    }
223 
224    if (Line.FileName) {
225       snprintf(buf, size, "%s at %s:%lu", pSymbol->Name, Line.FileName, Line.LineNumber);
226    } else {
227       snprintf(buf, size, "%s", pSymbol->Name);
228    }
229 
230    return true;
231 #else
232    return false;
233 #endif /* _GAMING_XBOX */
234 }
235 
236 #endif /* DETECT_OS_WINDOWS */
237 
238 void
debug_symbol_name(const void * addr,char * buf,unsigned size)239 debug_symbol_name(const void *addr, char* buf, unsigned size)
240 {
241 #if DETECT_OS_WINDOWS
242    if (debug_symbol_name_dbghelp(addr, buf, size)) {
243       return;
244    }
245 #endif
246 
247    snprintf(buf, size, "%p", addr);
248    buf[size - 1] = 0;
249 }
250 
251 void
debug_symbol_print(const void * addr)252 debug_symbol_print(const void *addr)
253 {
254    char buf[1024];
255    debug_symbol_name(addr, buf, sizeof(buf));
256    debug_printf("\t%s\n", buf);
257 }
258 
259 static struct hash_table* symbols_hash;
260 static simple_mtx_t symbols_mutex = SIMPLE_MTX_INITIALIZER;
261 
262 const char*
debug_symbol_name_cached(const void * addr)263 debug_symbol_name_cached(const void *addr)
264 {
265    const char* name;
266    simple_mtx_lock(&symbols_mutex);
267    if(!symbols_hash)
268       symbols_hash = _mesa_pointer_hash_table_create(NULL);
269    struct hash_entry *entry = _mesa_hash_table_search(symbols_hash, addr);
270    if (!entry) {
271       char buf[1024];
272       debug_symbol_name(addr, buf, sizeof(buf));
273       name = strdup(buf);
274 
275       entry = _mesa_hash_table_insert(symbols_hash, addr, (void*)name);
276    }
277    simple_mtx_unlock(&symbols_mutex);
278    return entry->data;
279 }
280