Developer Documentation
StackWalker.cc
1 /**********************************************************************
2  *
3  * StackWalker.cpp
4  * http://stackwalker.codeplex.com/
5  *
6  *
7  * History:
8  * 2005-07-27 v1 - First public release on http://www.codeproject.com/
9  * http://www.codeproject.com/threads/StackWalker.asp
10  * 2005-07-28 v2 - Changed the params of the constructor and ShowCallstack
11  * (to simplify the usage)
12  * 2005-08-01 v3 - Changed to use 'CONTEXT_FULL' instead of CONTEXT_ALL
13  * (should also be enough)
14  * - Changed to compile correctly with the PSDK of VC7.0
15  * (GetFileVersionInfoSizeA and GetFileVersionInfoA is wrongly defined:
16  * it uses LPSTR instead of LPCSTR as first paremeter)
17  * - Added declarations to support VC5/6 without using 'dbghelp.h'
18  * - Added a 'pUserData' member to the ShowCallstack function and the
19  * PReadProcessMemoryRoutine declaration (to pass some user-defined data,
20  * which can be used in the readMemoryFunction-callback)
21  * 2005-08-02 v4 - OnSymInit now also outputs the OS-Version by default
22  * - Added example for doing an exception-callstack-walking in main.cpp
23  * (thanks to owillebo: http://www.codeproject.com/script/profile/whos_who.asp?id=536268)
24  * 2005-08-05 v5 - Removed most Lint (http://www.gimpel.com/) errors... thanks to Okko Willeboordse!
25  * 2008-08-04 v6 - Fixed Bug: Missing LEAK-end-tag
26  * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=2502890#xx2502890xx
27  * Fixed Bug: Compiled with "WIN32_LEAN_AND_MEAN"
28  * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=1824718#xx1824718xx
29  * Fixed Bug: Compiling with "/Wall"
30  * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=2638243#xx2638243xx
31  * Fixed Bug: Now checking SymUseSymSrv
32  * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=1388979#xx1388979xx
33  * Fixed Bug: Support for recursive function calls
34  * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=1434538#xx1434538xx
35  * Fixed Bug: Missing FreeLibrary call in "GetModuleListTH32"
36  * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=1326923#xx1326923xx
37  * Fixed Bug: SymDia is number 7, not 9!
38  * 2008-09-11 v7 For some (undocumented) reason, dbhelp.h is needing a packing of 8!
39  * Thanks to Teajay which reported the bug...
40  * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=2718933#xx2718933xx
41  * 2008-11-27 v8 Debugging Tools for Windows are now stored in a different directory
42  * Thanks to Luiz Salamon which reported this "bug"...
43  * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=2822736#xx2822736xx
44  * 2009-04-10 v9 License slihtly corrected (<ORGANIZATION> replaced)
45  * 2009-11-01 v10 Moved to http://stackwalker.codeplex.com/
46  * 2009-11-02 v11 Now try to use IMAGEHLP_MODULE64_V3 if available
47  * 2010-04-15 v12 Added support for VS2010 RTM
48  * 2010-05-25 v13 Now using secure MyStrcCpy. Thanks to luke.simon:
49  * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=3477467#xx3477467xx
50  * 2013-01-07 v14 Runtime Check Error VS2010 Debug Builds fixed:
51  * http://stackwalker.codeplex.com/workitem/10511
52  *
53  *
54  * LICENSE (http://www.opensource.org/licenses/bsd-license.php)
55  *
56  * Copyright (c) 2005-2013, Jochen Kalmbach
57  * All rights reserved.
58  *
59  * Redistribution and use in source and binary forms, with or without modification,
60  * are permitted provided that the following conditions are met:
61  *
62  * Redistributions of source code must retain the above copyright notice,
63  * this list of conditions and the following disclaimer.
64  * Redistributions in binary form must reproduce the above copyright notice,
65  * this list of conditions and the following disclaimer in the documentation
66  * and/or other materials provided with the distribution.
67  * Neither the name of Jochen Kalmbach nor the names of its contributors may be
68  * used to endorse or promote products derived from this software without
69  * specific prior written permission.
70  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
71  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
72  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
73  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
74  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
75  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
76  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
77  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
78  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
79  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
80  *
81  **********************************************************************/
82 #include <windows.h>
83 #include <tchar.h>
84 #include <stdio.h>
85 #include <stdlib.h>
86 #pragma comment(lib, "version.lib") // for "VerQueryValue"
87 #pragma warning(disable:4826)
88 
89 #include "StackWalker.hh"
90 
91 
92 // If VC7 and later, then use the shipped 'dbghelp.h'-file
93 #pragma pack(push,8)
94 #if _MSC_VER >= 1300
95 #include <dbghelp.h>
96 #else
97 // inline the important dbghelp.h-declarations...
98 typedef enum {
99  SymNone = 0,
100  SymCoff,
101  SymCv,
102  SymPdb,
103  SymExport,
104  SymDeferred,
105  SymSym,
106  SymDia,
107  SymVirtual,
108  NumSymTypes
109 } SYM_TYPE;
110 typedef struct _IMAGEHLP_LINE64 {
111  DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_LINE64)
112  PVOID Key; // internal
113  DWORD LineNumber; // line number in file
114  PCHAR FileName; // full filename
115  DWORD64 Address; // first instruction of line
117 typedef struct _IMAGEHLP_MODULE64 {
118  DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64)
119  DWORD64 BaseOfImage; // base load address of module
120  DWORD ImageSize; // virtual size of the loaded module
121  DWORD TimeDateStamp; // date/time stamp from pe header
122  DWORD CheckSum; // checksum from the pe header
123  DWORD NumSyms; // number of symbols in the symbol table
124  SYM_TYPE SymType; // type of symbols loaded
125  CHAR ModuleName[32]; // module name
126  CHAR ImageName[256]; // image name
127  CHAR LoadedImageName[256]; // symbol file name
129 typedef struct _IMAGEHLP_SYMBOL64 {
130  DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_SYMBOL64)
131  DWORD64 Address; // virtual address including dll base address
132  DWORD Size; // estimated size of symbol, can be zero
133  DWORD Flags; // info about the symbols, see the SYMF defines
134  DWORD MaxNameLength; // maximum size of symbol name in 'Name'
135  CHAR Name[1]; // symbol name (null terminated string)
137 typedef enum {
138  AddrMode1616,
139  AddrMode1632,
140  AddrModeReal,
141  AddrModeFlat
142 } ADDRESS_MODE;
143 typedef struct _tagADDRESS64 {
144  DWORD64 Offset;
145  WORD Segment;
146  ADDRESS_MODE Mode;
148 typedef struct _KDHELP64 {
149  DWORD64 Thread;
150  DWORD ThCallbackStack;
151  DWORD ThCallbackBStore;
152  DWORD NextCallback;
153  DWORD FramePointer;
154  DWORD64 KiCallUserMode;
155  DWORD64 KeUserCallbackDispatcher;
156  DWORD64 SystemRangeStart;
157  DWORD64 Reserved[8];
158 } KDHELP64, *PKDHELP64;
159 typedef struct _tagSTACKFRAME64 {
160  ADDRESS64 AddrPC; // program counter
161  ADDRESS64 AddrReturn; // return address
162  ADDRESS64 AddrFrame; // frame pointer
163  ADDRESS64 AddrStack; // stack pointer
164  ADDRESS64 AddrBStore; // backing store pointer
165  PVOID FuncTableEntry; // pointer to pdata/fpo or NULL
166  DWORD64 Params[4]; // possible arguments to the function
167  BOOL Far; // WOW far call
168  BOOL Virtual; // is this a virtual frame?
169  DWORD64 Reserved[3];
170  KDHELP64 KdHelp;
172 typedef
173 BOOL
174 (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(
175  HANDLE hProcess,
176  DWORD64 qwBaseAddress,
177  PVOID lpBuffer,
178  DWORD nSize,
179  LPDWORD lpNumberOfBytesRead
180  );
181 typedef
182 PVOID
183 (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)(
184  HANDLE hProcess,
185  DWORD64 AddrBase
186  );
187 typedef
188 DWORD64
189 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(
190  HANDLE hProcess,
191  DWORD64 Address
192  );
193 typedef
194 DWORD64
195 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(
196  HANDLE hProcess,
197  HANDLE hThread,
198  LPADDRESS64 lpaddr
199  );
200 #define SYMOPT_CASE_INSENSITIVE 0x00000001
201 #define SYMOPT_UNDNAME 0x00000002
202 #define SYMOPT_DEFERRED_LOADS 0x00000004
203 #define SYMOPT_NO_CPP 0x00000008
204 #define SYMOPT_LOAD_LINES 0x00000010
205 #define SYMOPT_OMAP_FIND_NEAREST 0x00000020
206 #define SYMOPT_LOAD_ANYTHING 0x00000040
207 #define SYMOPT_IGNORE_CVREC 0x00000080
208 #define SYMOPT_NO_UNQUALIFIED_LOADS 0x00000100
209 #define SYMOPT_FAIL_CRITICAL_ERRORS 0x00000200
210 #define SYMOPT_EXACT_SYMBOLS 0x00000400
211 #define SYMOPT_ALLOW_ABSOLUTE_SYMBOLS 0x00000800
212 #define SYMOPT_IGNORE_NT_SYMPATH 0x00001000
213 #define SYMOPT_INCLUDE_32BIT_MODULES 0x00002000
214 #define SYMOPT_PUBLICS_ONLY 0x00004000
215 #define SYMOPT_NO_PUBLICS 0x00008000
216 #define SYMOPT_AUTO_PUBLICS 0x00010000
217 #define SYMOPT_NO_IMAGE_SEARCH 0x00020000
218 #define SYMOPT_SECURE 0x00040000
219 #define SYMOPT_DEBUG 0x80000000
220 #define UNDNAME_COMPLETE (0x0000) // Enable full undecoration
221 #define UNDNAME_NAME_ONLY (0x1000) // Crack only the name for primary declaration;
222 #endif // _MSC_VER < 1300
223 #pragma pack(pop)
224 
225 // Some missing defines (for VC5/6):
226 #ifndef INVALID_FILE_ATTRIBUTES
227 #define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
228 #endif
229 
230 
231 // secure-CRT_functions are only available starting with VC8
232 #if _MSC_VER < 1400
233 #define strcpy_s(dst, len, src) strcpy(dst, src)
234 #define strncpy_s(dst, len, src, maxLen) strncpy(dst, len, src)
235 #define strcat_s(dst, len, src) strcat(dst, src)
236 #define _snprintf_s _snprintf
237 #define _tcscat_s _tcscat
238 #endif
239 
240 static void MyStrCpy(char* szDest, size_t nMaxDestSize, const char* szSrc)
241 {
242  if (strlen(szSrc) < nMaxDestSize)
243  {
244  strcpy_s(szDest, nMaxDestSize, szSrc);
245  }
246  else
247  {
248  strncpy_s(szDest, nMaxDestSize, szSrc, nMaxDestSize);
249  szDest[nMaxDestSize-1] = 0;
250  }
251 } // MyStrCpy
252 
253 // Normally it should be enough to use 'CONTEXT_FULL' (better would be 'CONTEXT_ALL')
254 #define USED_CONTEXT_FLAGS CONTEXT_FULL
255 
256 
258 {
259 public:
260  StackWalkerInternal(StackWalker *parent, HANDLE hProcess)
261  {
262  m_parent = parent;
263  m_hDbhHelp = NULL;
264  pSC = NULL;
265  m_hProcess = hProcess;
266  m_szSymPath = NULL;
267  pSFTA = NULL;
268  pSGLFA = NULL;
269  pSGMB = NULL;
270  pSGMI = NULL;
271  pSGO = NULL;
272  pSGSFA = NULL;
273  pSI = NULL;
274  pSLM = NULL;
275  pSSO = NULL;
276  pSW = NULL;
277  pUDSN = NULL;
278  pSGSP = NULL;
279  }
281  {
282  if (pSC != NULL)
283  pSC(m_hProcess); // SymCleanup
284  if (m_hDbhHelp != NULL)
285  FreeLibrary(m_hDbhHelp);
286  m_hDbhHelp = NULL;
287  m_parent = NULL;
288  if(m_szSymPath != NULL)
289  free(m_szSymPath);
290  m_szSymPath = NULL;
291  }
292  BOOL Init(LPCSTR szSymPath)
293  {
294  if (m_parent == NULL)
295  return FALSE;
296  // Dynamically load the Entry-Points for dbghelp.dll:
297  // First try to load the newsest one from
298  TCHAR szTemp[4096];
299  // But before wqe do this, we first check if the ".local" file exists
300  if (GetModuleFileName(NULL, szTemp, 4096) > 0)
301  {
302  _tcscat_s(szTemp, _T(".local"));
303  if (GetFileAttributes(szTemp) == INVALID_FILE_ATTRIBUTES)
304  {
305  // ".local" file does not exist, so we can try to load the dbghelp.dll from the "Debugging Tools for Windows"
306  // Ok, first try the new path according to the archtitecture:
307 #ifdef _M_IX86
308  if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
309  {
310  _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (x86)\\dbghelp.dll"));
311  // now check if the file exists:
312  if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
313  {
314  m_hDbhHelp = LoadLibrary(szTemp);
315  }
316  }
317 #elif _M_X64
318  if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
319  {
320  _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (x64)\\dbghelp.dll"));
321  // now check if the file exists:
322  if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
323  {
324  m_hDbhHelp = LoadLibrary(szTemp);
325  }
326  }
327 #elif _M_IA64
328  if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
329  {
330  _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (ia64)\\dbghelp.dll"));
331  // now check if the file exists:
332  if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
333  {
334  m_hDbhHelp = LoadLibrary(szTemp);
335  }
336  }
337 #endif
338  // If still not found, try the old directories...
339  if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
340  {
341  _tcscat_s(szTemp, _T("\\Debugging Tools for Windows\\dbghelp.dll"));
342  // now check if the file exists:
343  if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
344  {
345  m_hDbhHelp = LoadLibrary(szTemp);
346  }
347  }
348 #if defined _M_X64 || defined _M_IA64
349  // Still not found? Then try to load the (old) 64-Bit version:
350  if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
351  {
352  _tcscat_s(szTemp, _T("\\Debugging Tools for Windows 64-Bit\\dbghelp.dll"));
353  if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
354  {
355  m_hDbhHelp = LoadLibrary(szTemp);
356  }
357  }
358 #endif
359  }
360  }
361  if (m_hDbhHelp == NULL) // if not already loaded, try to load a default-one
362  m_hDbhHelp = LoadLibrary( _T("dbghelp.dll") );
363  if (m_hDbhHelp == NULL)
364  return FALSE;
365  pSI = (tSI) GetProcAddress(m_hDbhHelp, "SymInitialize" );
366  pSC = (tSC) GetProcAddress(m_hDbhHelp, "SymCleanup" );
367 
368  pSW = (tSW) GetProcAddress(m_hDbhHelp, "StackWalk64" );
369  pSGO = (tSGO) GetProcAddress(m_hDbhHelp, "SymGetOptions" );
370  pSSO = (tSSO) GetProcAddress(m_hDbhHelp, "SymSetOptions" );
371 
372  pSFTA = (tSFTA) GetProcAddress(m_hDbhHelp, "SymFunctionTableAccess64" );
373  pSGLFA = (tSGLFA) GetProcAddress(m_hDbhHelp, "SymGetLineFromAddr64" );
374  pSGMB = (tSGMB) GetProcAddress(m_hDbhHelp, "SymGetModuleBase64" );
375  pSGMI = (tSGMI) GetProcAddress(m_hDbhHelp, "SymGetModuleInfo64" );
376  pSGSFA = (tSGSFA) GetProcAddress(m_hDbhHelp, "SymGetSymFromAddr64" );
377  pUDSN = (tUDSN) GetProcAddress(m_hDbhHelp, "UnDecorateSymbolName" );
378  pSLM = (tSLM) GetProcAddress(m_hDbhHelp, "SymLoadModule64" );
379  pSGSP =(tSGSP) GetProcAddress(m_hDbhHelp, "SymGetSearchPath" );
380 
381  if ( pSC == NULL || pSFTA == NULL || pSGMB == NULL || pSGMI == NULL ||
382  pSGO == NULL || pSGSFA == NULL || pSI == NULL || pSSO == NULL ||
383  pSW == NULL || pUDSN == NULL || pSLM == NULL )
384  {
385  FreeLibrary(m_hDbhHelp);
386  m_hDbhHelp = NULL;
387  pSC = NULL;
388  return FALSE;
389  }
390 
391  // SymInitialize
392  if (szSymPath != NULL)
393  m_szSymPath = _strdup(szSymPath);
394  if (this->pSI(m_hProcess, m_szSymPath, FALSE) == FALSE)
395  this->m_parent->OnDbgHelpErr("SymInitialize", GetLastError(), 0);
396 
397  DWORD symOptions = this->pSGO(); // SymGetOptions
398  symOptions |= SYMOPT_LOAD_LINES;
399  symOptions |= SYMOPT_FAIL_CRITICAL_ERRORS;
400  //symOptions |= SYMOPT_NO_PROMPTS;
401  // SymSetOptions
402  symOptions = this->pSSO(symOptions);
403 
404  char buf[StackWalker::STACKWALK_MAX_NAMELEN] = {0};
405  if (this->pSGSP != NULL)
406  {
407  if (this->pSGSP(m_hProcess, buf, StackWalker::STACKWALK_MAX_NAMELEN) == FALSE)
408  this->m_parent->OnDbgHelpErr("SymGetSearchPath", GetLastError(), 0);
409  }
410  char szUserName[1024] = {0};
411  DWORD dwSize = 1024;
412  GetUserNameA(szUserName, &dwSize);
413  this->m_parent->OnSymInit(buf, symOptions, szUserName);
414 
415  return TRUE;
416  }
417 
418  StackWalker *m_parent;
419 
420  HMODULE m_hDbhHelp;
421  HANDLE m_hProcess;
422  LPSTR m_szSymPath;
423 
424 #pragma pack(push,8)
425 typedef struct IMAGEHLP_MODULE64_V3 {
426  DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64)
427  DWORD64 BaseOfImage; // base load address of module
428  DWORD ImageSize; // virtual size of the loaded module
429  DWORD TimeDateStamp; // date/time stamp from pe header
430  DWORD CheckSum; // checksum from the pe header
431  DWORD NumSyms; // number of symbols in the symbol table
432  SYM_TYPE SymType; // type of symbols loaded
433  CHAR ModuleName[32]; // module name
434  CHAR ImageName[256]; // image name
435  CHAR LoadedImageName[256]; // symbol file name
436  // new elements: 07-Jun-2002
437  CHAR LoadedPdbName[256]; // pdb file name
438  DWORD CVSig; // Signature of the CV record in the debug directories
439  CHAR CVData[MAX_PATH * 3]; // Contents of the CV record
440  DWORD PdbSig; // Signature of PDB
441  GUID PdbSig70; // Signature of PDB (VC 7 and up)
442  DWORD PdbAge; // DBI age of pdb
443  BOOL PdbUnmatched; // loaded an unmatched pdb
444  BOOL DbgUnmatched; // loaded an unmatched dbg
445  BOOL LineNumbers; // we have line number information
446  BOOL GlobalSymbols; // we have internal symbol information
447  BOOL TypeInfo; // we have type information
448  // new elements: 17-Dec-2003
449  BOOL SourceIndexed; // pdb supports source server
450  BOOL Publics; // contains public symbols
451 };
452 
453 typedef struct IMAGEHLP_MODULE64_V2 {
454  DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64)
455  DWORD64 BaseOfImage; // base load address of module
456  DWORD ImageSize; // virtual size of the loaded module
457  DWORD TimeDateStamp; // date/time stamp from pe header
458  DWORD CheckSum; // checksum from the pe header
459  DWORD NumSyms; // number of symbols in the symbol table
460  SYM_TYPE SymType; // type of symbols loaded
461  CHAR ModuleName[32]; // module name
462  CHAR ImageName[256]; // image name
463  CHAR LoadedImageName[256]; // symbol file name
464 };
465 #pragma pack(pop)
466 
467 
468  // SymCleanup()
469  typedef BOOL (__stdcall *tSC)( IN HANDLE hProcess );
470  tSC pSC;
471 
472  // SymFunctionTableAccess64()
473  typedef PVOID (__stdcall *tSFTA)( HANDLE hProcess, DWORD64 AddrBase );
474  tSFTA pSFTA;
475 
476  // SymGetLineFromAddr64()
477  typedef BOOL (__stdcall *tSGLFA)( IN HANDLE hProcess, IN DWORD64 dwAddr,
478  OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Line );
479  tSGLFA pSGLFA;
480 
481  // SymGetModuleBase64()
482  typedef DWORD64 (__stdcall *tSGMB)( IN HANDLE hProcess, IN DWORD64 dwAddr );
483  tSGMB pSGMB;
484 
485  // SymGetModuleInfo64()
486  typedef BOOL (__stdcall *tSGMI)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT IMAGEHLP_MODULE64_V3 *ModuleInfo );
487  tSGMI pSGMI;
488 
489  // SymGetOptions()
490  typedef DWORD (__stdcall *tSGO)( VOID );
491  tSGO pSGO;
492 
493  // SymGetSymFromAddr64()
494  typedef BOOL (__stdcall *tSGSFA)( IN HANDLE hProcess, IN DWORD64 dwAddr,
495  OUT PDWORD64 pdwDisplacement, OUT PIMAGEHLP_SYMBOL64 Symbol );
496  tSGSFA pSGSFA;
497 
498  // SymInitialize()
499  typedef BOOL (__stdcall *tSI)( IN HANDLE hProcess, IN PSTR UserSearchPath, IN BOOL fInvadeProcess );
500  tSI pSI;
501 
502  // SymLoadModule64()
503  typedef DWORD64 (__stdcall *tSLM)( IN HANDLE hProcess, IN HANDLE hFile,
504  IN PSTR ImageName, IN PSTR ModuleName, IN DWORD64 BaseOfDll, IN DWORD SizeOfDll );
505  tSLM pSLM;
506 
507  // SymSetOptions()
508  typedef DWORD (__stdcall *tSSO)( IN DWORD SymOptions );
509  tSSO pSSO;
510 
511  // StackWalk64()
512  typedef BOOL (__stdcall *tSW)(
513  DWORD MachineType,
514  HANDLE hProcess,
515  HANDLE hThread,
516  LPSTACKFRAME64 StackFrame,
517  PVOID ContextRecord,
518  PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
519  PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
520  PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
521  PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress );
522  tSW pSW;
523 
524  // UnDecorateSymbolName()
525  typedef DWORD (__stdcall WINAPI *tUDSN)( PCSTR DecoratedName, PSTR UnDecoratedName,
526  DWORD UndecoratedLength, DWORD Flags );
527  tUDSN pUDSN;
528 
529  typedef BOOL (__stdcall WINAPI *tSGSP)(HANDLE hProcess, PSTR SearchPath, DWORD SearchPathLength);
530  tSGSP pSGSP;
531 
532 
533 private:
534  // **************************************** ToolHelp32 ************************
535  #define MAX_MODULE_NAME32 255
536  #define TH32CS_SNAPMODULE 0x00000008
537  #pragma pack( push, 8 )
538  typedef struct tagMODULEENTRY32
539  {
540  DWORD dwSize;
541  DWORD th32ModuleID; // This module
542  DWORD th32ProcessID; // owning process
543  DWORD GlblcntUsage; // Global usage count on the module
544  DWORD ProccntUsage; // Module usage count in th32ProcessID's context
545  BYTE * modBaseAddr; // Base address of module in th32ProcessID's context
546  DWORD modBaseSize; // Size in bytes of module starting at modBaseAddr
547  HMODULE hModule; // The hModule of this module in th32ProcessID's context
548  char szModule[MAX_MODULE_NAME32 + 1];
549  char szExePath[MAX_PATH];
550  } MODULEENTRY32;
551  typedef MODULEENTRY32 * PMODULEENTRY32;
552  typedef MODULEENTRY32 * LPMODULEENTRY32;
553  #pragma pack( pop )
554 
555  BOOL GetModuleListTH32(HANDLE hProcess, DWORD pid)
556  {
557  // CreateToolhelp32Snapshot()
558  typedef HANDLE (__stdcall *tCT32S)(DWORD dwFlags, DWORD th32ProcessID);
559  // Module32First()
560  typedef BOOL (__stdcall *tM32F)(HANDLE hSnapshot, LPMODULEENTRY32 lpme);
561  // Module32Next()
562  typedef BOOL (__stdcall *tM32N)(HANDLE hSnapshot, LPMODULEENTRY32 lpme);
563 
564  // try both dlls...
565  const TCHAR *dllname[] = { _T("kernel32.dll"), _T("tlhelp32.dll") };
566  HINSTANCE hToolhelp = NULL;
567  tCT32S pCT32S = NULL;
568  tM32F pM32F = NULL;
569  tM32N pM32N = NULL;
570 
571  HANDLE hSnap;
572  MODULEENTRY32 me;
573  me.dwSize = sizeof(me);
574  BOOL keepGoing;
575  size_t i;
576 
577  for (i = 0; i<(sizeof(dllname) / sizeof(dllname[0])); i++ )
578  {
579  hToolhelp = LoadLibrary( dllname[i] );
580  if (hToolhelp == NULL)
581  continue;
582  pCT32S = (tCT32S) GetProcAddress(hToolhelp, "CreateToolhelp32Snapshot");
583  pM32F = (tM32F) GetProcAddress(hToolhelp, "Module32First");
584  pM32N = (tM32N) GetProcAddress(hToolhelp, "Module32Next");
585  if ( (pCT32S != NULL) && (pM32F != NULL) && (pM32N != NULL) )
586  break; // found the functions!
587  FreeLibrary(hToolhelp);
588  hToolhelp = NULL;
589  }
590 
591  if (hToolhelp == NULL)
592  return FALSE;
593 
594  hSnap = pCT32S( TH32CS_SNAPMODULE, pid );
595  if (hSnap == (HANDLE) -1)
596  {
597  FreeLibrary(hToolhelp);
598  return FALSE;
599  }
600 
601  keepGoing = !!pM32F( hSnap, &me );
602  int cnt = 0;
603  while (keepGoing)
604  {
605  this->LoadModule(hProcess, me.szExePath, me.szModule, (DWORD64) me.modBaseAddr, me.modBaseSize);
606  cnt++;
607  keepGoing = !!pM32N( hSnap, &me );
608  }
609  CloseHandle(hSnap);
610  FreeLibrary(hToolhelp);
611  if (cnt <= 0)
612  return FALSE;
613  return TRUE;
614  } // GetModuleListTH32
615 
616  // **************************************** PSAPI ************************
617  typedef struct _MODULEINFO {
618  LPVOID lpBaseOfDll;
619  DWORD SizeOfImage;
620  LPVOID EntryPoint;
622 
623  BOOL GetModuleListPSAPI(HANDLE hProcess)
624  {
625  // EnumProcessModules()
626  typedef BOOL (__stdcall *tEPM)(HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded );
627  // GetModuleFileNameEx()
628  typedef DWORD (__stdcall *tGMFNE)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
629  // GetModuleBaseName()
630  typedef DWORD (__stdcall *tGMBN)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
631  // GetModuleInformation()
632  typedef BOOL (__stdcall *tGMI)(HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize );
633 
634  HINSTANCE hPsapi;
635  tEPM pEPM;
636  tGMFNE pGMFNE;
637  tGMBN pGMBN;
638  tGMI pGMI;
639 
640  DWORD i;
641  //ModuleEntry e;
642  DWORD cbNeeded;
643  MODULEINFO mi;
644  HMODULE *hMods = 0;
645  char *tt = NULL;
646  char *tt2 = NULL;
647  const SIZE_T TTBUFLEN = 8096;
648  int cnt = 0;
649 
650  hPsapi = LoadLibrary( _T("psapi.dll") );
651  if (hPsapi == NULL)
652  return FALSE;
653 
654  pEPM = (tEPM) GetProcAddress( hPsapi, "EnumProcessModules" );
655  pGMFNE = (tGMFNE) GetProcAddress( hPsapi, "GetModuleFileNameExA" );
656  pGMBN = (tGMFNE) GetProcAddress( hPsapi, "GetModuleBaseNameA" );
657  pGMI = (tGMI) GetProcAddress( hPsapi, "GetModuleInformation" );
658  if ( (pEPM == NULL) || (pGMFNE == NULL) || (pGMBN == NULL) || (pGMI == NULL) )
659  {
660  // we couldn't find all functions
661  FreeLibrary(hPsapi);
662  return FALSE;
663  }
664 
665  hMods = (HMODULE*) malloc(sizeof(HMODULE) * (TTBUFLEN / sizeof HMODULE));
666  tt = (char*) malloc(sizeof(char) * TTBUFLEN);
667  tt2 = (char*) malloc(sizeof(char) * TTBUFLEN);
668  if ( (hMods == NULL) || (tt == NULL) || (tt2 == NULL) )
669  goto cleanup;
670 
671  if ( ! pEPM( hProcess, hMods, TTBUFLEN, &cbNeeded ) )
672  {
673  //_ftprintf(fLogFile, _T("%lu: EPM failed, GetLastError = %lu\n"), g_dwShowCount, gle );
674  goto cleanup;
675  }
676 
677  if ( cbNeeded > TTBUFLEN )
678  {
679  //_ftprintf(fLogFile, _T("%lu: More than %lu module handles. Huh?\n"), g_dwShowCount, lenof( hMods ) );
680  goto cleanup;
681  }
682 
683  for ( i = 0; i < cbNeeded / sizeof hMods[0]; i++ )
684  {
685  // base address, size
686  pGMI(hProcess, hMods[i], &mi, sizeof mi );
687  // image file name
688  tt[0] = 0;
689  pGMFNE(hProcess, hMods[i], tt, TTBUFLEN );
690  // module name
691  tt2[0] = 0;
692  pGMBN(hProcess, hMods[i], tt2, TTBUFLEN );
693 
694  DWORD dwRes = this->LoadModule(hProcess, tt, tt2, (DWORD64) mi.lpBaseOfDll, mi.SizeOfImage);
695  if (dwRes != ERROR_SUCCESS)
696  this->m_parent->OnDbgHelpErr("LoadModule", dwRes, 0);
697  cnt++;
698  }
699 
700  cleanup:
701  if (hPsapi != NULL) FreeLibrary(hPsapi);
702  if (tt2 != NULL) free(tt2);
703  if (tt != NULL) free(tt);
704  if (hMods != NULL) free(hMods);
705 
706  return cnt != 0;
707  } // GetModuleListPSAPI
708 
709  DWORD LoadModule(HANDLE hProcess, LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size)
710  {
711  CHAR *szImg = _strdup(img);
712  CHAR *szMod = _strdup(mod);
713  DWORD result = ERROR_SUCCESS;
714  if ( (szImg == NULL) || (szMod == NULL) )
715  result = ERROR_NOT_ENOUGH_MEMORY;
716  else
717  {
718  if (pSLM(hProcess, 0, szImg, szMod, baseAddr, size) == 0)
719  result = GetLastError();
720  }
721  ULONGLONG fileVersion = 0;
722  if ( (m_parent != NULL) && (szImg != NULL) )
723  {
724  // try to retrive the file-version:
725  if ( (this->m_parent->m_options & StackWalker::RetrieveFileVersion) != 0)
726  {
727  VS_FIXEDFILEINFO *fInfo = NULL;
728  DWORD dwHandle;
729  DWORD dwSize = GetFileVersionInfoSizeA(szImg, &dwHandle);
730  if (dwSize > 0)
731  {
732  LPVOID vData = malloc(dwSize);
733  if (vData != NULL)
734  {
735  if (GetFileVersionInfoA(szImg, dwHandle, dwSize, vData) != 0)
736  {
737  UINT len;
738  TCHAR szSubBlock[] = _T("\\");
739  if (VerQueryValue(vData, szSubBlock, (LPVOID*) &fInfo, &len) == 0)
740  fInfo = NULL;
741  else
742  {
743  fileVersion = ((ULONGLONG)fInfo->dwFileVersionLS) + ((ULONGLONG)fInfo->dwFileVersionMS << 32);
744  }
745  }
746  free(vData);
747  }
748  }
749  }
750 
751  // Retrive some additional-infos about the module
752  IMAGEHLP_MODULE64_V3 Module;
753  const char *szSymType = "-unknown-";
754  if (this->GetModuleInfo(hProcess, baseAddr, &Module) != FALSE)
755  {
756  switch(Module.SymType)
757  {
758  case SymNone:
759  szSymType = "-nosymbols-";
760  break;
761  case SymCoff: // 1
762  szSymType = "COFF";
763  break;
764  case SymCv: // 2
765  szSymType = "CV";
766  break;
767  case SymPdb: // 3
768  szSymType = "PDB";
769  break;
770  case SymExport: // 4
771  szSymType = "-exported-";
772  break;
773  case SymDeferred: // 5
774  szSymType = "-deferred-";
775  break;
776  case SymSym: // 6
777  szSymType = "SYM";
778  break;
779  case 7: // SymDia:
780  szSymType = "DIA";
781  break;
782  case 8: //SymVirtual:
783  szSymType = "Virtual";
784  break;
785  }
786  }
787  LPCSTR pdbName = Module.LoadedImageName;
788  if (Module.LoadedPdbName[0] != 0)
789  pdbName = Module.LoadedPdbName;
790  this->m_parent->OnLoadModule(img, mod, baseAddr, size, result, szSymType, pdbName, fileVersion);
791  }
792  if (szImg != NULL) free(szImg);
793  if (szMod != NULL) free(szMod);
794  return result;
795  }
796 public:
797  BOOL LoadModules(HANDLE hProcess, DWORD dwProcessId)
798  {
799  // first try toolhelp32
800  if (GetModuleListTH32(hProcess, dwProcessId))
801  return true;
802  // then try psapi
803  return GetModuleListPSAPI(hProcess);
804  }
805 
806 
807  BOOL GetModuleInfo(HANDLE hProcess, DWORD64 baseAddr, IMAGEHLP_MODULE64_V3 *pModuleInfo)
808  {
809  memset(pModuleInfo, 0, sizeof(IMAGEHLP_MODULE64_V3));
810  if(this->pSGMI == NULL)
811  {
812  SetLastError(ERROR_DLL_INIT_FAILED);
813  return FALSE;
814  }
815  // First try to use the larger ModuleInfo-Structure
816  pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V3);
817  void *pData = malloc(4096); // reserve enough memory, so the bug in v6.3.5.1 does not lead to memory-overwrites...
818  if (pData == NULL)
819  {
820  SetLastError(ERROR_NOT_ENOUGH_MEMORY);
821  return FALSE;
822  }
823  memcpy(pData, pModuleInfo, sizeof(IMAGEHLP_MODULE64_V3));
824  static bool s_useV3Version = true;
825  if (s_useV3Version)
826  {
827  if (this->pSGMI(hProcess, baseAddr, reinterpret_cast<IMAGEHLP_MODULE64_V3*>(pData) ) != FALSE)
828  {
829  // only copy as much memory as is reserved...
830  memcpy(pModuleInfo, pData, sizeof(IMAGEHLP_MODULE64_V3));
831  pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V3);
832  free(pData);
833  return TRUE;
834  }
835  s_useV3Version = false; // to prevent unneccessarry calls with the larger struct...
836  }
837 
838  // could not retrive the bigger structure, try with the smaller one (as defined in VC7.1)...
839  pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2);
840  memcpy(pData, pModuleInfo, sizeof(IMAGEHLP_MODULE64_V2));
841  if (this->pSGMI(hProcess, baseAddr, reinterpret_cast<IMAGEHLP_MODULE64_V3*>(pData) ) != FALSE)
842  {
843  // only copy as much memory as is reserved...
844  memcpy(pModuleInfo, pData, sizeof(IMAGEHLP_MODULE64_V2));
845  pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2);
846  free(pData);
847  return TRUE;
848  }
849  free(pData);
850  SetLastError(ERROR_DLL_INIT_FAILED);
851  return FALSE;
852  }
853 };
854 
855 // #############################################################
856 StackWalker::StackWalker(DWORD dwProcessId, HANDLE hProcess)
857 {
858  this->m_options = OptionsAll;
859  this->m_modulesLoaded = FALSE;
860  this->m_hProcess = hProcess;
861  this->m_sw = new StackWalkerInternal(this, this->m_hProcess);
862  this->m_dwProcessId = dwProcessId;
863  this->m_szSymPath = NULL;
864  this->m_MaxRecursionCount = 1000;
865 }
866 StackWalker::StackWalker(int options, LPCSTR szSymPath, DWORD dwProcessId, HANDLE hProcess)
867 {
868  this->m_options = options;
869  this->m_modulesLoaded = FALSE;
870  this->m_hProcess = hProcess;
871  this->m_sw = new StackWalkerInternal(this, this->m_hProcess);
872  this->m_dwProcessId = dwProcessId;
873  if (szSymPath != NULL)
874  {
875  this->m_szSymPath = _strdup(szSymPath);
876  this->m_options |= SymBuildPath;
877  }
878  else
879  this->m_szSymPath = NULL;
880  this->m_MaxRecursionCount = 1000;
881 }
882 
883 StackWalker::~StackWalker()
884 {
885  if (m_szSymPath != NULL)
886  free(m_szSymPath);
887  m_szSymPath = NULL;
888  if (this->m_sw != NULL)
889  delete this->m_sw;
890  this->m_sw = NULL;
891 }
892 
893 BOOL StackWalker::LoadModules()
894 {
895  if (this->m_sw == NULL)
896  {
897  SetLastError(ERROR_DLL_INIT_FAILED);
898  return FALSE;
899  }
900  if (m_modulesLoaded != FALSE)
901  return TRUE;
902 
903  // Build the sym-path:
904  char *szSymPath = NULL;
905  if ( (this->m_options & SymBuildPath) != 0)
906  {
907  const size_t nSymPathLen = 4096;
908  szSymPath = (char*) malloc(nSymPathLen);
909  if (szSymPath == NULL)
910  {
911  SetLastError(ERROR_NOT_ENOUGH_MEMORY);
912  return FALSE;
913  }
914  szSymPath[0] = 0;
915  // Now first add the (optional) provided sympath:
916  if (this->m_szSymPath != NULL)
917  {
918  strcat_s(szSymPath, nSymPathLen, this->m_szSymPath);
919  strcat_s(szSymPath, nSymPathLen, ";");
920  }
921 
922  strcat_s(szSymPath, nSymPathLen, ".;");
923 
924  const size_t nTempLen = 1024;
925  char szTemp[nTempLen];
926  // Now add the current directory:
927  if (GetCurrentDirectoryA(nTempLen, szTemp) > 0)
928  {
929  szTemp[nTempLen-1] = 0;
930  strcat_s(szSymPath, nSymPathLen, szTemp);
931  strcat_s(szSymPath, nSymPathLen, ";");
932  }
933 
934  // Now add the path for the main-module:
935  if (GetModuleFileNameA(NULL, szTemp, nTempLen) > 0)
936  {
937  szTemp[nTempLen-1] = 0;
938  for (char *p = (szTemp+strlen(szTemp)-1); p >= szTemp; --p)
939  {
940  // locate the rightmost path separator
941  if ( (*p == '\\') || (*p == '/') || (*p == ':') )
942  {
943  *p = 0;
944  break;
945  }
946  } // for (search for path separator...)
947  if (strlen(szTemp) > 0)
948  {
949  strcat_s(szSymPath, nSymPathLen, szTemp);
950  strcat_s(szSymPath, nSymPathLen, ";");
951  }
952  }
953  if (GetEnvironmentVariableA("_NT_SYMBOL_PATH", szTemp, nTempLen) > 0)
954  {
955  szTemp[nTempLen-1] = 0;
956  strcat_s(szSymPath, nSymPathLen, szTemp);
957  strcat_s(szSymPath, nSymPathLen, ";");
958  }
959  if (GetEnvironmentVariableA("_NT_ALTERNATE_SYMBOL_PATH", szTemp, nTempLen) > 0)
960  {
961  szTemp[nTempLen-1] = 0;
962  strcat_s(szSymPath, nSymPathLen, szTemp);
963  strcat_s(szSymPath, nSymPathLen, ";");
964  }
965  if (GetEnvironmentVariableA("SYSTEMROOT", szTemp, nTempLen) > 0)
966  {
967  szTemp[nTempLen-1] = 0;
968  strcat_s(szSymPath, nSymPathLen, szTemp);
969  strcat_s(szSymPath, nSymPathLen, ";");
970  // also add the "system32"-directory:
971  strcat_s(szTemp, nTempLen, "\\system32");
972  strcat_s(szSymPath, nSymPathLen, szTemp);
973  strcat_s(szSymPath, nSymPathLen, ";");
974  }
975 
976  if ( (this->m_options & SymUseSymSrv) != 0)
977  {
978  if (GetEnvironmentVariableA("SYSTEMDRIVE", szTemp, nTempLen) > 0)
979  {
980  szTemp[nTempLen-1] = 0;
981  strcat_s(szSymPath, nSymPathLen, "SRV*");
982  strcat_s(szSymPath, nSymPathLen, szTemp);
983  strcat_s(szSymPath, nSymPathLen, "\\websymbols");
984  strcat_s(szSymPath, nSymPathLen, "*http://msdl.microsoft.com/download/symbols;");
985  }
986  else
987  strcat_s(szSymPath, nSymPathLen, "SRV*c:\\websymbols*http://msdl.microsoft.com/download/symbols;");
988  }
989  } // if SymBuildPath
990 
991  // First Init the whole stuff...
992  BOOL bRet = this->m_sw->Init(szSymPath);
993  if (szSymPath != NULL) free(szSymPath); szSymPath = NULL;
994  if (bRet == FALSE)
995  {
996  this->OnDbgHelpErr("Error while initializing dbghelp.dll", 0, 0);
997  SetLastError(ERROR_DLL_INIT_FAILED);
998  return FALSE;
999  }
1000 
1001  bRet = this->m_sw->LoadModules(this->m_hProcess, this->m_dwProcessId);
1002  if (bRet != FALSE)
1003  m_modulesLoaded = TRUE;
1004  return bRet;
1005 }
1006 
1007 
1008 // The following is used to pass the "userData"-Pointer to the user-provided readMemoryFunction
1009 // This has to be done due to a problem with the "hProcess"-parameter in x64...
1010 // Because this class is in no case multi-threading-enabled (because of the limitations
1011 // of dbghelp.dll) it is "safe" to use a static-variable
1012 static StackWalker::PReadProcessMemoryRoutine s_readMemoryFunction = NULL;
1013 static LPVOID s_readMemoryFunction_UserData = NULL;
1014 
1015 BOOL StackWalker::ShowCallstack(HANDLE hThread, const CONTEXT *context, PReadProcessMemoryRoutine readMemoryFunction, LPVOID pUserData)
1016 {
1017  CONTEXT c;
1018  CallstackEntry csEntry;
1019  IMAGEHLP_SYMBOL64 *pSym = NULL;
1021  IMAGEHLP_LINE64 Line;
1022  int frameNum;
1023  bool bLastEntryCalled = true;
1024  int curRecursionCount = 0;
1025 
1026  if (m_modulesLoaded == FALSE)
1027  this->LoadModules(); // ignore the result...
1028 
1029  if (this->m_sw->m_hDbhHelp == NULL)
1030  {
1031  SetLastError(ERROR_DLL_INIT_FAILED);
1032  return FALSE;
1033  }
1034 
1035  s_readMemoryFunction = readMemoryFunction;
1036  s_readMemoryFunction_UserData = pUserData;
1037 
1038  if (context == NULL)
1039  {
1040  // If no context is provided, capture the context
1041  if (hThread == GetCurrentThread())
1042  {
1043  GET_CURRENT_CONTEXT(c, USED_CONTEXT_FLAGS);
1044  }
1045  else
1046  {
1047  SuspendThread(hThread);
1048  memset(&c, 0, sizeof(CONTEXT));
1049  c.ContextFlags = USED_CONTEXT_FLAGS;
1050  if (GetThreadContext(hThread, &c) == FALSE)
1051  {
1052  ResumeThread(hThread);
1053  return FALSE;
1054  }
1055  }
1056  }
1057  else
1058  c = *context;
1059 
1060  // init STACKFRAME for first call
1061  STACKFRAME64 s; // in/out stackframe
1062  memset(&s, 0, sizeof(s));
1063  DWORD imageType;
1064 #ifdef _M_IX86
1065  // normally, call ImageNtHeader() and use machine info from PE header
1066  imageType = IMAGE_FILE_MACHINE_I386;
1067  s.AddrPC.Offset = c.Eip;
1068  s.AddrPC.Mode = AddrModeFlat;
1069  s.AddrFrame.Offset = c.Ebp;
1070  s.AddrFrame.Mode = AddrModeFlat;
1071  s.AddrStack.Offset = c.Esp;
1072  s.AddrStack.Mode = AddrModeFlat;
1073 #elif _M_X64
1074  imageType = IMAGE_FILE_MACHINE_AMD64;
1075  s.AddrPC.Offset = c.Rip;
1076  s.AddrPC.Mode = AddrModeFlat;
1077  s.AddrFrame.Offset = c.Rsp;
1078  s.AddrFrame.Mode = AddrModeFlat;
1079  s.AddrStack.Offset = c.Rsp;
1080  s.AddrStack.Mode = AddrModeFlat;
1081 #elif _M_IA64
1082  imageType = IMAGE_FILE_MACHINE_IA64;
1083  s.AddrPC.Offset = c.StIIP;
1084  s.AddrPC.Mode = AddrModeFlat;
1085  s.AddrFrame.Offset = c.IntSp;
1086  s.AddrFrame.Mode = AddrModeFlat;
1087  s.AddrBStore.Offset = c.RsBSP;
1088  s.AddrBStore.Mode = AddrModeFlat;
1089  s.AddrStack.Offset = c.IntSp;
1090  s.AddrStack.Mode = AddrModeFlat;
1091 #else
1092 #error "Platform not supported!"
1093 #endif
1094 
1095  pSym = (IMAGEHLP_SYMBOL64 *) malloc(sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN);
1096  if (!pSym) goto cleanup; // not enough memory...
1097  memset(pSym, 0, sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN);
1098  pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
1099  pSym->MaxNameLength = STACKWALK_MAX_NAMELEN;
1100 
1101  memset(&Line, 0, sizeof(Line));
1102  Line.SizeOfStruct = sizeof(Line);
1103 
1104  memset(&Module, 0, sizeof(Module));
1105  Module.SizeOfStruct = sizeof(Module);
1106 
1107  for (frameNum = 0; ; ++frameNum )
1108  {
1109  // get next stack frame (StackWalk64(), SymFunctionTableAccess64(), SymGetModuleBase64())
1110  // if this returns ERROR_INVALID_ADDRESS (487) or ERROR_NOACCESS (998), you can
1111  // assume that either you are done, or that the stack is so hosed that the next
1112  // deeper frame could not be found.
1113  // CONTEXT need not to be suplied if imageTyp is IMAGE_FILE_MACHINE_I386!
1114  if ( ! this->m_sw->pSW(imageType, this->m_hProcess, hThread, &s, &c, myReadProcMem, this->m_sw->pSFTA, this->m_sw->pSGMB, NULL) )
1115  {
1116  // INFO: "StackWalk64" does not set "GetLastError"...
1117  this->OnDbgHelpErr("StackWalk64", 0, s.AddrPC.Offset);
1118  break;
1119  }
1120 
1121  csEntry.offset = s.AddrPC.Offset;
1122  csEntry.name[0] = 0;
1123  csEntry.undName[0] = 0;
1124  csEntry.undFullName[0] = 0;
1125  csEntry.offsetFromSmybol = 0;
1126  csEntry.offsetFromLine = 0;
1127  csEntry.lineFileName[0] = 0;
1128  csEntry.lineNumber = 0;
1129  csEntry.loadedImageName[0] = 0;
1130  csEntry.moduleName[0] = 0;
1131  if (s.AddrPC.Offset == s.AddrReturn.Offset)
1132  {
1133  if ( (this->m_MaxRecursionCount > 0) && (curRecursionCount > m_MaxRecursionCount) )
1134  {
1135  this->OnDbgHelpErr("StackWalk64-Endless-Callstack!", 0, s.AddrPC.Offset);
1136  break;
1137  }
1138  curRecursionCount++;
1139  }
1140  else
1141  curRecursionCount = 0;
1142  if (s.AddrPC.Offset != 0)
1143  {
1144  // we seem to have a valid PC
1145  // show procedure info (SymGetSymFromAddr64())
1146  if (this->m_sw->pSGSFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromSmybol), pSym) != FALSE)
1147  {
1148  MyStrCpy(csEntry.name, STACKWALK_MAX_NAMELEN, pSym->Name);
1149  // UnDecorateSymbolName()
1150  this->m_sw->pUDSN( pSym->Name, csEntry.undName, STACKWALK_MAX_NAMELEN, UNDNAME_NAME_ONLY );
1151  this->m_sw->pUDSN( pSym->Name, csEntry.undFullName, STACKWALK_MAX_NAMELEN, UNDNAME_COMPLETE );
1152  }
1153  else
1154  {
1155  this->OnDbgHelpErr("SymGetSymFromAddr64", GetLastError(), s.AddrPC.Offset);
1156  }
1157 
1158  // show line number info, NT5.0-method (SymGetLineFromAddr64())
1159  if (this->m_sw->pSGLFA != NULL )
1160  { // yes, we have SymGetLineFromAddr64()
1161  if (this->m_sw->pSGLFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromLine), &Line) != FALSE)
1162  {
1163  csEntry.lineNumber = Line.LineNumber;
1164  MyStrCpy(csEntry.lineFileName, STACKWALK_MAX_NAMELEN, Line.FileName);
1165  }
1166  else
1167  {
1168  this->OnDbgHelpErr("SymGetLineFromAddr64", GetLastError(), s.AddrPC.Offset);
1169  }
1170  } // yes, we have SymGetLineFromAddr64()
1171 
1172  // show module info (SymGetModuleInfo64())
1173  if (this->m_sw->GetModuleInfo(this->m_hProcess, s.AddrPC.Offset, &Module ) != FALSE)
1174  { // got module info OK
1175  switch ( Module.SymType )
1176  {
1177  case SymNone:
1178  csEntry.symTypeString = "-nosymbols-";
1179  break;
1180  case SymCoff:
1181  csEntry.symTypeString = "COFF";
1182  break;
1183  case SymCv:
1184  csEntry.symTypeString = "CV";
1185  break;
1186  case SymPdb:
1187  csEntry.symTypeString = "PDB";
1188  break;
1189  case SymExport:
1190  csEntry.symTypeString = "-exported-";
1191  break;
1192  case SymDeferred:
1193  csEntry.symTypeString = "-deferred-";
1194  break;
1195  case SymSym:
1196  csEntry.symTypeString = "SYM";
1197  break;
1198 #if API_VERSION_NUMBER >= 9
1199  case SymDia:
1200  csEntry.symTypeString = "DIA";
1201  break;
1202 #endif
1203  case 8: //SymVirtual:
1204  csEntry.symTypeString = "Virtual";
1205  break;
1206  default:
1207  //_snprintf( ty, sizeof ty, "symtype=%ld", (long) Module.SymType );
1208  csEntry.symTypeString = NULL;
1209  break;
1210  }
1211 
1212  MyStrCpy(csEntry.moduleName, STACKWALK_MAX_NAMELEN, Module.ModuleName);
1213  csEntry.baseOfImage = Module.BaseOfImage;
1214  MyStrCpy(csEntry.loadedImageName, STACKWALK_MAX_NAMELEN, Module.LoadedImageName);
1215  } // got module info OK
1216  else
1217  {
1218  this->OnDbgHelpErr("SymGetModuleInfo64", GetLastError(), s.AddrPC.Offset);
1219  }
1220  } // we seem to have a valid PC
1221 
1222  CallstackEntryType et = nextEntry;
1223  if (frameNum == 0)
1224  et = firstEntry;
1225  bLastEntryCalled = false;
1226  this->OnCallstackEntry(et, csEntry);
1227 
1228  if (s.AddrReturn.Offset == 0)
1229  {
1230  bLastEntryCalled = true;
1231  this->OnCallstackEntry(lastEntry, csEntry);
1232  SetLastError(ERROR_SUCCESS);
1233  break;
1234  }
1235  } // for ( frameNum )
1236 
1237  cleanup:
1238  if (pSym) free( pSym );
1239 
1240  if (bLastEntryCalled == false)
1241  this->OnCallstackEntry(lastEntry, csEntry);
1242 
1243  if (context == NULL)
1244  ResumeThread(hThread);
1245 
1246  return TRUE;
1247 }
1248 
1249 BOOL __stdcall StackWalker::myReadProcMem(
1250  HANDLE hProcess,
1251  DWORD64 qwBaseAddress,
1252  PVOID lpBuffer,
1253  DWORD nSize,
1254  LPDWORD lpNumberOfBytesRead
1255  )
1256 {
1257  if (s_readMemoryFunction == NULL)
1258  {
1259  SIZE_T st;
1260  BOOL bRet = ReadProcessMemory(hProcess, (LPVOID) qwBaseAddress, lpBuffer, nSize, &st);
1261  *lpNumberOfBytesRead = (DWORD) st;
1262  //printf("ReadMemory: hProcess: %p, baseAddr: %p, buffer: %p, size: %d, read: %d, result: %d\n", hProcess, (LPVOID) qwBaseAddress, lpBuffer, nSize, (DWORD) st, (DWORD) bRet);
1263  return bRet;
1264  }
1265  else
1266  {
1267  return s_readMemoryFunction(hProcess, qwBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead, s_readMemoryFunction_UserData);
1268  }
1269 }
1270 
1271 void StackWalker::OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
1272 {
1273  CHAR buffer[STACKWALK_MAX_NAMELEN];
1274  if (fileVersion == 0)
1275  _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "%s:%s (%p), size: %d (result: %d), SymType: '%s', PDB: '%s'\n", img, mod, (LPVOID) baseAddr, size, result, symType, pdbName);
1276  else
1277  {
1278  DWORD v4 = (DWORD) (fileVersion & 0xFFFF);
1279  DWORD v3 = (DWORD) ((fileVersion>>16) & 0xFFFF);
1280  DWORD v2 = (DWORD) ((fileVersion>>32) & 0xFFFF);
1281  DWORD v1 = (DWORD) ((fileVersion>>48) & 0xFFFF);
1282  _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "%s:%s (%p), size: %d (result: %d), SymType: '%s', PDB: '%s', fileVersion: %d.%d.%d.%d\n", img, mod, (LPVOID) baseAddr, size, result, symType, pdbName, v1, v2, v3, v4);
1283  }
1284  OnOutput(buffer);
1285 }
1286 
1287 void StackWalker::OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry)
1288 {
1289  CHAR buffer[STACKWALK_MAX_NAMELEN];
1290  if ( (eType != lastEntry) && (entry.offset != 0) )
1291  {
1292  if (entry.name[0] == 0)
1293  MyStrCpy(entry.name, STACKWALK_MAX_NAMELEN, "(function-name not available)");
1294  if (entry.undName[0] != 0)
1295  MyStrCpy(entry.name, STACKWALK_MAX_NAMELEN, entry.undName);
1296  if (entry.undFullName[0] != 0)
1297  MyStrCpy(entry.name, STACKWALK_MAX_NAMELEN, entry.undFullName);
1298  if (entry.lineFileName[0] == 0)
1299  {
1300  MyStrCpy(entry.lineFileName, STACKWALK_MAX_NAMELEN, "(filename not available)");
1301  if (entry.moduleName[0] == 0)
1302  MyStrCpy(entry.moduleName, STACKWALK_MAX_NAMELEN, "(module-name not available)");
1303  _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "%p (%s): %s: %s\n", (LPVOID) entry.offset, entry.moduleName, entry.lineFileName, entry.name);
1304  }
1305  else
1306  _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "%s (%d): %s\n", entry.lineFileName, entry.lineNumber, entry.name);
1307  buffer[STACKWALK_MAX_NAMELEN-1] = 0;
1308  OnOutput(buffer);
1309  }
1310 }
1311 
1312 void StackWalker::OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr)
1313 {
1314  CHAR buffer[STACKWALK_MAX_NAMELEN];
1315  _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "ERROR: %s, GetLastError: %d (Address: %p)\n", szFuncName, gle, (LPVOID) addr);
1316  OnOutput(buffer);
1317 }
1318 
1319 void StackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName)
1320 {
1321  CHAR buffer[STACKWALK_MAX_NAMELEN];
1322  _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "SymInit: Symbol-SearchPath: '%s', symOptions: %d, UserName: '%s'\n", szSearchPath, symOptions, szUserName);
1323  OnOutput(buffer);
1324  // Also display the OS-version
1325 #if _MSC_VER <= 1200
1326  OSVERSIONINFOA ver;
1327  ZeroMemory(&ver, sizeof(OSVERSIONINFOA));
1328  ver.dwOSVersionInfoSize = sizeof(ver);
1329  if (GetVersionExA(&ver) != FALSE)
1330  {
1331  _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "OS-Version: %d.%d.%d (%s)\n",
1332  ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber,
1333  ver.szCSDVersion);
1334  OnOutput(buffer);
1335  }
1336 #else
1337  OSVERSIONINFOEXA ver;
1338  ZeroMemory(&ver, sizeof(OSVERSIONINFOEXA));
1339  ver.dwOSVersionInfoSize = sizeof(ver);
1340  if (GetVersionExA( (OSVERSIONINFOA*) &ver) != FALSE)
1341  {
1342  _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "OS-Version: %d.%d.%d (%s) 0x%x-0x%x\n",
1343  ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber,
1344  ver.szCSDVersion, ver.wSuiteMask, ver.wProductType);
1345  OnOutput(buffer);
1346  }
1347 #endif
1348 }
1349 
1350 void StackWalker::OnOutput(LPCSTR buffer)
1351 {
1352  OutputDebugStringA(buffer);
1353 }