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 "pipe/p_compiler.h"
36#include "os/os_thread.h"
37#include "util/u_string.h"
38
39#include "util/u_debug.h"
40#include "u_debug_symbol.h"
41#include "util/hash_table.h"
42
43
44#if defined(PIPE_OS_WINDOWS)
45
46#include <windows.h>
47#include <stddef.h>
48
49#include "dbghelp.h"
50
51
52/**
53 * SymInitialize() must be called once for each process (in this case, the
54 * current process), before any of the other functions can be called.
55 */
56static BOOL g_bSymInitialized = FALSE;
57
58
59/**
60 * Lookup the address of a DbgHelp function.
61 */
62static FARPROC WINAPI
63getDbgHelpProcAddress(LPCSTR lpProcName)
64{
65   static HMODULE hModule = NULL;
66
67   if (!hModule) {
68      static boolean bail = FALSE;
69
70      if (bail) {
71         return NULL;
72      }
73
74#ifdef PIPE_CC_GCC
75      /*
76       * DbgHelp does not understand the debug information generated by MinGW toolchain.
77       *
78       * mgwhelp.dll is a dbghelp.dll look-alike replacement, which is able to
79       * understand MinGW symbols, including on 64-bit builds.
80       */
81      if (!hModule) {
82         hModule = LoadLibraryA("mgwhelp.dll");
83         if (!hModule) {
84            _debug_printf("warning: mgwhelp.dll not found: symbol names will not be resolved\n"
85                          "warning: download it from https://github.com/jrfonseca/drmingw/#mgwhelp\n");
86         }
87      }
88#endif
89
90      /*
91       * Fallback to the real DbgHelp.
92       */
93      if (!hModule) {
94         hModule = LoadLibraryA("dbghelp.dll");
95      }
96
97      if (!hModule) {
98         bail = TRUE;
99         return NULL;
100      }
101   }
102
103   return GetProcAddress(hModule, lpProcName);
104}
105
106
107/**
108 * Generic macro to dispatch a DbgHelp functions.
109 */
110#define DBGHELP_DISPATCH(_name, _ret_type, _ret_default, _arg_types, _arg_names) \
111   static _ret_type WINAPI \
112   j_##_name _arg_types \
113   { \
114      typedef BOOL (WINAPI *PFN) _arg_types; \
115      static PFN pfn = NULL; \
116      if (!pfn) { \
117         pfn = (PFN) getDbgHelpProcAddress(#_name); \
118         if (!pfn) { \
119            return _ret_default; \
120         } \
121      } \
122      return pfn _arg_names; \
123   }
124
125DBGHELP_DISPATCH(SymInitialize,
126                 BOOL, 0,
127                 (HANDLE hProcess, PSTR UserSearchPath, BOOL fInvadeProcess),
128                 (hProcess, UserSearchPath, fInvadeProcess))
129
130DBGHELP_DISPATCH(SymSetOptions,
131                 DWORD, FALSE,
132                 (DWORD SymOptions),
133                 (SymOptions))
134
135DBGHELP_DISPATCH(SymFromAddr,
136                 BOOL, FALSE,
137                 (HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol),
138                 (hProcess, Address, Displacement, Symbol))
139
140DBGHELP_DISPATCH(SymGetLineFromAddr64,
141                 BOOL, FALSE,
142                 (HANDLE hProcess, DWORD64 dwAddr, PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line),
143                 (hProcess, dwAddr, pdwDisplacement, Line))
144
145DBGHELP_DISPATCH(SymCleanup, BOOL, FALSE, (HANDLE hProcess), (hProcess))
146
147
148#undef DBGHELP_DISPATCH
149
150
151static inline boolean
152debug_symbol_name_dbghelp(const void *addr, char* buf, unsigned size)
153{
154   DWORD64 dwAddr = (DWORD64)(uintptr_t)addr;
155   HANDLE hProcess = GetCurrentProcess();
156
157   /* General purpose buffer, to back pSymbol and other temporary stuff.
158    * Must not be too memory hungry here to avoid stack overflows.
159    */
160   CHAR buffer[512];
161
162   PSYMBOL_INFO pSymbol = (PSYMBOL_INFO) buffer;
163   DWORD64 dwDisplacement = 0;  /* Displacement of the input address, relative to the start of the symbol */
164   DWORD dwLineDisplacement = 0;
165   IMAGEHLP_LINE64 Line;
166
167   memset(pSymbol, 0, sizeof *pSymbol);
168   pSymbol->SizeOfStruct = sizeof *pSymbol;
169   pSymbol->MaxNameLen = sizeof buffer - offsetof(SYMBOL_INFO, Name);
170
171   if (!g_bSymInitialized) {
172      /* Some components (e.g. Java) will init dbghelp before we're loaded, causing the "invade process"
173       * option to be invalid when attempting to re-init. But without it, we'd have to manually
174       * load symbols for all modules in the stack. For simplicity, we can just uninit and then
175       * re-"invade".
176       */
177      if (debug_get_bool_option("GALLIUM_SYMBOL_FORCE_REINIT", false))
178         j_SymCleanup(hProcess);
179
180      j_SymSetOptions(/* SYMOPT_UNDNAME | */ SYMOPT_LOAD_LINES);
181      if (j_SymInitialize(hProcess, NULL, TRUE)) {
182         g_bSymInitialized = TRUE;
183      }
184   }
185
186   /* Lookup symbol name */
187   if (!g_bSymInitialized ||
188       !j_SymFromAddr(hProcess, dwAddr, &dwDisplacement, pSymbol)) {
189      /*
190       * We couldn't obtain symbol information.  At least tell which module the address belongs.
191       */
192
193      HMODULE hModule = NULL;
194
195      if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
196                             (LPCTSTR)addr,
197                             &hModule)) {
198         return FALSE;
199      }
200
201      if (GetModuleFileNameA(hModule, buffer, sizeof buffer) == sizeof buffer) {
202         return FALSE;
203      }
204      snprintf(buf, size, "%p at %s+0x%lx",
205               addr, buffer,
206               (unsigned long)((uintptr_t)addr - (uintptr_t)hModule));
207
208      return TRUE;
209   }
210
211   /*
212    * Try to get filename and line number.
213    */
214   memset(&Line, 0, sizeof Line);
215   Line.SizeOfStruct = sizeof Line;
216   if (!j_SymGetLineFromAddr64(hProcess, dwAddr, &dwLineDisplacement, &Line)) {
217      Line.FileName = NULL;
218   }
219
220   if (Line.FileName) {
221      snprintf(buf, size, "%s at %s:%lu", pSymbol->Name, Line.FileName, Line.LineNumber);
222   } else {
223      snprintf(buf, size, "%s", pSymbol->Name);
224   }
225
226   return TRUE;
227}
228
229#endif /* PIPE_OS_WINDOWS */
230
231void
232debug_symbol_name(const void *addr, char* buf, unsigned size)
233{
234#if defined(PIPE_OS_WINDOWS)
235   if (debug_symbol_name_dbghelp(addr, buf, size)) {
236      return;
237   }
238#endif
239
240   snprintf(buf, size, "%p", addr);
241   buf[size - 1] = 0;
242}
243
244void
245debug_symbol_print(const void *addr)
246{
247   char buf[1024];
248   debug_symbol_name(addr, buf, sizeof(buf));
249   debug_printf("\t%s\n", buf);
250}
251
252static struct hash_table* symbols_hash;
253#ifdef PIPE_OS_WINDOWS
254static mtx_t symbols_mutex;
255#else
256static mtx_t symbols_mutex = _MTX_INITIALIZER_NP;
257#endif
258
259const char*
260debug_symbol_name_cached(const void *addr)
261{
262   const char* name;
263#ifdef PIPE_OS_WINDOWS
264   static boolean first = TRUE;
265
266   if (first) {
267      (void) mtx_init(&symbols_mutex, mtx_plain);
268      first = FALSE;
269   }
270#endif
271
272   mtx_lock(&symbols_mutex);
273   if(!symbols_hash)
274      symbols_hash = _mesa_pointer_hash_table_create(NULL);
275   struct hash_entry *entry = _mesa_hash_table_search(symbols_hash, addr);
276   if (!entry) {
277      char buf[1024];
278      debug_symbol_name(addr, buf, sizeof(buf));
279      name = strdup(buf);
280
281      entry = _mesa_hash_table_insert(symbols_hash, addr, (void*)name);
282   }
283   mtx_unlock(&symbols_mutex);
284   return entry->data;
285}
286