summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/CMakeLists.txt7
-rw-r--r--src/LeakFinder.cpp1048
-rw-r--r--src/LeakFinder.h156
-rw-r--r--src/MemoryLeak.h19
-rw-r--r--src/OSSupport/CMakeLists.txt2
-rw-r--r--src/OSSupport/StackTrace.cpp8
-rw-r--r--src/OSSupport/WinStackWalker.cpp1257
-rw-r--r--src/OSSupport/WinStackWalker.h173
-rw-r--r--src/Server.cpp37
-rw-r--r--src/StackWalker.cpp1347
-rw-r--r--src/StackWalker.h214
-rw-r--r--src/main.cpp30
12 files changed, 1435 insertions, 2863 deletions
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 93a1fa368..3ae56e635 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -202,10 +202,6 @@ if (NOT MSVC)
else ()
# MSVC-specific handling: Put all files into one project, separate by the folders:
- # Add the MSVC-specific LeakFinder sources:
- list (APPEND SRCS LeakFinder.cpp StackWalker.cpp)
- list (APPEND HDRS LeakFinder.h StackWalker.h MemoryLeak.h)
-
source_group(Bindings FILES "Bindings/Bindings.cpp" "Bindings/Bindings.h")
# Add all subfolders as solution-folders:
@@ -258,9 +254,6 @@ else ()
SET_SOURCE_FILES_PROPERTIES(
Bindings/Bindings.cpp PROPERTIES COMPILE_FLAGS "/Yc\"string.h\" /Fp\"$(IntDir)/Bindings.pch\""
)
- SET_SOURCE_FILES_PROPERTIES(
- "StackWalker.cpp LeakFinder.cpp" PROPERTIES COMPILE_FLAGS "/Yc\"Globals.h\""
- )
list(APPEND SOURCE "Resources/Cuberite.rc")
# Make MSVC generate the PDB files even for the release build:
diff --git a/src/LeakFinder.cpp b/src/LeakFinder.cpp
deleted file mode 100644
index dba8275c8..000000000
--- a/src/LeakFinder.cpp
+++ /dev/null
@@ -1,1048 +0,0 @@
-
-// LeakFinder.cpp
-
-// Finds memory leaks rather effectively
-
-// _X: downloaded from http://www.codeproject.com/Articles/3134/Memory-Leak-and-Exception-Trace-CRT-and-COM-Leaks - the real link is in the comments, RC11 version
-
-
-
-
-
-/**********************************************************************
- *
- * LEAKFINDER.CPP
- *
- *
- *
- * History:
- * 2010-04-15 RC10 - Updated to VC10 RTM
- * Fixed Bug: Application Verifier, thanks to handsinmypocket!
- * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=3439751#xx3439751xx
- * 2008-08-04 RC6 - Updated to VC9 RTM
- * Fixed Bug: Missing "ole32.lib" LIB
- * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=2253980#xx2253980xx
- * Fixed Bug: Compiled with "WIN32_LEAN_AND_MEAN"
- * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=1824718#xx1824718xx
- * Fixed Bug: Compiling with "/Wall"
- * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=2638243#xx2638243xx
- * Removed "#pragma init_seg (compiler)" from h-file
- *
- * 2005-12-30 RC5 - Now again VC8 RTM compatible
- * - Added Xml-Output (like in the old Leakfinder)
- * YOu need to define XML_LEAK_FINDER to activate it
- * So you can use the LeakAnalyseTool from
- * http://www.codeproject.com/tools/leakfinder.asp
- *
- * 2005-12-13 RC4 - Merged with the new "StackWalker"-project on
- * http://www.codeproject.com/threads/StackWalker.asp
- *
- * 2005-08-01 RC3 - Merged with the new "StackWalker"-project on
- * http://www.codeproject.com/threads/StackWalker.asp
- *
- * 2005-07-05 RC2 - First version with x86, IA64 and x64 support
- *
- * 2005-07-04 RC1 - Added "OutputOptions"
- * - New define "INIT_LEAK_FINDER_VERBOSE" to
- * display more info (for error reporting)
- *
- * 2005-07-01 Beta3 - Workaround for a bug in the new dbghelp.dll
- * (version 6.5.3.7 from 2005-05-30; StakWalk64 no
- * refused to produce an callstack on x86 systems
- * if the context is NULL or has some registers set
- * to 0 (for example Esp). This is against the
- * documented behaviour of StackWalk64...)
- * - First version with x64-support
- *
- * 2005-06-16 Beta1 First public release with the following features:
- * - Completely rewritten in C++ (object oriented)
- * - CRT-Leak-Report
- * - COM-Leak-Report
- * - Report is done via "OutputDebugString" so
- * the line can directly selected in the debugger
- * and is opening the corresponding file/line of
- * the allocation
- * - Tried to support x64 systems, bud had some
- * trouble wih StackWalk64
- * See: http://blog.kalmbachnet.de/?postid=43
- *
- * LICENSE (http://www.opensource.org/licenses/bsd-license.php)
- *
- * Copyright (c) 2005-2010, Jochen Kalmbach
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * Neither the name of Jochen Kalmbach nor the names of its contributors may be
- * used to endorse or promote products derived from this software without
- * specific prior written permission.
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- **********************************************************************/
-
-#include "Globals.h"
-
-#include <tchar.h>
-#include <objidl.h> // Needed if compiled with "WIN32_LEAN_AND_MEAN"
-#include <crtdbg.h>
-
-#include "LeakFinder.h"
-
-// Currently only tested with MS VC++ 5 to 2015
-#if (_MSC_VER < 1100) || (_MSC_VER > 1900)
- #error Only MS VC++ 5/6/7/7.1/8/9/10/11/12 supported. Check if the '_CrtMemBlockHeader' has not changed with this compiler!
-#endif
-
-
-/* _X: MSVC 2012 (MSC 1700) seems to use a different allocation scheme for STL containers,
-* allocating lots of small objects and running out of memory very soon
-* Thus for MSVC 2012 we cut the callstack buffer length in half
-*
-* _X 2013_08_25: The callstack tracking gets worse even for MSVC 2008, a single lua_state eats 50 MiB of RAM
-* Therefore I decided to further reduce the buffers from 0x2000 to 0x1000
-*/
-// Controlling the callstack depth
-#if (_MSC_VER < 1700)
- #define MAX_CALLSTACK_LEN_BUF 0x1000
-#else
- #define MAX_CALLSTACK_LEN_BUF 0x0800
-#endif
-
-
-
-
-
-#define IGNORE_CRT_ALLOC
-
-// disable 64-bit compatibility-checks (because we explicite have here either x86 or x64!)
-#pragma warning(disable:4312) // warning C4312: 'type cast' : conversion from 'DWORD' to 'LPCVOID' of greater size
-#pragma warning(disable:4826)
-
-
-// secure-CRT_functions are only available starting with VC8
-#if _MSC_VER < 1400
-#define _snprintf_s _snprintf
-#define _tcscat_s _tcscat
-#endif
-
-
-
-
-
-static std::string SimpleXMLEncode(LPCSTR szText)
-{
- std::string szRet;
- for (size_t i=0; i<strlen(szText); i++)
- {
- switch(szText[i])
- {
- case '&':
- szRet.append("&amp;");
- break;
- case '<':
- szRet.append("&lt;");
- break;
- case '>':
- szRet.append("&gt;");
- break;
- case '"':
- szRet.append("&quot;");
- break;
- case '\'':
- szRet.append("&apos;");
- break;
- default:
- szRet += szText[i];
- }
- }
- return szRet;
-}
-
-
-
-
-
-LeakFinderOutput::LeakFinderOutput(int options, LPCSTR szSymPath)
- : StackWalker(options, szSymPath)
-{
-}
-
-
-
-
-
-void LeakFinderOutput::OnLeakSearchStart(LPCSTR szLeakFinderName)
-{
- CHAR buffer[1024];
- _snprintf_s(buffer, 1024, "######## %s ########\n", szLeakFinderName);
- this->OnOutput(buffer);
-}
-
-
-
-
-
-void LeakFinderOutput::OnLeakStartEntry(LPCSTR szKeyName, SIZE_T nDataSize)
-{
- CHAR buffer[1024];
- _snprintf_s(buffer, 1024, "--------------- Key: %s, %d bytes ---------\n", szKeyName, nDataSize);
- this->OnOutput(buffer);
-}
-
-
-
-
-
-void LeakFinderOutput::OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry)
-{
- if ( (eType != lastEntry) && (entry.offset != 0) )
- {
- if ( ((this->m_options & LeakFinderShowCompleteCallstack) == 0) && (
- (strstr(entry.lineFileName, "afxmem.cpp") != NULL) ||
- (strstr(entry.lineFileName, "dbgheap.c") != NULL) ||
- (strstr(entry.lineFileName, "new.cpp") != NULL) ||
- (strstr(entry.lineFileName, "newop.cpp") != NULL) ||
- (strstr(entry.lineFileName, "leakfinder.cpp") != NULL) ||
- (strstr(entry.lineFileName, "stackwalker.cpp") != NULL)
- ) )
- {
- return;
- }
- }
- StackWalker::OnCallstackEntry(eType, entry);
-}
-
-
-
-
-
-// ####################################################################
-// XML-Output
-LeakFinderXmlOutput::LeakFinderXmlOutput()
-{
- TCHAR szXMLFileName[1024];
-
- GetModuleFileName(NULL, szXMLFileName, sizeof(szXMLFileName) / sizeof(TCHAR));
- _tcscat_s(szXMLFileName, _T(".mem.xml-leaks"));
-#if _MSC_VER < 1400
- m_fXmlFile = _tfopen(szXMLFileName, _T("w"));
-#else
- m_fXmlFile = NULL;
- _tfopen_s(&m_fXmlFile, szXMLFileName, _T("w"));
-#endif
- if (m_fXmlFile != NULL)
- {
- SYSTEMTIME st;
- GetLocalTime(&st);
- fprintf(m_fXmlFile, "<MEMREPORT date=\"%.2d/%.2d/%.4d\" time=\"%.2d:%.2d:%.2d\">\n",
- st.wMonth, st.wDay, st.wYear,
- st.wHour, st.wMinute, st.wSecond);
- }
- else
- {
- MessageBox(NULL, _T("Could not open xml-logfile for leakfinder!"), _T("Warning"), MB_ICONHAND);
- }
-}
-
-
-
-
-
-LeakFinderXmlOutput::LeakFinderXmlOutput(LPCTSTR szFileName) :
- m_Progress(10)
-{
-#if _MSC_VER < 1400
- m_fXmlFile = _tfopen(szFileName, _T("w"));
-#else
- m_fXmlFile = NULL;
- _tfopen_s(&m_fXmlFile, szFileName, _T("w"));
-#endif
- if (m_fXmlFile == NULL)
- {
- MessageBox(NULL, _T("Could not open xml-logfile for leakfinder!"), _T("Warning"), MB_ICONHAND);
- }
- else
- {
- fprintf(m_fXmlFile, "<MEMREPORT>\n");
- }
-}
-
-
-
-
-
-LeakFinderXmlOutput::~LeakFinderXmlOutput()
-{
- if (m_fXmlFile != NULL)
- {
- // Write the ending-tags and close the file
- fprintf(m_fXmlFile, "</MEMREPORT>\n");
- fclose(m_fXmlFile);
- }
- m_fXmlFile = NULL;
-}
-
-
-
-
-
-void LeakFinderXmlOutput::OnLeakSearchStart(LPCSTR sszLeakFinderName)
-{
-}
-
-
-
-
-
-void LeakFinderXmlOutput::OnLeakStartEntry(LPCSTR szKeyName, SIZE_T nDataSize)
-{
- if (m_fXmlFile != NULL)
- {
- fprintf(m_fXmlFile, "\t<LEAK requestID=\"%s\" size=\"%d\">\n", SimpleXMLEncode(szKeyName).c_str(), nDataSize);
- }
- if (--m_Progress == 0)
- {
- m_Progress = 100;
- putc('.', stdout);
- }
-}
-
-
-
-
-
-void LeakFinderXmlOutput::OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry)
-{
- if (m_fXmlFile != NULL)
- {
- if (eType != lastEntry)
- {
- fprintf(m_fXmlFile, "\t\t<STACKENTRY decl=\"%s\" decl_offset=\"%+ld\" ", SimpleXMLEncode(entry.undName).c_str(), entry.offsetFromSmybol);
- fprintf(m_fXmlFile, "srcfile=\"%s\" line=\"%d\" line_offset=\"%+ld\" ", SimpleXMLEncode(entry.lineFileName).c_str(), entry.lineNumber, entry.offsetFromLine);
- fprintf(m_fXmlFile, "module=\"%s\" base=\"%08lx\" ", SimpleXMLEncode(entry.moduleName).c_str(), entry.baseOfImage);
- fprintf(m_fXmlFile, "/>\n");
- }
- else
- {
- fprintf(m_fXmlFile, "\t</LEAK>\n");
- }
- }
-}
-
-
-
-
-
-// ##########################################################################
-// ##########################################################################
-// ##########################################################################
-// Base class for storing contexts in a hashtable
-template <typename HASHTABLE_KEY> class ContextHashtableBase
-{
-public:
- ContextHashtableBase(SIZE_T sizeOfHastable, LPCSTR finderName)
- {
- SIZE_T s = sizeOfHastable*sizeof(AllocHashEntryType);
- m_hHeap = HeapCreate(0, 10*1024 + s, 0);
- if (m_hHeap == NULL)
- throw;
- pAllocHashTable = (AllocHashEntryType*) own_malloc(s);
- sAllocEntries = sizeOfHastable;
- m_finderName = own_strdup(finderName);
- }
-
-protected:
- virtual ~ContextHashtableBase()
- {
- if (pAllocHashTable != NULL)
- own_free(pAllocHashTable);
- pAllocHashTable = NULL;
-
- own_free(m_finderName);
- m_finderName = NULL;
-
- if (m_hHeap != NULL)
- HeapDestroy(m_hHeap);
- }
-
- __inline LPVOID own_malloc(SIZE_T size)
- {
- return HeapAlloc(m_hHeap, HEAP_ZERO_MEMORY, size);
- }
- __inline VOID own_free(LPVOID memblock)
- {
- HeapFree(m_hHeap, 0, memblock);
- }
- __inline CHAR *own_strdup(const char *str)
- {
- size_t len = strlen(str)+1;
- CHAR *c = (CHAR*)own_malloc(len);
-#if _MSC_VER >= 1400
- strcpy_s(c, len, str);
-#else
- strcpy(c, str);
-#endif
- return c;
- }
-
- // Disables this leak-finder
- virtual LONG Disable() = 0;
- // enables the leak-finder again...
- virtual LONG Enable() = 0;
-
-protected:
- // Entry for each allocation
- typedef struct AllocHashEntryType {
- HASHTABLE_KEY key;
- SIZE_T nDataSize; // Size of the allocated memory
- struct AllocHashEntryType *Next;
- CONTEXT c;
- PVOID pStackBaseAddr;
- SIZE_T nMaxStackSize;
-
- PVOID pCallstackOffset;
- SIZE_T nCallstackLen;
- char pcCallstackAddr[MAX_CALLSTACK_LEN_BUF]; // min of both values...
- } AllocHashEntryType;
-
-protected:
- virtual SIZE_T HashFunction(HASHTABLE_KEY &key) = 0;
- virtual BOOL IsKeyEmpty(HASHTABLE_KEY &key) = 0;
- virtual VOID SetEmptyKey(HASHTABLE_KEY &key) = 0;
- virtual VOID GetKeyAsString(HASHTABLE_KEY &key, CHAR *szName, SIZE_T nBufferLen) = 0;
- //virtual SIZE_T GetNativeBytes(HASHTABLE_KEY &key, CHAR *szName, SIZE_T nBufferLen) { return 0; }
-
-public:
- VOID Insert(HASHTABLE_KEY &key, CONTEXT &context, SIZE_T nDataSize)
- {
- SIZE_T HashIdx;
- AllocHashEntryType *pHashEntry;
-
- // generate hash-value
- HashIdx = HashFunction(key);
-
- pHashEntry = &pAllocHashTable[HashIdx];
- if (IsKeyEmpty(pHashEntry->key) != FALSE) {
- // Entry is empty...
- }
- else {
- // Entry is not empy! make a list of entries for this hash value...
- while(pHashEntry->Next != NULL) {
- pHashEntry = pHashEntry->Next;
- }
-
- pHashEntry->Next = (AllocHashEntryType*) own_malloc(sizeof(AllocHashEntryType));
- g_CurrentMemUsage += CRTTable::AllocHashEntryTypeSize;
- pHashEntry = pHashEntry->Next;
- if (pHashEntry == NULL)
- {
- // Exhausted the available memory?
- return;
- }
- }
- pHashEntry->key = key;
- pHashEntry->nDataSize = nDataSize;
- pHashEntry->Next = NULL;
-#ifdef _M_IX86
- pHashEntry->pCallstackOffset = (LPVOID) std::min(context.Ebp, context.Esp);
-#elif _M_X64
- pHashEntry->pCallstackOffset = (LPVOID) std::min(context.Rdi, context.Rsp);
-#elif _M_IA64
- pHashEntry->pCallstackOffset = (LPVOID) std::min(context.IntSp, context.RsBSP);
-#else
-#error "Platform not supported!"
-#endif
- pHashEntry->c = context;
-
- // Query the max. stack-area:
- MEMORY_BASIC_INFORMATION MemBuffer;
- if(VirtualQuery((LPCVOID) pHashEntry->pCallstackOffset, &MemBuffer, sizeof(MemBuffer)) > 0)
- {
- pHashEntry->pStackBaseAddr = MemBuffer.BaseAddress;
- pHashEntry->nMaxStackSize = MemBuffer.RegionSize;
- }
- else
- {
- pHashEntry->pStackBaseAddr = 0;
- pHashEntry->nMaxStackSize = 0;
- }
-
- SIZE_T bytesToRead = MAX_CALLSTACK_LEN_BUF;
- if (pHashEntry->nMaxStackSize > 0)
- {
- SIZE_T len = ((SIZE_T) pHashEntry->pStackBaseAddr + pHashEntry->nMaxStackSize) - (SIZE_T)pHashEntry->pCallstackOffset;
- bytesToRead = std::min(len, (SIZE_T)MAX_CALLSTACK_LEN_BUF);
- }
- // Now read the callstack:
- if (ReadProcessMemory(GetCurrentProcess(), (LPCVOID) pHashEntry->pCallstackOffset, &(pHashEntry->pcCallstackAddr), bytesToRead, &(pHashEntry->nCallstackLen)) == 0)
- {
- // Could not read memory...
- pHashEntry->nCallstackLen = 0;
- pHashEntry->pCallstackOffset = 0;
- } // read callstack
- } // Insert
-
- BOOL Remove(HASHTABLE_KEY &key)
- {
- SIZE_T HashIdx;
- AllocHashEntryType *pHashEntry, *pHashEntryLast;
-
- // get the Hash-Value
- HashIdx = HashFunction(key);
-
- pHashEntryLast = NULL;
- pHashEntry = &pAllocHashTable[HashIdx];
- while(pHashEntry != NULL) {
- if (pHashEntry->key == key) {
- // release my memory
- if (pHashEntryLast == NULL) {
- // It is an entry in the table, so do not release this memory
- if (pHashEntry->Next == NULL) {
- // It was the last entry, so empty the table entry
- SetEmptyKey(pAllocHashTable[HashIdx].key);
- //memset(&pAllocHashTable[HashIdx], 0, sizeof(pAllocHashTable[HashIdx]));
- }
- else {
- // There are some more entries, so shorten the list
- AllocHashEntryType *pTmp = pHashEntry->Next;
- *pHashEntry = *(pHashEntry->Next);
- own_free(pTmp);
- g_CurrentMemUsage -= CRTTable::AllocHashEntryTypeSize;
- }
- return TRUE;
- }
- else {
- // now, I am in an dynamic allocated entry (it was a collision)
- pHashEntryLast->Next = pHashEntry->Next;
- own_free(pHashEntry);
- g_CurrentMemUsage -= CRTTable::AllocHashEntryTypeSize;
- return TRUE;
- }
- }
- pHashEntryLast = pHashEntry;
- pHashEntry = pHashEntry->Next;
- }
-
- // if we are here, we could not find the RequestID
- return FALSE;
- }
-
- AllocHashEntryType *Find(HASHTABLE_KEY &key)
- {
- SIZE_T HashIdx;
- AllocHashEntryType *pHashEntry;
-
- // get the Hash-Value
- HashIdx = HashFunction(key);
-
- pHashEntry = &pAllocHashTable[HashIdx];
- while(pHashEntry != NULL) {
- if (pHashEntry->key == key) {
- return pHashEntry;
- }
- pHashEntry = pHashEntry->Next;
- }
-
- // entry was not found!
- return NULL;
- }
-
- // For the followong static-var See comment in "ShowCallstack"...
- static BOOL CALLBACK ReadProcessMemoryFromHashEntry64(
- HANDLE hProcess, // hProcess must be a pointer to an hash-entry!
- DWORD64 lpBaseAddress,
- PVOID lpBuffer,
- DWORD nSize,
- LPDWORD lpNumberOfBytesRead,
- LPVOID pUserData // optional data, which was passed in "ShowCallstack"
- )
- {
- *lpNumberOfBytesRead = 0;
- AllocHashEntryType *pHashEntry = (AllocHashEntryType*) pUserData;
- if (pHashEntry == NULL)
- {
- return FALSE;
- }
-
- if ( ( (DWORD64)lpBaseAddress >= (DWORD64)pHashEntry->pCallstackOffset) && ((DWORD64)lpBaseAddress <= ((DWORD64)pHashEntry->pCallstackOffset+pHashEntry->nCallstackLen)) ) {
- // Memory is located in saved Callstack:
- // Calculate the offset
- DWORD dwOffset = (DWORD) ((DWORD64)lpBaseAddress - (DWORD64)pHashEntry->pCallstackOffset);
- DWORD dwSize = __min(nSize, MAX_CALLSTACK_LEN_BUF-dwOffset);
- memcpy(lpBuffer, &(pHashEntry->pcCallstackAddr[dwOffset]), dwSize);
- *lpNumberOfBytesRead = dwSize;
- if (dwSize != nSize)
- {
- return FALSE;
- }
- *lpNumberOfBytesRead = nSize;
- return TRUE;
- }
-
- if (*lpNumberOfBytesRead == 0) // Memory could not be found
- {
- if ( ( (DWORD64)lpBaseAddress < (DWORD64)pHashEntry->pStackBaseAddr) || ((DWORD64)lpBaseAddress > ((DWORD64)pHashEntry->pStackBaseAddr+pHashEntry->nMaxStackSize)) )
- {
- // Stackwalking is done by reading the "real memory" (normally this happens when the StackWalk64 tries to read some code)
- SIZE_T st = 0;
- BOOL bRet = ReadProcessMemory(hProcess, (LPCVOID) lpBaseAddress, lpBuffer, nSize, &st);
- *lpNumberOfBytesRead = (DWORD) st;
- return bRet;
- }
- }
-
- return TRUE;
- }
-
- VOID ShowLeaks(LeakFinderOutput &leakFinderOutput)
- {
- SIZE_T ulTemp;
- AllocHashEntryType *pHashEntry;
- ULONG ulCount = 0;
- SIZE_T ulLeaksByte = 0;
-
- leakFinderOutput.OnLeakSearchStart(this->m_finderName);
-
- // Move throu every entry
- CHAR keyName[1024];
- for(ulTemp = 0; ulTemp < this->sAllocEntries; ulTemp++) {
- pHashEntry = &pAllocHashTable[ulTemp];
- if (IsKeyEmpty(pHashEntry->key) == FALSE) {
- while(pHashEntry != NULL) {
- ulCount++;
- CONTEXT c;
- memcpy(&c, &(pHashEntry->c), sizeof(CONTEXT));
-
- this->GetKeyAsString(pHashEntry->key, keyName, 1024);
-
- leakFinderOutput.OnLeakStartEntry(keyName, pHashEntry->nDataSize);
- leakFinderOutput.ShowCallstack(GetCurrentThread(), &c, ReadProcessMemoryFromHashEntry64, pHashEntry);
-
- // Count the number of leaky bytes
- ulLeaksByte += pHashEntry->nDataSize;
-
- pHashEntry = pHashEntry->Next;
- } // while
- }
- }
- }
-
- AllocHashEntryType *pAllocHashTable;
- SIZE_T sAllocEntries;
- HANDLE m_hHeap;
- LPSTR m_finderName;
- bool m_bSupressUselessLines;
-}; // template <typename HASHTABLE_KEY> class ContextHashtableBase
-
-
-
-
-
-// ##########################################################################
-// ##########################################################################
-// ##########################################################################
-// Specialization for CRT-Leaks:
-// VC5 has excluded all types in release-builds
-#ifdef _DEBUG
-
-// The follwoing is copied from dbgint.h:
-// <CRT_INTERNALS>
-/*
-* For diagnostic purpose, blocks are allocated with extra information and
-* stored in a doubly-linked list. This makes all blocks registered with
-* how big they are, when they were allocated, and what they are used for.
-*/
-
-// forward declaration:
-#ifndef _M_CEE_PURE
-#define MyAllocHookCallingConvention __cdecl
-#endif
-#if _MSC_VER >= 1400
-#ifdef _M_CEE
-#define MyAllocHookCallingConvention __clrcall
-#endif
-#endif
-
-static int MyAllocHookCallingConvention MyAllocHook(int nAllocType, void *pvData,
- size_t nSize, int nBlockUse, long lRequest,
-#if _MSC_VER <= 1100 // Special case for VC 5 and before
- const char * szFileName,
-#else
- const unsigned char * szFileName,
-#endif
- int nLine);
-
-static _CRT_ALLOC_HOOK s_pfnOldCrtAllocHook = NULL;
-static LONG s_CrtDisableCount = 0;
-static LONG s_lMallocCalled = 0;
-
-
-
-
-
-class CRTTable : public ContextHashtableBase<LONG>
-{
-public:
- CRTTable() : ContextHashtableBase<LONG>(1021, "CRT-Leaks")
- {
- // save the previous alloc hook
- s_pfnOldCrtAllocHook = _CrtSetAllocHook(MyAllocHook);
- }
-
- virtual ~CRTTable()
- {
- _CrtSetAllocHook(s_pfnOldCrtAllocHook);
- }
-
- virtual LONG Disable()
- {
- return InterlockedIncrement(&s_CrtDisableCount);
- }
- virtual LONG Enable()
- {
- return InterlockedDecrement(&s_CrtDisableCount);
- }
-
- virtual SIZE_T HashFunction(LONG &key)
- {
- // I couldnīt find any better and faster
- return key % sAllocEntries;
- }
- virtual BOOL IsKeyEmpty(LONG &key)
- {
- if (key == 0)
- return TRUE;
- return FALSE;
- }
- virtual VOID SetEmptyKey(LONG &key)
- {
- key = 0;
- }
- virtual VOID GetKeyAsString(LONG &key, CHAR *szName, SIZE_T nBufferLen)
- {
-#if _MSC_VER < 1400
- _snprintf_s(szName, nBufferLen, "%d", key);
-#else
- _snprintf_s(szName, nBufferLen, nBufferLen, "%d", key);
-#endif
- }
-
- static const int AllocHashEntryTypeSize = sizeof(AllocHashEntryType);
-
-protected:
- CHAR *m_pBuffer;
- SIZE_T m_maxBufferLen;
- SIZE_T m_bufferLen;
-}; // class CRTTable
-
-
-#define nNoMansLandSize 4
-
-typedef struct _CrtMemBlockHeader
-{
- struct _CrtMemBlockHeader * pBlockHeaderNext;
- struct _CrtMemBlockHeader * pBlockHeaderPrev;
- char * szFileName;
- int nLine;
-#ifdef _WIN64
- /* These items are reversed on Win64 to eliminate gaps in the struct
- * and ensure that sizeof(struct)%16 == 0, so 16-byte alignment is
- * maintained in the debug heap.
- */
- int nBlockUse;
- size_t nDataSize;
-#else /* _WIN64 */
- size_t nDataSize;
- int nBlockUse;
-#endif /* _WIN64 */
- long lRequest;
- unsigned char gap[nNoMansLandSize];
- /* followed by:
- * unsigned char data[nDataSize];
- * unsigned char anotherGap[nNoMansLandSize];
- */
-} _CrtMemBlockHeader;
-#define pbData(pblock) ((unsigned char *)((_CrtMemBlockHeader *)pblock + 1))
-#define pHdr(pbData) (((_CrtMemBlockHeader *)pbData)-1)
-// </CRT_INTERNALS>
-
-static CRTTable *g_pCRTTable = NULL;
-
-size_t g_CurrentMemUsage = 0;
-
-
-
-
-
-// MyAllocHook is Single-Threaded, that means the the calls are serialized in the calling function!
-static int MyAllocHook(int nAllocType, void *pvData,
- size_t nSize, int nBlockUse, long lRequest,
-#if _MSC_VER <= 1100 // Special case for VC 5
- const char * szFileName,
-#else
- const unsigned char * szFileName,
-#endif
- int nLine)
-{
- //static TCHAR *operation[] = { _T(""), _T("ALLOCATIONG"), _T("RE-ALLOCATING"), _T("FREEING") };
- //static TCHAR *blockType[] = { _T("Free"), _T("Normal"), _T("CRT"), _T("Ignore"), _T("Client") };
-
-#ifdef IGNORE_CRT_ALLOC
- if (_BLOCK_TYPE(nBlockUse) == _CRT_BLOCK) // Ignore internal C runtime library allocations
- return TRUE;
-#endif
- extern int _crtDbgFlag;
- if ( ((_CRTDBG_ALLOC_MEM_DF & _crtDbgFlag) == 0) && ( (nAllocType == _HOOK_ALLOC) || (nAllocType == _HOOK_REALLOC) ) )
- {
- // Someone has disabled that the runtime should log this allocation
- // so we do not log this allocation
- if (s_pfnOldCrtAllocHook != NULL)
- s_pfnOldCrtAllocHook(nAllocType, pvData, nSize, nBlockUse, lRequest, szFileName, nLine);
- return TRUE;
- }
-
- // Handle the Disable/Enable setting
- if (InterlockedExchangeAdd(&s_CrtDisableCount, 0) != 0)
- {
- return TRUE;
- }
-
- // Prevent from reentrat calls
- if (InterlockedIncrement(&s_lMallocCalled) > 1)
- {
- // I was already called
- InterlockedDecrement(&s_lMallocCalled);
- // call the previous alloc hook
- if (s_pfnOldCrtAllocHook != NULL)
- s_pfnOldCrtAllocHook(nAllocType, pvData, nSize, nBlockUse, lRequest, szFileName, nLine);
- return TRUE;
- }
-
- _ASSERT( (nAllocType == _HOOK_ALLOC) || (nAllocType == _HOOK_REALLOC) || (nAllocType == _HOOK_FREE) );
- _ASSERT( ( _BLOCK_TYPE(nBlockUse) >= 0 ) && ( _BLOCK_TYPE(nBlockUse) < 5 ) );
-
- if (nAllocType == _HOOK_FREE)
- {
- // freeing
- // Try to get the header information
- if (_CrtIsValidHeapPointer(pvData)) { // it is a valid Heap-Pointer
- // get the ID
- _CrtMemBlockHeader *pHead;
- // get a pointer to memory block header
- pHead = pHdr(pvData);
- nSize = pHead->nDataSize;
- lRequest = pHead->lRequest; // This is the ID!
-
- if (pHead->nBlockUse == _IGNORE_BLOCK)
- {
- InterlockedDecrement(&s_lMallocCalled);
- if (s_pfnOldCrtAllocHook != NULL)
- {
- s_pfnOldCrtAllocHook(nAllocType, pvData, nSize, nBlockUse, lRequest, szFileName, nLine);
- }
- return TRUE;
- }
- }
- if (lRequest != 0)
- {
- // RequestID was found
- size_t temp = g_CurrentMemUsage;
- if (g_pCRTTable->Remove(lRequest))
- {
- g_CurrentMemUsage -= nSize;
- }
- if (g_CurrentMemUsage > temp)
- {
- printf("********************************************\n");
- printf("** Server detected underflow in memory **\n");
- printf("** usage counter. Something is not right. **\n");
- printf("** Writing memory dump into memdump.xml **\n");
- printf("********************************************\n");
- printf("Please wait\n");
-
- LeakFinderXmlOutput Output(L"memdump.xml");
- DumpUsedMemory(&Output);
-
- printf("\nMemory dump complete. Server will now abort.\n");
- abort();
- }
- }
- } // freeing
-
- if (nAllocType == _HOOK_REALLOC)
- {
- // re-allocating
- // Try to get the header information
- if (_CrtIsValidHeapPointer(pvData)) { // it is a valid Heap-Pointer
- BOOL bRet;
- LONG lReallocRequest;
- // get the ID
- _CrtMemBlockHeader *pHead;
- // get a pointer to memory block header
- pHead = pHdr(pvData);
- // Try to find the RequestID in the Hash-Table, mark it that it was freed
- lReallocRequest = pHead->lRequest;
- size_t temp = g_CurrentMemUsage;
- bRet = g_pCRTTable->Remove(lReallocRequest);
- if (bRet)
- {
- g_CurrentMemUsage -= pHead->nDataSize;
- }
- if (g_CurrentMemUsage > temp)
- {
- printf("********************************************\n");
- printf("** Server detected underflow in memory **\n");
- printf("** usage counter. Something is not right. **\n");
- printf("** Writing memory dump into memdump.xml **\n");
- printf("********************************************\n");
- printf("Please wait\n");
-
- LeakFinderXmlOutput Output(L"memdump.xml");
- DumpUsedMemory(&Output);
-
- printf("\nMemory dump complete. Server will now abort.\n");
- abort();
- }
- } // ValidHeapPointer
- } // re-allocating
-
- //if ( (g_ulShowStackAtAlloc < 3) && (nAllocType == _HOOK_FREE) ) {
- if (nAllocType == _HOOK_FREE)
- {
- InterlockedDecrement(&s_lMallocCalled);
- // call the previous alloc hook
- if (s_pfnOldCrtAllocHook != NULL)
- {
- s_pfnOldCrtAllocHook(nAllocType, pvData, nSize, nBlockUse, lRequest, szFileName, nLine);
- }
- return TRUE;
- }
-
- CONTEXT c;
- GET_CURRENT_CONTEXT(c, CONTEXT_FULL);
-
- // Only insert in the Hash-Table if it is not a "freeing"
- if (nAllocType != _HOOK_FREE)
- {
- if (lRequest != 0) // Always a valid RequestID should be provided (see comments in the header)
- {
- //No need to check for overflow since we are checking if we are getting higher than 1gb.
- //If we change this, then we probably would want an overflow check.
- g_CurrentMemUsage += nSize ;
- g_pCRTTable->Insert(lRequest, c, nSize);
-
- if (g_CurrentMemUsage > 1536 * 1024* 1024)
- {
- printf("******************************************\n");
- printf("** Server reached 1.5 GiB memory usage, **\n");
- printf("** something is probably wrong. **\n");
- printf("** Writing memory dump into memdump.xml **\n");
- printf("******************************************\n");
- printf("Please wait\n");
-
- LeakFinderXmlOutput Output(L"memdump.xml");
- DumpUsedMemory(&Output);
-
- printf("\nMemory dump complete. Server will now abort.\n");
- abort();
- }
- }
- }
-
- InterlockedDecrement(&s_lMallocCalled);
- // call the previous alloc hook
- if (s_pfnOldCrtAllocHook != NULL)
- s_pfnOldCrtAllocHook(nAllocType, pvData, nSize, nBlockUse, lRequest, szFileName, nLine);
- return TRUE; // allow the memory operation to proceed
-} // MyAllocHook
-
-#endif // _DEBUG
-
-
-
-
-
-// ##########################################################################
-// ##########################################################################
-// ##########################################################################
-// Init/Deinit functions
-
-HRESULT InitLeakFinder()
-{
- #ifdef _DEBUG
- g_pCRTTable = new CRTTable();
- #endif
- return S_OK;
-}
-
-
-
-
-
-void DumpUsedMemory(LeakFinderOutput * output)
-{
- LeakFinderOutput *pLeakFinderOutput = output;
-
- #ifdef _DEBUG
- g_pCRTTable->Disable();
- #endif
-
- if (pLeakFinderOutput == NULL)
- {
- pLeakFinderOutput = new LeakFinderOutput();
- }
-
- // explicitly load the modules:
- pLeakFinderOutput->LoadModules();
-
- #ifdef _DEBUG
- g_pCRTTable->ShowLeaks(*pLeakFinderOutput);
- #endif
-
- if (output == NULL)
- {
- delete pLeakFinderOutput;
- }
-}
-
-
-
-
-
-void DeinitLeakFinder(LeakFinderOutput *output)
-{
- DumpUsedMemory(output);
-
- #ifdef _DEBUG
- delete g_pCRTTable;
- g_pCRTTable = NULL;
- #endif
-}
-
-
-
-
-
-void DeinitLeakFinder()
-{
- DeinitLeakFinder(NULL);
-}
-
-
-
-
diff --git a/src/LeakFinder.h b/src/LeakFinder.h
deleted file mode 100644
index ceaa53782..000000000
--- a/src/LeakFinder.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/**********************************************************************
- *
- * LEAKFINDER.H
- *
- *
- *
- * LICENSE (http://www.opensource.org/licenses/bsd-license.php)
- *
- * Copyright (c) 2005-2010, Jochen Kalmbach
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * Neither the name of Jochen Kalmbach nor the names of its contributors may be
- * used to endorse or promote products derived from this software without
- * specific prior written permission.
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- **********************************************************************/
-
-// #pragma once is supported starting with _MCS_VER 1000,
-// so we need not to check the version (because we only support _MSC_VER >= 1100)!
-#pragma once
-
-#include <windows.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-HRESULT InitLeakFinder();
-void DeinitLeakFinder();
-
-#ifdef __cplusplus
-}
-#endif
-
-
-// The following is only available if the file is CPP
-#ifdef __cplusplus
-
-#include "StackWalker.h"
-
-// Interface for output...
-class LeakFinderOutput : public StackWalker
-{
-public:
- typedef enum LeakFinderOptions
- {
- // No addition info will be retrived
- // (only the address is available)
- LeakFinderNone = 0,
- LeakFinderShowCompleteCallstack = 0x1000
- } LeakFinderOptions;
-
- LeakFinderOutput(int options = OptionsAll, LPCSTR szSymPath = nullptr);
- virtual void OnLeakSearchStart(LPCSTR sszLeakFinderName);
- virtual void OnLeakStartEntry(LPCSTR szKeyName, SIZE_T nDataSize);
-protected:
- virtual void OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry);
- virtual void OnOutput(LPCSTR szText)
- {
- printf(szText);
- StackWalker::OnOutput(szText);
- }
- virtual void OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr)
- {
- if (strcmp(szFuncName, "SymGetLineFromAddr64") == 0) return;
- StackWalker::OnDbgHelpErr(szFuncName, gle, addr);
- }
-};
-
-class LeakFinderXmlOutput : public LeakFinderOutput
-{
-public:
- LeakFinderXmlOutput();
- virtual ~LeakFinderXmlOutput();
- LeakFinderXmlOutput(LPCTSTR szFileName);
- virtual void OnLeakSearchStart(LPCSTR sszLeakFinderName);
- virtual void OnLeakStartEntry(LPCSTR szKeyName, SIZE_T nDataSize);
-protected:
- virtual void OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry);
- virtual void OnOutput(LPCSTR szText) { }
- virtual void OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr) { }
-
- FILE * m_fXmlFile;
- int m_Progress;
-};
-
-// C++ interface:
-void DeinitLeakFinder(LeakFinderOutput *output);
-
-class ZZZ_LeakFinder
-{
-public:
- ZZZ_LeakFinder()
- {
- m_pXml = nullptr;
-#ifdef XML_LEAK_FINDER
- m_pXml = new LeakFinderXmlOutput();
-#endif
- InitLeakFinder();
- }
- ~ZZZ_LeakFinder()
- {
- DeinitLeakFinder(m_pXml);
- if (m_pXml != nullptr) delete m_pXml;
- }
-protected:
- LeakFinderXmlOutput *m_pXml;
-};
-
-#if defined(INIT_LEAK_FINDER)
-#if _MSC_VER >= 1200
-#pragma warning(push)
-#endif
-#pragma warning (disable:4074)
-
-// WARNING: If you enable this option, the code might run without the CRT being initialized or after the CRT was deinitialized!!!
-// Currently the code is not designed to bypass the CRT...
-//#pragma init_seg (compiler)
-ZZZ_LeakFinder zzz_LeakFinder;
-
-#if _MSC_VER >= 1200
-#pragma warning(pop)
-#else
-#pragma warning(default:4074)
-#endif
-#endif
-
-#endif // __cplusplus
-
-
-
-
-extern void DumpUsedMemory(LeakFinderOutput * output = nullptr);
-
-
-
-
-
diff --git a/src/MemoryLeak.h b/src/MemoryLeak.h
deleted file mode 100644
index 441429c23..000000000
--- a/src/MemoryLeak.h
+++ /dev/null
@@ -1,19 +0,0 @@
-#pragma once
-
-#ifdef _WIN32
- #ifdef _DEBUG
- // Enable the CRT debugging features:
- #define _CRTDBG_MAP_ALLOC
- #include <stdlib.h>
- #include <crtdbg.h>
-
- // This works only in MSVC 2010+:
- #if _MSC_VER >= 1600
- // Map the new operator
- #ifndef DEBUG_NEW
- #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
- #define new DEBUG_NEW
- #endif // _CRTDBG_MAP_ALLOC
- #endif // _MSC_VER
- #endif // _DEBUG
-#endif // _WIN32
diff --git a/src/OSSupport/CMakeLists.txt b/src/OSSupport/CMakeLists.txt
index 8e018425b..e6fb37987 100644
--- a/src/OSSupport/CMakeLists.txt
+++ b/src/OSSupport/CMakeLists.txt
@@ -18,6 +18,7 @@ SET (SRCS
StackTrace.cpp
TCPLinkImpl.cpp
UDPEndpointImpl.cpp
+ WinStackWalker.cpp
)
SET (HDRS
@@ -38,6 +39,7 @@ SET (HDRS
StackTrace.h
TCPLinkImpl.h
UDPEndpointImpl.h
+ WinStackWalker.h
)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
diff --git a/src/OSSupport/StackTrace.cpp b/src/OSSupport/StackTrace.cpp
index c84e2cbca..b8f80f5f3 100644
--- a/src/OSSupport/StackTrace.cpp
+++ b/src/OSSupport/StackTrace.cpp
@@ -6,7 +6,7 @@
#include "Globals.h"
#include "StackTrace.h"
#ifdef _WIN32
- #include "../StackWalker.h"
+ #include "WinStackWalker.h"
#elif !defined(ANDROID) // The Android NDK has no execinfo header
#ifdef __GLIBC__
#include <execinfo.h>
@@ -21,10 +21,8 @@
void PrintStackTrace(void)
{
#ifdef _WIN32
- // Reuse the StackWalker from the LeakFinder project already bound to MCS
- // Define a subclass of the StackWalker that outputs everything to stdout
- class PrintingStackWalker :
- public StackWalker
+ class PrintingStackWalker:
+ public WinStackWalker
{
virtual void OnOutput(LPCSTR szText) override
{
diff --git a/src/OSSupport/WinStackWalker.cpp b/src/OSSupport/WinStackWalker.cpp
new file mode 100644
index 000000000..6d732bd61
--- /dev/null
+++ b/src/OSSupport/WinStackWalker.cpp
@@ -0,0 +1,1257 @@
+// WinStackWalker.cpp
+
+// Implements the stack walking for Windows binaries
+
+
+
+/*
+LICENSE (http://www.opensource.org/licenses/bsd-license.php)
+
+Copyright (c) 2005-2010, Jochen Kalmbach
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
+and / or other materials provided with the distribution.
+Neither the name of Jochen Kalmbach nor the names of its contributors may be
+used to endorse or promote products derived from this software without
+specific prior written permission.
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+NOTE: 2017-06-16 madmaxoft: Removed the legacy VS code and generally cleaned up
+*/
+
+
+
+
+
+#include "Globals.h"
+
+#ifdef _WIN32
+
+#include <tchar.h>
+#pragma comment(lib, "version.lib") // for "VerQueryValue"
+#pragma warning(disable:4826)
+#pragma warning(disable:4996) // "GetVersionEx" was declared deprecated
+
+#include "WinStackWalker.h"
+
+
+#pragma pack(push, 8)
+ #include <dbghelp.h>
+#pragma pack(pop)
+
+
+
+
+
+// Copy szSrc to szDest, but at most nMaxDestSize bytes. Always NUL-terminate
+template<size_t COUNT>
+static void MyStrCpy(CHAR (&szDest)[COUNT], const CHAR * szSrc)
+{
+ auto len = strlen(szSrc);
+ if (len < COUNT)
+ {
+ memcpy(szDest, szSrc, len + 1);
+ }
+ else
+ {
+ memcpy(szDest, szSrc, COUNT - 1);
+ szDest[COUNT - 1] = 0;
+ }
+}
+
+
+
+
+
+// Normally it should be enough to use 'CONTEXT_FULL' (better would be 'CONTEXT_ALL')
+#define USED_CONTEXT_FLAGS CONTEXT_FULL
+
+
+
+
+
+class StackWalkerInternal
+{
+public:
+ StackWalkerInternal(WinStackWalker * parent, HANDLE hProcess)
+ {
+ m_parent = parent;
+ m_hDbhHelp = nullptr;
+ pSC = nullptr;
+ m_hProcess = hProcess;
+ m_szSymPath = nullptr;
+ pSFTA = nullptr;
+ pSGLFA = nullptr;
+ pSGMB = nullptr;
+ pSGMI = nullptr;
+ pSGO = nullptr;
+ pSGSFA = nullptr;
+ pSI = nullptr;
+ pSLM = nullptr;
+ pSSO = nullptr;
+ pSW = nullptr;
+ pUDSN = nullptr;
+ pSGSP = nullptr;
+ }
+
+
+ ~StackWalkerInternal()
+ {
+ if (pSC != nullptr)
+ {
+ pSC(m_hProcess); // SymCleanup
+ }
+ if (m_hDbhHelp != nullptr)
+ {
+ FreeLibrary(m_hDbhHelp);
+ }
+ m_hDbhHelp = nullptr;
+ m_parent = nullptr;
+ if (m_szSymPath != nullptr)
+ {
+ free(m_szSymPath);
+ }
+ m_szSymPath = nullptr;
+ }
+
+
+ BOOL Init(LPCSTR szSymPath)
+ {
+ if (m_parent == nullptr)
+ {
+ return FALSE;
+ }
+ // Dynamically load the Entry-Points for dbghelp.dll:
+ // First try to load the newsest one from
+ TCHAR szTemp[4096];
+ // But before wqe do this, we first check if the ".local" file exists
+ if (GetModuleFileName(nullptr, szTemp, sizeof(szTemp)) > 0)
+ {
+ _tcscat_s(szTemp, _T(".local"));
+ if (GetFileAttributes(szTemp) == INVALID_FILE_ATTRIBUTES)
+ {
+ // ".local" file does not exist, so we can try to load the dbghelp.dll from the "Debugging Tools for Windows"
+ // Ok, first try the new path according to the archtitecture:
+ #ifdef _M_IX86
+ if ((m_hDbhHelp == nullptr) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, ARRAYCOUNT(szTemp)) > 0))
+ {
+ _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (x86)\\dbghelp.dll"));
+ // now check if the file exists:
+ if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
+ {
+ m_hDbhHelp = LoadLibrary(szTemp);
+ }
+ }
+ #elif _M_X64
+ if ((m_hDbhHelp == nullptr) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, ARRAYCOUNT(szTemp)) > 0))
+ {
+ _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (x64)\\dbghelp.dll"));
+ // now check if the file exists:
+ if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
+ {
+ m_hDbhHelp = LoadLibrary(szTemp);
+ }
+ }
+ #elif _M_IA64
+ if ((m_hDbhHelp == nullptr) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, ARRAYCOUNT(szTemp)) > 0))
+ {
+ _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (ia64)\\dbghelp.dll"));
+ // now check if the file exists:
+ if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
+ {
+ m_hDbhHelp = LoadLibrary(szTemp);
+ }
+ }
+ #endif
+ // If still not found, try the old directories...
+ if ((m_hDbhHelp == nullptr) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, ARRAYCOUNT(szTemp)) > 0))
+ {
+ _tcscat_s(szTemp, _T("\\Debugging Tools for Windows\\dbghelp.dll"));
+ // now check if the file exists:
+ if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
+ {
+ m_hDbhHelp = LoadLibrary(szTemp);
+ }
+ }
+ #if defined _M_X64 || defined _M_IA64
+ // Still not found? Then try to load the (old) 64-Bit version:
+ if ((m_hDbhHelp == nullptr) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, ARRAYCOUNT(szTemp)) > 0))
+ {
+ _tcscat_s(szTemp, _T("\\Debugging Tools for Windows 64-Bit\\dbghelp.dll"));
+ if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
+ {
+ m_hDbhHelp = LoadLibrary(szTemp);
+ }
+ }
+ #endif
+ }
+ }
+ if (m_hDbhHelp == nullptr) // if not already loaded, try to load a default-one
+ {
+ m_hDbhHelp = LoadLibrary(_T("dbghelp.dll"));
+ }
+ if (m_hDbhHelp == nullptr)
+ {
+ return FALSE;
+ }
+ pSI = (tSI)GetProcAddress(m_hDbhHelp, "SymInitialize");
+ pSC = (tSC)GetProcAddress(m_hDbhHelp, "SymCleanup");
+
+ pSW = (tSW)GetProcAddress(m_hDbhHelp, "StackWalk64");
+ pSGO = (tSGO)GetProcAddress(m_hDbhHelp, "SymGetOptions");
+ pSSO = (tSSO)GetProcAddress(m_hDbhHelp, "SymSetOptions");
+
+ pSFTA = (tSFTA)GetProcAddress(m_hDbhHelp, "SymFunctionTableAccess64");
+ pSGLFA = (tSGLFA)GetProcAddress(m_hDbhHelp, "SymGetLineFromAddr64");
+ pSGMB = (tSGMB)GetProcAddress(m_hDbhHelp, "SymGetModuleBase64");
+ pSGMI = (tSGMI)GetProcAddress(m_hDbhHelp, "SymGetModuleInfo64");
+ // pSGMI_V3 = (tSGMI_V3) GetProcAddress(m_hDbhHelp, "SymGetModuleInfo64");
+ pSGSFA = (tSGSFA)GetProcAddress(m_hDbhHelp, "SymGetSymFromAddr64");
+ pUDSN = (tUDSN)GetProcAddress(m_hDbhHelp, "UnDecorateSymbolName");
+ pSLM = (tSLM)GetProcAddress(m_hDbhHelp, "SymLoadModule64");
+ pSGSP = (tSGSP)GetProcAddress(m_hDbhHelp, "SymGetSearchPath");
+
+ if (
+ (pSC == nullptr) || (pSFTA == nullptr) || (pSGMB == nullptr) || (pSGMI == nullptr) ||
+ (pSGO == nullptr) || (pSGSFA == nullptr) || (pSI == nullptr) || (pSSO == nullptr) ||
+ (pSW == nullptr) || (pUDSN == nullptr) || (pSLM == nullptr)
+ )
+ {
+ FreeLibrary(m_hDbhHelp);
+ m_hDbhHelp = nullptr;
+ pSC = nullptr;
+ return FALSE;
+ }
+
+ // SymInitialize
+ if (szSymPath != nullptr)
+ {
+ m_szSymPath = _strdup(szSymPath);
+ }
+ if (this->pSI(m_hProcess, m_szSymPath, FALSE) == FALSE)
+ {
+ this->m_parent->OnDbgHelpErr("SymInitialize", GetLastError(), 0);
+ }
+
+ DWORD symOptions = this->pSGO(); // SymGetOptions
+ symOptions |= SYMOPT_LOAD_LINES;
+ symOptions |= SYMOPT_FAIL_CRITICAL_ERRORS;
+ symOptions = this->pSSO(symOptions);
+
+ char buf[WinStackWalker::STACKWALK_MAX_NAMELEN] = { 0 };
+ if (this->pSGSP != nullptr)
+ {
+ if (this->pSGSP(m_hProcess, buf, static_cast<DWORD>(sizeof(buf))) == FALSE)
+ {
+ this->m_parent->OnDbgHelpErr("SymGetSearchPath", GetLastError(), 0);
+ }
+ }
+ char szUserName[1024] = { 0 };
+ DWORD dwSize = static_cast<DWORD>(sizeof(szUserName));
+ GetUserNameA(szUserName, &dwSize);
+ this->m_parent->OnSymInit(buf, symOptions, szUserName);
+
+ return TRUE;
+ }
+
+
+
+
+
+ WinStackWalker * m_parent;
+
+ HMODULE m_hDbhHelp;
+ HANDLE m_hProcess;
+ LPSTR m_szSymPath;
+
+ #pragma pack(push, 8)
+ struct IMAGEHLP_MODULE64_V2
+ {
+ DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64)
+ DWORD64 BaseOfImage; // base load address of module
+ DWORD ImageSize; // virtual size of the loaded module
+ DWORD TimeDateStamp; // date / time stamp from pe header
+ DWORD CheckSum; // checksum from the pe header
+ DWORD NumSyms; // number of symbols in the symbol table
+ SYM_TYPE SymType; // type of symbols loaded
+ CHAR ModuleName[32]; // module name
+ CHAR ImageName[256]; // image name
+ CHAR LoadedImageName[256]; // symbol file name
+ };
+ #pragma pack(pop)
+
+
+ // SymCleanup()
+ typedef BOOL(__stdcall *tSC)(IN HANDLE hProcess);
+ tSC pSC;
+
+ // SymFunctionTableAccess64()
+ typedef PVOID(__stdcall *tSFTA)(HANDLE hProcess, DWORD64 AddrBase);
+ tSFTA pSFTA;
+
+ // SymGetLineFromAddr64()
+ typedef BOOL(__stdcall *tSGLFA)(IN HANDLE hProcess, IN DWORD64 dwAddr, OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Line);
+ tSGLFA pSGLFA;
+
+ // SymGetModuleBase64()
+ typedef DWORD64(__stdcall *tSGMB)(IN HANDLE hProcess, IN DWORD64 dwAddr);
+ tSGMB pSGMB;
+
+ // SymGetModuleInfo64()
+ typedef BOOL(__stdcall *tSGMI)(IN HANDLE hProcess, IN DWORD64 dwAddr, OUT IMAGEHLP_MODULE64_V2 *ModuleInfo);
+ tSGMI pSGMI;
+
+ // // SymGetModuleInfo64()
+ // typedef BOOL (__stdcall *tSGMI_V3)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT IMAGEHLP_MODULE64_V3 *ModuleInfo);
+ // tSGMI_V3 pSGMI_V3;
+
+ // SymGetOptions()
+ typedef DWORD(__stdcall *tSGO)(VOID);
+ tSGO pSGO;
+
+ // SymGetSymFromAddr64()
+ typedef BOOL(__stdcall *tSGSFA)(IN HANDLE hProcess, IN DWORD64 dwAddr, OUT PDWORD64 pdwDisplacement, OUT PIMAGEHLP_SYMBOL64 Symbol);
+ tSGSFA pSGSFA;
+
+ // SymInitialize()
+ typedef BOOL(__stdcall *tSI)(IN HANDLE hProcess, IN PSTR UserSearchPath, IN BOOL fInvadeProcess);
+ tSI pSI;
+
+ // SymLoadModule64()
+ typedef DWORD64(__stdcall *tSLM)(IN HANDLE hProcess, IN HANDLE hFile, IN PSTR ImageName, IN PSTR ModuleName, IN DWORD64 BaseOfDll, IN DWORD SizeOfDll);
+ tSLM pSLM;
+
+ // SymSetOptions()
+ typedef DWORD(__stdcall *tSSO)(IN DWORD SymOptions);
+ tSSO pSSO;
+
+ // StackWalk64()
+ typedef BOOL(__stdcall *tSW)(
+ DWORD MachineType,
+ HANDLE hProcess,
+ HANDLE hThread,
+ LPSTACKFRAME64 StackFrame,
+ PVOID ContextRecord,
+ PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
+ PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
+ PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
+ PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
+ tSW pSW;
+
+ // UnDecorateSymbolName()
+ typedef DWORD(__stdcall WINAPI *tUDSN)(PCSTR DecoratedName, PSTR UnDecoratedName, DWORD UndecoratedLength, DWORD Flags);
+ tUDSN pUDSN;
+
+ typedef BOOL(__stdcall WINAPI *tSGSP)(HANDLE hProcess, PSTR SearchPath, DWORD SearchPathLength);
+ tSGSP pSGSP;
+
+
+private:
+ // **************************************** ToolHelp32 ************************
+ #define MAX_MODULE_NAME32 255
+ #define TH32CS_SNAPMODULE 0x00000008
+
+ #pragma pack(push, 8)
+ typedef struct tagMODULEENTRY32
+ {
+ DWORD dwSize;
+ DWORD th32ModuleID; // This module
+ DWORD th32ProcessID; // owning process
+ DWORD GlblcntUsage; // Global usage count on the module
+ DWORD ProccntUsage; // Module usage count in th32ProcessID's context
+ BYTE * modBaseAddr; // Base address of module in th32ProcessID's context
+ DWORD modBaseSize; // Size in bytes of module starting at modBaseAddr
+ HMODULE hModule; // The hModule of this module in th32ProcessID's context
+ char szModule[MAX_MODULE_NAME32 + 1];
+ char szExePath[MAX_PATH];
+ } MODULEENTRY32;
+ typedef MODULEENTRY32 * PMODULEENTRY32;
+ typedef MODULEENTRY32 * LPMODULEENTRY32;
+ #pragma pack(pop)
+
+ BOOL GetModuleListTH32(HANDLE hProcess, DWORD pid)
+ {
+ // CreateToolhelp32Snapshot()
+ typedef HANDLE(__stdcall *tCT32S)(DWORD dwFlags, DWORD th32ProcessID);
+ // Module32First()
+ typedef BOOL(__stdcall *tM32F)(HANDLE hSnapshot, LPMODULEENTRY32 lpme);
+ // Module32Next()
+ typedef BOOL(__stdcall *tM32N)(HANDLE hSnapshot, LPMODULEENTRY32 lpme);
+
+ // try both dlls...
+ const TCHAR *dllname[] = { _T("kernel32.dll"), _T("tlhelp32.dll") };
+ HINSTANCE hToolhelp = nullptr;
+ tCT32S pCT32S = nullptr;
+ tM32F pM32F = nullptr;
+ tM32N pM32N = nullptr;
+
+ HANDLE hSnap;
+ MODULEENTRY32 me;
+ me.dwSize = sizeof(me);
+ BOOL keepGoing;
+
+ for (size_t i = 0; i < ARRAYCOUNT(dllname); i++)
+ {
+ hToolhelp = LoadLibrary(dllname[i]);
+ if (hToolhelp == nullptr)
+ {
+ continue;
+ }
+ pCT32S = (tCT32S)GetProcAddress(hToolhelp, "CreateToolhelp32Snapshot");
+ pM32F = (tM32F)GetProcAddress(hToolhelp, "Module32First");
+ pM32N = (tM32N)GetProcAddress(hToolhelp, "Module32Next");
+ if ((pCT32S != nullptr) && (pM32F != nullptr) && (pM32N != nullptr))
+ {
+ break; // found the functions!
+ }
+ FreeLibrary(hToolhelp);
+ hToolhelp = nullptr;
+ }
+
+ if (hToolhelp == nullptr)
+ {
+ return FALSE;
+ }
+
+ hSnap = pCT32S(TH32CS_SNAPMODULE, pid);
+ if (hSnap == (HANDLE)-1)
+ {
+ FreeLibrary(hToolhelp);
+ return FALSE;
+ }
+
+ keepGoing = !!pM32F(hSnap, &me);
+ int cnt = 0;
+ while (keepGoing)
+ {
+ this->LoadModule(hProcess, me.szExePath, me.szModule, (DWORD64)me.modBaseAddr, me.modBaseSize);
+ cnt++;
+ keepGoing = !!pM32N(hSnap, &me);
+ }
+ CloseHandle(hSnap);
+ FreeLibrary(hToolhelp);
+ if (cnt <= 0)
+ {
+ return FALSE;
+ }
+ return TRUE;
+ } // GetModuleListTH32
+
+
+
+
+
+ // **************************************** PSAPI ************************
+ typedef struct _MODULEINFO
+ {
+ LPVOID lpBaseOfDll;
+ DWORD SizeOfImage;
+ LPVOID EntryPoint;
+ } MODULEINFO, *LPMODULEINFO;
+
+ BOOL GetModuleListPSAPI(HANDLE hProcess)
+ {
+ // EnumProcessModules()
+ typedef BOOL(__stdcall *tEPM)(HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded);
+ // GetModuleFileNameEx()
+ typedef DWORD(__stdcall *tGMFNE)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize);
+ // GetModuleBaseName()
+ typedef DWORD(__stdcall *tGMBN)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize);
+ // GetModuleInformation()
+ typedef BOOL(__stdcall *tGMI)(HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize);
+
+ HINSTANCE hPsapi;
+ tEPM pEPM;
+ tGMFNE pGMFNE;
+ tGMBN pGMBN;
+ tGMI pGMI;
+
+ DWORD i;
+ DWORD cbNeeded;
+ MODULEINFO mi;
+ HMODULE *hMods = 0;
+ char *tt = nullptr;
+ char *tt2 = nullptr;
+ const SIZE_T TTBUFLEN = 8096;
+ int cnt = 0;
+
+ hPsapi = LoadLibrary(_T("psapi.dll"));
+ if (hPsapi == nullptr)
+ {
+ return FALSE;
+ }
+
+ pEPM = (tEPM)GetProcAddress(hPsapi, "EnumProcessModules");
+ pGMFNE = (tGMFNE)GetProcAddress(hPsapi, "GetModuleFileNameExA");
+ pGMBN = (tGMFNE)GetProcAddress(hPsapi, "GetModuleBaseNameA");
+ pGMI = (tGMI)GetProcAddress(hPsapi, "GetModuleInformation");
+ if ((pEPM == nullptr) || (pGMFNE == nullptr) || (pGMBN == nullptr) || (pGMI == nullptr))
+ {
+ // we couldnīt find all functions
+ FreeLibrary(hPsapi);
+ return FALSE;
+ }
+
+ hMods = (HMODULE*)malloc(sizeof(HMODULE) * (TTBUFLEN / sizeof HMODULE));
+ tt = (char*)malloc(sizeof(char) * TTBUFLEN);
+ tt2 = (char*)malloc(sizeof(char) * TTBUFLEN);
+ if ((hMods == nullptr) || (tt == nullptr) || (tt2 == nullptr))
+ {
+ goto cleanup;
+ }
+
+ if (!pEPM(hProcess, hMods, TTBUFLEN, &cbNeeded))
+ {
+ goto cleanup;
+ }
+
+ if (cbNeeded > TTBUFLEN)
+ {
+ goto cleanup;
+ }
+
+ for (i = 0; i < cbNeeded / sizeof hMods[0]; i++)
+ {
+ // base address, size
+ pGMI(hProcess, hMods[i], &mi, sizeof mi);
+ // image file name
+ tt[0] = 0;
+ pGMFNE(hProcess, hMods[i], tt, TTBUFLEN);
+ // module name
+ tt2[0] = 0;
+ pGMBN(hProcess, hMods[i], tt2, TTBUFLEN);
+
+ DWORD dwRes = this->LoadModule(hProcess, tt, tt2, (DWORD64)mi.lpBaseOfDll, mi.SizeOfImage);
+ if (dwRes != ERROR_SUCCESS)
+ {
+ this->m_parent->OnDbgHelpErr("LoadModule", dwRes, 0);
+ }
+ cnt++;
+ }
+
+ cleanup:
+ if (hPsapi != nullptr)
+ {
+ FreeLibrary(hPsapi);
+ }
+ if (tt2 != nullptr)
+ {
+ free(tt2);
+ }
+ if (tt != nullptr)
+ {
+ free(tt);
+ }
+ if (hMods != nullptr)
+ {
+ free(hMods);
+ }
+
+ return cnt != 0;
+ } // GetModuleListPSAPI
+
+
+
+
+
+ DWORD LoadModule(HANDLE hProcess, LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size)
+ {
+ CHAR *szImg = _strdup(img);
+ CHAR *szMod = _strdup(mod);
+ DWORD result = ERROR_SUCCESS;
+ if ((szImg == nullptr) || (szMod == nullptr))
+ {
+ result = ERROR_NOT_ENOUGH_MEMORY;
+ }
+ else
+ {
+ if (pSLM(hProcess, 0, szImg, szMod, baseAddr, size) == 0)
+ {
+ result = GetLastError();
+ }
+ }
+ ULONGLONG fileVersion = 0;
+ if ((m_parent != nullptr) && (szImg != nullptr))
+ {
+ // try to retrive the file-version:
+ if ((this->m_parent->m_options & WinStackWalker::RetrieveFileVersion) != 0)
+ {
+ VS_FIXEDFILEINFO *fInfo = nullptr;
+ DWORD dwHandle;
+ DWORD dwSize = GetFileVersionInfoSizeA(szImg, &dwHandle);
+ if (dwSize > 0)
+ {
+ LPVOID vData = malloc(dwSize);
+ if (vData != nullptr)
+ {
+ if (GetFileVersionInfoA(szImg, dwHandle, dwSize, vData) != 0)
+ {
+ UINT len;
+ TCHAR szSubBlock[] = _T("\\");
+ if (VerQueryValue(vData, szSubBlock, (LPVOID*)&fInfo, &len) == 0)
+ {
+ fInfo = nullptr;
+ }
+ else
+ {
+ fileVersion = ((ULONGLONG)fInfo->dwFileVersionLS) + ((ULONGLONG)fInfo->dwFileVersionMS << 32);
+ }
+ }
+ free(vData);
+ }
+ }
+ }
+
+ // Retrive some additional-infos about the module
+ IMAGEHLP_MODULE64_V2 Module;
+ const char *szSymType = "-unknown-";
+ if (this->GetModuleInfo(hProcess, baseAddr, &Module) != FALSE)
+ {
+ switch (Module.SymType)
+ {
+ case SymNone: szSymType = "-nosymbols-"; break;
+ case SymCoff: szSymType = "COFF"; break;
+ case SymCv: szSymType = "CV"; break;
+ case SymPdb: szSymType = "PDB"; break;
+ case SymExport: szSymType = "-exported-"; break;
+ case SymDeferred: szSymType = "-deferred-"; break;
+ case SymSym: szSymType = "SYM"; break;
+ case 7: szSymType = "DIA"; break;
+ case 8: szSymType = "Virtual"; break;
+ }
+ }
+ this->m_parent->OnLoadModule(img, mod, baseAddr, size, result, szSymType, Module.LoadedImageName, fileVersion);
+ }
+ if (szImg != nullptr)
+ {
+ free(szImg);
+ }
+ if (szMod != nullptr)
+ {
+ free(szMod);
+ }
+ return result;
+ }
+
+
+
+
+
+public:
+ BOOL LoadModules(HANDLE hProcess, DWORD dwProcessId)
+ {
+ // first try toolhelp32
+ if (GetModuleListTH32(hProcess, dwProcessId))
+ {
+ return true;
+ }
+ // then try psapi
+ return GetModuleListPSAPI(hProcess);
+ }
+
+
+ BOOL GetModuleInfo(HANDLE hProcess, DWORD64 baseAddr, IMAGEHLP_MODULE64_V2 *pModuleInfo)
+ {
+ if (this->pSGMI == nullptr)
+ {
+ SetLastError(ERROR_DLL_INIT_FAILED);
+ return FALSE;
+ }
+ pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2);
+ void * pData = malloc(4096); // reserve enough memory, so the bug in v6.3.5.1 does not lead to memory-overwrites...
+ if (pData == nullptr)
+ {
+ SetLastError(ERROR_NOT_ENOUGH_MEMORY);
+ return FALSE;
+ }
+ memcpy(pData, pModuleInfo, sizeof(IMAGEHLP_MODULE64_V2));
+ if (this->pSGMI(hProcess, baseAddr, (IMAGEHLP_MODULE64_V2*)pData) != FALSE)
+ {
+ // only copy as much memory as is reserved...
+ memcpy(pModuleInfo, pData, sizeof(IMAGEHLP_MODULE64_V2));
+ pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2);
+ free(pData);
+ return TRUE;
+ }
+ free(pData);
+ SetLastError(ERROR_DLL_INIT_FAILED);
+ return FALSE;
+ }
+};
+
+
+
+
+
+// #############################################################
+WinStackWalker::WinStackWalker(DWORD dwProcessId, HANDLE hProcess)
+{
+ this->m_options = OptionsAll;
+ this->m_modulesLoaded = FALSE;
+ this->m_hProcess = hProcess;
+ this->m_sw = new StackWalkerInternal(this, this->m_hProcess);
+ this->m_dwProcessId = dwProcessId;
+ this->m_szSymPath = nullptr;
+ this->m_MaxRecursionCount = 1000;
+}
+
+
+
+
+WinStackWalker::WinStackWalker(int options, LPCSTR szSymPath, DWORD dwProcessId, HANDLE hProcess)
+{
+ this->m_options = options;
+ this->m_modulesLoaded = FALSE;
+ this->m_hProcess = hProcess;
+ this->m_sw = new StackWalkerInternal(this, this->m_hProcess);
+ this->m_dwProcessId = dwProcessId;
+ if (szSymPath != nullptr)
+ {
+ this->m_szSymPath = _strdup(szSymPath);
+ this->m_options |= SymBuildPath;
+ }
+ else
+ {
+ this->m_szSymPath = nullptr;
+ }
+ this->m_MaxRecursionCount = 1000;
+}
+
+
+
+
+
+WinStackWalker::~WinStackWalker()
+{
+ if (m_szSymPath != nullptr)
+ {
+ free(m_szSymPath);
+ }
+ m_szSymPath = nullptr;
+ if (this->m_sw != nullptr)
+ {
+ delete this->m_sw;
+ }
+ this->m_sw = nullptr;
+}
+
+
+
+
+
+BOOL WinStackWalker::LoadModules()
+{
+ if (this->m_sw == nullptr)
+ {
+ SetLastError(ERROR_DLL_INIT_FAILED);
+ return FALSE;
+ }
+ if (m_modulesLoaded != FALSE)
+ {
+ return TRUE;
+ }
+
+ // Build the sym-path:
+ char *szSymPath = nullptr;
+ if ((this->m_options & SymBuildPath) != 0)
+ {
+ const size_t nSymPathLen = 4096;
+ szSymPath = (char*)malloc(nSymPathLen);
+ if (szSymPath == nullptr)
+ {
+ SetLastError(ERROR_NOT_ENOUGH_MEMORY);
+ return FALSE;
+ }
+ szSymPath[0] = 0;
+ // Now first add the (optional) provided sympath:
+ if (this->m_szSymPath != nullptr)
+ {
+ strcat_s(szSymPath, nSymPathLen, this->m_szSymPath);
+ strcat_s(szSymPath, nSymPathLen, ";");
+ }
+
+ strcat_s(szSymPath, nSymPathLen, ".;");
+
+ const DWORD nTempLen = 1024;
+ char szTemp[nTempLen];
+ // Now add the current directory:
+ if (GetCurrentDirectoryA(nTempLen, szTemp) > 0)
+ {
+ szTemp[nTempLen - 1] = 0;
+ strcat_s(szSymPath, nSymPathLen, szTemp);
+ strcat_s(szSymPath, nSymPathLen, ";");
+ }
+
+ // Now add the path for the main-module:
+ if (GetModuleFileNameA(nullptr, szTemp, nTempLen) > 0)
+ {
+ szTemp[nTempLen - 1] = 0;
+ for (char *p = (szTemp + strlen(szTemp) - 1); p >= szTemp; --p)
+ {
+ // locate the rightmost path separator
+ if ((*p == '\\') || (*p == '/') || (*p == ':'))
+ {
+ *p = 0;
+ break;
+ }
+ } // for (search for path separator...)
+
+ if (szTemp[0] != '\0')
+ {
+ strcat_s(szSymPath, nSymPathLen, szTemp);
+ strcat_s(szSymPath, nSymPathLen, ";");
+ }
+ }
+ if (GetEnvironmentVariableA("_NT_SYMBOL_PATH", szTemp, nTempLen) > 0)
+ {
+ szTemp[nTempLen - 1] = 0;
+ strcat_s(szSymPath, nSymPathLen, szTemp);
+ strcat_s(szSymPath, nSymPathLen, ";");
+ }
+ if (GetEnvironmentVariableA("_NT_ALTERNATE_SYMBOL_PATH", szTemp, nTempLen) > 0)
+ {
+ szTemp[nTempLen - 1] = 0;
+ strcat_s(szSymPath, nSymPathLen, szTemp);
+ strcat_s(szSymPath, nSymPathLen, ";");
+ }
+ if (GetEnvironmentVariableA("SYSTEMROOT", szTemp, nTempLen) > 0)
+ {
+ szTemp[nTempLen - 1] = 0;
+ strcat_s(szSymPath, nSymPathLen, szTemp);
+ strcat_s(szSymPath, nSymPathLen, ";");
+ // also add the "system32"-directory:
+ strcat_s(szTemp, nTempLen, "\\system32");
+ strcat_s(szSymPath, nSymPathLen, szTemp);
+ strcat_s(szSymPath, nSymPathLen, ";");
+ }
+
+ if ((this->m_options & SymUseSymSrv) != 0)
+ {
+ if (GetEnvironmentVariableA("SYSTEMDRIVE", szTemp, nTempLen) > 0)
+ {
+ szTemp[nTempLen - 1] = 0;
+ strcat_s(szSymPath, nSymPathLen, "SRV*");
+ strcat_s(szSymPath, nSymPathLen, szTemp);
+ strcat_s(szSymPath, nSymPathLen, "\\websymbols");
+ strcat_s(szSymPath, nSymPathLen, "*http://msdl.microsoft.com/download/symbols;");
+ }
+ else
+ {
+ strcat_s(szSymPath, nSymPathLen, "SRV*c:\\websymbols*http://msdl.microsoft.com/download/symbols;");
+ }
+ }
+ } // if SymBuildPath
+
+ // First Init the whole stuff...
+ BOOL bRet = this->m_sw->Init(szSymPath);
+ if (szSymPath != nullptr)
+ {
+ free(szSymPath);
+ szSymPath = nullptr;
+ }
+ if (bRet == FALSE)
+ {
+ this->OnDbgHelpErr("Error while initializing dbghelp.dll", 0, 0);
+ SetLastError(ERROR_DLL_INIT_FAILED);
+ return FALSE;
+ }
+
+ bRet = this->m_sw->LoadModules(this->m_hProcess, this->m_dwProcessId);
+ if (bRet != FALSE)
+ {
+ m_modulesLoaded = TRUE;
+ }
+ return bRet;
+}
+
+
+
+
+
+// The following is used to pass the "userData"-Pointer to the user-provided readMemoryFunction
+// This has to be done due to a problem with the "hProcess"-parameter in x64
+// Because this class is in no case multi-threading-enabled (because of the limitations
+// of dbghelp.dll) it is "safe" to use a static-variable
+static WinStackWalker::PReadProcessMemoryRoutine s_readMemoryFunction = nullptr;
+static LPVOID s_readMemoryFunction_UserData = nullptr;
+
+BOOL WinStackWalker::ShowCallstack(HANDLE hThread, const CONTEXT *context, PReadProcessMemoryRoutine readMemoryFunction, LPVOID pUserData)
+{
+ CONTEXT c;
+ CallstackEntry csEntry;
+ IMAGEHLP_SYMBOL64 *pSym = nullptr;
+ StackWalkerInternal::IMAGEHLP_MODULE64_V2 Module;
+ IMAGEHLP_LINE64 Line;
+ int frameNum;
+ bool bLastEntryCalled = true;
+ int curRecursionCount = 0;
+
+ if (!m_modulesLoaded)
+ {
+ this->LoadModules(); // ignore the result...
+ }
+
+ if (this->m_sw->m_hDbhHelp == nullptr)
+ {
+ SetLastError(ERROR_DLL_INIT_FAILED);
+ return FALSE;
+ }
+
+ s_readMemoryFunction = readMemoryFunction;
+ s_readMemoryFunction_UserData = pUserData;
+
+ if (context == nullptr)
+ {
+ // If no context is provided, capture the context
+ if (hThread == GetCurrentThread())
+ {
+ GET_CURRENT_CONTEXT(c, USED_CONTEXT_FLAGS);
+ }
+ else
+ {
+ SuspendThread(hThread);
+ memset(&c, 0, sizeof(CONTEXT));
+ c.ContextFlags = USED_CONTEXT_FLAGS;
+ if (GetThreadContext(hThread, &c) == FALSE)
+ {
+ ResumeThread(hThread);
+ return FALSE;
+ }
+ }
+ }
+ else
+ {
+ c = *context;
+ }
+
+ // init STACKFRAME for first call
+ STACKFRAME64 s; // in / out stackframe
+ memset(&s, 0, sizeof(s));
+ DWORD imageType;
+ #ifdef _M_IX86
+ // normally, call ImageNtHeader() and use machine info from PE header
+ imageType = IMAGE_FILE_MACHINE_I386;
+ s.AddrPC.Offset = c.Eip;
+ s.AddrPC.Mode = AddrModeFlat;
+ s.AddrFrame.Offset = c.Ebp;
+ s.AddrFrame.Mode = AddrModeFlat;
+ s.AddrStack.Offset = c.Esp;
+ s.AddrStack.Mode = AddrModeFlat;
+ #elif _M_X64
+ imageType = IMAGE_FILE_MACHINE_AMD64;
+ s.AddrPC.Offset = c.Rip;
+ s.AddrPC.Mode = AddrModeFlat;
+ s.AddrFrame.Offset = c.Rsp;
+ s.AddrFrame.Mode = AddrModeFlat;
+ s.AddrStack.Offset = c.Rsp;
+ s.AddrStack.Mode = AddrModeFlat;
+ #elif _M_IA64
+ imageType = IMAGE_FILE_MACHINE_IA64;
+ s.AddrPC.Offset = c.StIIP;
+ s.AddrPC.Mode = AddrModeFlat;
+ s.AddrFrame.Offset = c.IntSp;
+ s.AddrFrame.Mode = AddrModeFlat;
+ s.AddrBStore.Offset = c.RsBSP;
+ s.AddrBStore.Mode = AddrModeFlat;
+ s.AddrStack.Offset = c.IntSp;
+ s.AddrStack.Mode = AddrModeFlat;
+ #else
+ #error "Platform not supported!"
+ #endif
+
+ pSym = (IMAGEHLP_SYMBOL64 *)malloc(sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN);
+ if (!pSym)
+ {
+ goto cleanup; // not enough memory...
+ }
+ memset(pSym, 0, sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN);
+ pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
+ pSym->MaxNameLength = STACKWALK_MAX_NAMELEN;
+
+ memset(&Line, 0, sizeof(Line));
+ Line.SizeOfStruct = sizeof(Line);
+
+ memset(&Module, 0, sizeof(Module));
+ Module.SizeOfStruct = sizeof(Module);
+
+ for (frameNum = 0; ; ++frameNum)
+ {
+ // get next stack frame (StackWalk64(), SymFunctionTableAccess64(), SymGetModuleBase64())
+ // if this returns ERROR_INVALID_ADDRESS (487) or ERROR_NOACCESS (998), you can
+ // assume that either you are done, or that the stack is so hosed that the next
+ // deeper frame could not be found.
+ // CONTEXT need not to be suplied if imageTyp is IMAGE_FILE_MACHINE_I386!
+ if (!this->m_sw->pSW(imageType, this->m_hProcess, hThread, &s, &c, myReadProcMem, this->m_sw->pSFTA, this->m_sw->pSGMB, nullptr))
+ {
+ // INFO: "StackWalk64" does not set "GetLastError"...
+ this->OnDbgHelpErr("StackWalk64", 0, s.AddrPC.Offset);
+ break;
+ }
+
+ csEntry.offset = s.AddrPC.Offset;
+ csEntry.name[0] = 0;
+ csEntry.undName[0] = 0;
+ csEntry.undFullName[0] = 0;
+ csEntry.offsetFromSmybol = 0;
+ csEntry.offsetFromLine = 0;
+ csEntry.lineFileName[0] = 0;
+ csEntry.lineNumber = 0;
+ csEntry.loadedImageName[0] = 0;
+ csEntry.moduleName[0] = 0;
+ if (s.AddrPC.Offset == s.AddrReturn.Offset)
+ {
+ if ((this->m_MaxRecursionCount > 0) && (curRecursionCount > m_MaxRecursionCount))
+ {
+ this->OnDbgHelpErr("StackWalk64-Endless-Callstack!", 0, s.AddrPC.Offset);
+ break;
+ }
+ curRecursionCount++;
+ }
+ else
+ {
+ curRecursionCount = 0;
+ }
+ if (s.AddrPC.Offset != 0)
+ {
+ // we seem to have a valid PC
+ // show procedure info (SymGetSymFromAddr64())
+ if (this->m_sw->pSGSFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromSmybol), pSym) != FALSE)
+ {
+ MyStrCpy(csEntry.name, pSym->Name);
+ // UnDecorateSymbolName()
+ this->m_sw->pUDSN(pSym->Name, csEntry.undName, static_cast<DWORD>(sizeof(csEntry.undName)), UNDNAME_NAME_ONLY);
+ this->m_sw->pUDSN(pSym->Name, csEntry.undFullName, static_cast<DWORD>(sizeof(csEntry.undFullName)), UNDNAME_COMPLETE);
+ }
+ else
+ {
+ this->OnDbgHelpErr("SymGetSymFromAddr64", GetLastError(), s.AddrPC.Offset);
+ }
+
+ // show line number info, NT5.0-method (SymGetLineFromAddr64())
+ if (this->m_sw->pSGLFA != nullptr)
+ {
+ if (this->m_sw->pSGLFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromLine), &Line) != FALSE)
+ {
+ csEntry.lineNumber = Line.LineNumber;
+ MyStrCpy(csEntry.lineFileName, Line.FileName);
+ }
+ else
+ {
+ this->OnDbgHelpErr("SymGetLineFromAddr64", GetLastError(), s.AddrPC.Offset);
+ }
+ }
+
+ // show module info (SymGetModuleInfo64())
+ if (this->m_sw->GetModuleInfo(this->m_hProcess, s.AddrPC.Offset, &Module) != FALSE)
+ {
+ switch (Module.SymType)
+ {
+ case SymNone: csEntry.symTypeString = "-nosymbols-"; break;
+ case SymCoff: csEntry.symTypeString = "COFF"; break;
+ case SymCv: csEntry.symTypeString = "CV"; break;
+ case SymPdb: csEntry.symTypeString = "PDB"; break;
+ case SymExport: csEntry.symTypeString = "-exported-"; break;
+ case SymDeferred: csEntry.symTypeString = "-deferred-"; break;
+ case SymSym: csEntry.symTypeString = "SYM"; break;
+ case SymDia: csEntry.symTypeString = "DIA"; break;
+ case 8: csEntry.symTypeString = "Virtual"; break;
+ default: csEntry.symTypeString = nullptr; break;
+ }
+
+ MyStrCpy(csEntry.moduleName, Module.ModuleName);
+ csEntry.baseOfImage = Module.BaseOfImage;
+ MyStrCpy(csEntry.loadedImageName, Module.LoadedImageName);
+ }
+ else
+ {
+ this->OnDbgHelpErr("SymGetModuleInfo64", GetLastError(), s.AddrPC.Offset);
+ }
+ }
+
+ CallstackEntryType et = nextEntry;
+ if (frameNum == 0)
+ {
+ et = firstEntry;
+ }
+ bLastEntryCalled = false;
+ this->OnCallstackEntry(et, csEntry);
+
+ if (s.AddrReturn.Offset == 0)
+ {
+ bLastEntryCalled = true;
+ this->OnCallstackEntry(lastEntry, csEntry);
+ SetLastError(ERROR_SUCCESS);
+ break;
+ }
+ } // for (frameNum)
+
+cleanup:
+ if (pSym)
+ {
+ free(pSym);
+ }
+
+ if (bLastEntryCalled == false)
+ {
+ this->OnCallstackEntry(lastEntry, csEntry);
+ }
+
+ if (context == nullptr)
+ {
+ ResumeThread(hThread);
+ }
+
+ return TRUE;
+}
+
+
+
+
+
+BOOL __stdcall WinStackWalker::myReadProcMem(
+ HANDLE hProcess,
+ DWORD64 qwBaseAddress,
+ PVOID lpBuffer,
+ DWORD nSize,
+ LPDWORD lpNumberOfBytesRead
+)
+{
+ if (s_readMemoryFunction == nullptr)
+ {
+ SIZE_T st;
+ BOOL bRet = ReadProcessMemory(hProcess, (LPVOID)qwBaseAddress, lpBuffer, nSize, &st);
+ *lpNumberOfBytesRead = (DWORD)st;
+ // printf("ReadMemory: hProcess: %p, baseAddr: %p, buffer: %p, size: %d, read: %d, result: %d\n", hProcess, (LPVOID) qwBaseAddress, lpBuffer, nSize, (DWORD) st, (DWORD) bRet);
+ return bRet;
+ }
+ else
+ {
+ return s_readMemoryFunction(hProcess, qwBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead, s_readMemoryFunction_UserData);
+ }
+}
+
+
+
+
+
+void WinStackWalker::OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
+{
+ char buffer[STACKWALK_MAX_NAMELEN];
+ if (fileVersion == 0)
+ {
+ _snprintf_s(buffer, sizeof(buffer), "%s:%s (%p), size: %d (result: %d), SymType: '%s', PDB: '%s'\n", img, mod, (LPVOID)baseAddr, size, result, symType, pdbName);
+ }
+ else
+ {
+ DWORD v4 = (DWORD)fileVersion & 0xFFFF;
+ DWORD v3 = (DWORD)(fileVersion >> 16) & 0xFFFF;
+ DWORD v2 = (DWORD)(fileVersion >> 32) & 0xFFFF;
+ DWORD v1 = (DWORD)(fileVersion >> 48) & 0xFFFF;
+ _snprintf_s(buffer, sizeof(buffer), "%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);
+ }
+ OnOutput(buffer);
+}
+
+
+
+
+
+void WinStackWalker::OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry)
+{
+ CHAR buffer[STACKWALK_MAX_NAMELEN + MAX_PATH + 100];
+ if ((eType == lastEntry) || (entry.offset == 0))
+ {
+ return;
+ }
+ if (entry.undFullName[0] != 0)
+ {
+ MyStrCpy(entry.name, entry.undFullName);
+ }
+ else if (entry.undName[0] != 0)
+ {
+ MyStrCpy(entry.name, entry.undName);
+ }
+ else if (entry.name[0] == 0)
+ {
+ MyStrCpy(entry.name, "(function-name not available)");
+ }
+ if (entry.lineFileName[0] == 0)
+ {
+ MyStrCpy(entry.lineFileName, "(filename not available)");
+ if (entry.moduleName[0] == 0)
+ {
+ MyStrCpy(entry.moduleName, "(module-name not available)");
+ }
+ _snprintf_s(buffer, sizeof(buffer), "%p (%s): %s: %s\n", (LPVOID)entry.offset, entry.moduleName, entry.lineFileName, entry.name);
+ }
+ else
+ {
+ _snprintf_s(buffer, sizeof(buffer), "%s (%d): %s\n", entry.lineFileName, entry.lineNumber, entry.name);
+ }
+ OnOutput(buffer);
+}
+
+
+
+
+
+void WinStackWalker::OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr)
+{
+ CHAR buffer[STACKWALK_MAX_NAMELEN];
+ _snprintf_s(buffer, sizeof(buffer), "ERROR: %s, GetLastError: %d (Address: %p)\n", szFuncName, gle, (LPVOID)addr);
+ OnOutput(buffer);
+}
+
+
+
+
+
+void WinStackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName)
+{
+ CHAR buffer[STACKWALK_MAX_NAMELEN];
+ _snprintf_s(buffer, sizeof(buffer), "SymInit: Symbol-SearchPath: '%s', symOptions: %d, UserName: '%s'\n", szSearchPath, symOptions, szUserName);
+ OnOutput(buffer);
+ // Also display the OS-version
+ OSVERSIONINFOEXA ver;
+ ZeroMemory(&ver, sizeof(OSVERSIONINFOEXA));
+ ver.dwOSVersionInfoSize = sizeof(ver);
+ if (GetVersionExA((OSVERSIONINFOA*)&ver) != FALSE)
+ {
+ _snprintf_s(buffer, sizeof(buffer), "OS-Version: %d.%d.%d (%s) 0x%x-0x%x\n",
+ ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber,
+ ver.szCSDVersion, ver.wSuiteMask, ver.wProductType
+ );
+ OnOutput(buffer);
+ }
+}
+
+
+
+
+
+void WinStackWalker::OnOutput(LPCSTR buffer)
+{
+ OutputDebugStringA(buffer);
+}
+
+
+
+
+#endif // _WIN32
diff --git a/src/OSSupport/WinStackWalker.h b/src/OSSupport/WinStackWalker.h
new file mode 100644
index 000000000..9dfd08e00
--- /dev/null
+++ b/src/OSSupport/WinStackWalker.h
@@ -0,0 +1,173 @@
+// WinStackWalker.h
+
+// Declares the stack walking for Windows binaries
+
+/*
+LICENSE (http://www.opensource.org/licenses/bsd-license.php)
+
+Copyright (c) 2005-2010, Jochen Kalmbach
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
+and / or other materials provided with the distribution.
+Neither the name of Jochen Kalmbach nor the names of its contributors may be
+used to endorse or promote products derived from this software without
+specific prior written permission.
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#pragma once
+
+
+
+
+
+#ifdef _WIN32 // This is Windows-only code
+
+
+
+
+
+class StackWalkerInternal; // forward
+class WinStackWalker
+{
+public:
+ enum StackWalkOptions
+ {
+ // No addition info will be retrived
+ // (only the address is available)
+ RetrieveNone = 0,
+
+ // Try to get the symbol-name
+ RetrieveSymbol = 1,
+
+ // Try to get the line for this symbol
+ RetrieveLine = 2,
+
+ // Try to retrieve the module-infos
+ RetrieveModuleInfo = 4,
+
+ // Also retrieve the version for the DLL / EXE
+ RetrieveFileVersion = 8,
+
+ // Contains all the abouve
+ RetrieveVerbose = 0xF,
+
+ // Generate a "good" symbol-search-path
+ SymBuildPath = 0x10,
+
+ // Also use the public Microsoft-Symbol-Server
+ SymUseSymSrv = 0x20,
+
+ // Contains all the abouve "Sym"-options
+ SymAll = 0x30,
+
+ // Contains all options (default)
+ OptionsAll = 0x3F
+ };
+
+ WinStackWalker(
+ int options = OptionsAll,
+ LPCSTR szSymPath = nullptr,
+ DWORD dwProcessId = GetCurrentProcessId(),
+ HANDLE hProcess = GetCurrentProcess()
+ );
+
+ WinStackWalker(DWORD dwProcessId, HANDLE hProcess);
+ virtual ~WinStackWalker();
+
+ typedef BOOL(__stdcall *PReadProcessMemoryRoutine)(
+ HANDLE hProcess,
+ DWORD64 qwBaseAddress,
+ PVOID lpBuffer,
+ DWORD nSize,
+ LPDWORD lpNumberOfBytesRead,
+ LPVOID pUserData // optional data, which was passed in "ShowCallstack"
+ );
+
+ BOOL LoadModules();
+
+ BOOL ShowCallstack(
+ HANDLE hThread = GetCurrentThread(),
+ const CONTEXT *context = nullptr,
+ PReadProcessMemoryRoutine readMemoryFunction = nullptr,
+ LPVOID pUserData = nullptr // optional to identify some data in the 'readMemoryFunction'-callback
+ );
+
+protected:
+ enum
+ {
+ STACKWALK_MAX_NAMELEN = 1024, ///< Max name length for found symbols
+ };
+
+protected:
+ // Entry for each Callstack-Entry
+ struct CallstackEntry
+ {
+ DWORD64 offset; // if 0, we have no valid entry
+ CHAR name[STACKWALK_MAX_NAMELEN];
+ CHAR undName[STACKWALK_MAX_NAMELEN];
+ CHAR undFullName[STACKWALK_MAX_NAMELEN];
+ DWORD64 offsetFromSmybol;
+ DWORD offsetFromLine;
+ DWORD lineNumber;
+ CHAR lineFileName[STACKWALK_MAX_NAMELEN];
+ DWORD symType;
+ LPCSTR symTypeString;
+ CHAR moduleName[STACKWALK_MAX_NAMELEN];
+ DWORD64 baseOfImage;
+ CHAR loadedImageName[STACKWALK_MAX_NAMELEN];
+ };
+
+ enum CallstackEntryType { firstEntry, nextEntry, lastEntry };
+
+ virtual void OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName);
+ virtual void OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion);
+ virtual void OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry);
+ virtual void OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr);
+ virtual void OnOutput(LPCSTR szText);
+
+ StackWalkerInternal *m_sw;
+ HANDLE m_hProcess;
+ DWORD m_dwProcessId;
+ BOOL m_modulesLoaded;
+ LPSTR m_szSymPath;
+
+ int m_options;
+ int m_MaxRecursionCount;
+
+ static BOOL __stdcall myReadProcMem(HANDLE hProcess, DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize, LPDWORD lpNumberOfBytesRead);
+
+ friend StackWalkerInternal;
+};
+
+
+
+
+#define GET_CURRENT_CONTEXT(c, contextFlags) \
+ do \
+ { \
+ memset(&c, 0, sizeof(CONTEXT)); \
+ c.ContextFlags = contextFlags; \
+ RtlCaptureContext(&c); \
+ } while (false);
+
+
+
+
+#endif // _WIN32
diff --git a/src/Server.cpp b/src/Server.cpp
index 6d56a5890..fd707e61a 100644
--- a/src/Server.cpp
+++ b/src/Server.cpp
@@ -34,22 +34,6 @@ extern "C"
-/** Enable the memory leak finder - needed for the "dumpmem" server command:
-Synchronize this with main.cpp - the leak finder needs initialization before it can be used to dump memory
-_X 2014_02_20: Disabled for canon repo, it makes the debug version too slow in MSVC2013
-and we haven't had a memory leak for over a year anyway. */
-// #define ENABLE_LEAK_FINDER
-
-#if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER)
- #pragma warning(push)
- #pragma warning(disable:4100)
- #include "LeakFinder.h"
- #pragma warning(pop)
-#endif
-
-
-
-
typedef std::list< cClientHandle* > ClientList;
@@ -535,23 +519,6 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac
a_Output.Finished();
return;
}
- #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER)
- else if (split[0].compare("dumpmem") == 0)
- {
- LeakFinderXmlOutput Output("memdump.xml");
- DumpUsedMemory(&Output);
- return;
- }
-
- else if (split[0].compare("killmem") == 0)
- {
- for (;;)
- {
- new char[100 * 1024 * 1024]; // Allocate and leak 100 MiB in a loop -> fill memory and kill MCS
- }
- }
- #endif
-
else if (cPluginManager::Get()->ExecuteConsoleCommand(split, a_Output, a_Cmd))
{
a_Output.Finished();
@@ -637,10 +604,6 @@ void cServer::BindBuiltInConsoleCommands(void)
PlgMgr->BindConsoleCommand("load", nullptr, handler, "Adds and enables the specified plugin");
PlgMgr->BindConsoleCommand("unload", nullptr, handler, "Disables the specified plugin");
PlgMgr->BindConsoleCommand("destroyentities", nullptr, handler, "Destroys all entities in all worlds");
-
- #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER)
- PlgMgr->BindConsoleCommand("dumpmem", nullptr, handler, " - Dumps all used memory blocks together with their callstacks into memdump.xml");
- #endif
}
diff --git a/src/StackWalker.cpp b/src/StackWalker.cpp
deleted file mode 100644
index c2d9dbbe1..000000000
--- a/src/StackWalker.cpp
+++ /dev/null
@@ -1,1347 +0,0 @@
-/**********************************************************************
- *
- * StackWalker.cpp
- *
- *
- * History:
- * 2005-07-27 v1 - First public release on http://www.codeproject.com/
- * http://www.codeproject.com/threads/StackWalker.asp
- * 2005-07-28 v2 - Changed the params of the constructor and ShowCallstack
- * (to simplify the usage)
- * 2005-08-01 v3 - Changed to use 'CONTEXT_FULL' instead of CONTEXT_ALL
- * (should also be enough)
- * - Changed to compile correctly with the PSDK of VC7.0
- * (GetFileVersionInfoSizeA and GetFileVersionInfoA is wrongly defined:
- * it uses LPSTR instead of LPCSTR as first paremeter)
- * - Added declarations to support VC5/6 without using 'dbghelp.h'
- * - Added a 'pUserData' member to the ShowCallstack function and the
- * PReadProcessMemoryRoutine declaration (to pass some user-defined data,
- * which can be used in the readMemoryFunction-callback)
- * 2005-08-02 v4 - OnSymInit now also outputs the OS-Version by default
- * - Added example for doing an exception-callstack-walking in main.cpp
- * (thanks to owillebo: http://www.codeproject.com/script/profile/whos_who.asp?id=536268)
- * 2005-08-05 v5 - Removed most Lint (http://www.gimpel.com/) errors... thanks to Okko Willeboordse!
- * 2008-08-04 v6 - Fixed Bug: Missing LEAK-end-tag
- * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=2502890#xx2502890xx
- * Fixed Bug: Compiled with "WIN32_LEAN_AND_MEAN"
- * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=1824718#xx1824718xx
- * Fixed Bug: Compiling with "/Wall"
- * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=2638243#xx2638243xx
- * Fixed Bug: Now checking SymUseSymSrv
- * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=1388979#xx1388979xx
- * Fixed Bug: Support for recursive function calls
- * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=1434538#xx1434538xx
- * Fixed Bug: Missing FreeLibrary call in "GetModuleListTH32"
- * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=1326923#xx1326923xx
- * Fixed Bug: SymDia is number 7, not 9!
- * 2008-09-11 v7 For some (undocumented) reason, dbhelp.h is needing a packing of 8!
- * Thanks to Teajay which reported the bug...
- * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=2718933#xx2718933xx
- * 2008-11-27 v8 Debugging Tools for Windows are now stored in a different directory
- * Thanks to Luiz Salamon which reported this "bug"...
- * http://www.codeproject.com/KB/threads/StackWalker.aspx?msg=2822736#xx2822736xx
- * 2009-04-10 v9 License slihtly corrected (<ORGANIZATION> replaced)
- * 2010-04-15 v10 Added support for VS2010 RTM
- * 2010-05-2ß v11 Now using secure MyStrcCpy. Thanks to luke.simon:
- * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=3477467#xx3477467xx
- *
- * LICENSE (http://www.opensource.org/licenses/bsd-license.php)
- *
- * Copyright (c) 2005-2010, Jochen Kalmbach
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * Neither the name of Jochen Kalmbach nor the names of its contributors may be
- * used to endorse or promote products derived from this software without
- * specific prior written permission.
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- **********************************************************************/
-
-#include "Globals.h"
-
-#include <tchar.h>
-#pragma comment(lib, "version.lib") // for "VerQueryValue"
-#pragma warning(disable:4826)
-#pragma warning(disable:4996) // "GetVersionEx" was declared deprecated
-
-#include "StackWalker.h"
-
-
-// If VC7 and later, then use the shipped 'dbghelp.h'-file
-#pragma pack(push,8)
-#if _MSC_VER >= 1300
-#include <dbghelp.h>
-#else
-// inline the important dbghelp.h-declarations...
-typedef enum {
- SymNone = 0,
- SymCoff,
- SymCv,
- SymPdb,
- SymExport,
- SymDeferred,
- SymSym,
- SymDia,
- SymVirtual,
- NumSymTypes
-} SYM_TYPE;
-typedef struct _IMAGEHLP_LINE64 {
- DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_LINE64)
- PVOID Key; // internal
- DWORD LineNumber; // line number in file
- PCHAR FileName; // full filename
- DWORD64 Address; // first instruction of line
-} IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
-typedef struct _IMAGEHLP_MODULE64 {
- DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64)
- DWORD64 BaseOfImage; // base load address of module
- DWORD ImageSize; // virtual size of the loaded module
- DWORD TimeDateStamp; // date/time stamp from pe header
- DWORD CheckSum; // checksum from the pe header
- DWORD NumSyms; // number of symbols in the symbol table
- SYM_TYPE SymType; // type of symbols loaded
- CHAR ModuleName[32]; // module name
- CHAR ImageName[256]; // image name
- CHAR LoadedImageName[256]; // symbol file name
-} IMAGEHLP_MODULE64, *PIMAGEHLP_MODULE64;
-typedef struct _IMAGEHLP_SYMBOL64 {
- DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_SYMBOL64)
- DWORD64 Address; // virtual address including dll base address
- DWORD Size; // estimated size of symbol, can be zero
- DWORD Flags; // info about the symbols, see the SYMF defines
- DWORD MaxNameLength; // maximum size of symbol name in 'Name'
- CHAR Name[1]; // symbol name (null terminated string)
-} IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
-typedef enum {
- AddrMode1616,
- AddrMode1632,
- AddrModeReal,
- AddrModeFlat
-} ADDRESS_MODE;
-typedef struct _tagADDRESS64 {
- DWORD64 Offset;
- WORD Segment;
- ADDRESS_MODE Mode;
-} ADDRESS64, *LPADDRESS64;
-typedef struct _KDHELP64 {
- DWORD64 Thread;
- DWORD ThCallbackStack;
- DWORD ThCallbackBStore;
- DWORD NextCallback;
- DWORD FramePointer;
- DWORD64 KiCallUserMode;
- DWORD64 KeUserCallbackDispatcher;
- DWORD64 SystemRangeStart;
- DWORD64 Reserved[8];
-} KDHELP64, *PKDHELP64;
-typedef struct _tagSTACKFRAME64 {
- ADDRESS64 AddrPC; // program counter
- ADDRESS64 AddrReturn; // return address
- ADDRESS64 AddrFrame; // frame pointer
- ADDRESS64 AddrStack; // stack pointer
- ADDRESS64 AddrBStore; // backing store pointer
- PVOID FuncTableEntry; // pointer to pdata/fpo or NULL
- DWORD64 Params[4]; // possible arguments to the function
- BOOL Far; // WOW far call
- BOOL Virtual; // is this a virtual frame?
- DWORD64 Reserved[3];
- KDHELP64 KdHelp;
-} STACKFRAME64, *LPSTACKFRAME64;
-typedef
-BOOL
-(__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(
- HANDLE hProcess,
- DWORD64 qwBaseAddress,
- PVOID lpBuffer,
- DWORD nSize,
- LPDWORD lpNumberOfBytesRead
- );
-typedef
-PVOID
-(__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)(
- HANDLE hProcess,
- DWORD64 AddrBase
- );
-typedef
-DWORD64
-(__stdcall *PGET_MODULE_BASE_ROUTINE64)(
- HANDLE hProcess,
- DWORD64 Address
- );
-typedef
-DWORD64
-(__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(
- HANDLE hProcess,
- HANDLE hThread,
- LPADDRESS64 lpaddr
- );
-#define SYMOPT_CASE_INSENSITIVE 0x00000001
-#define SYMOPT_UNDNAME 0x00000002
-#define SYMOPT_DEFERRED_LOADS 0x00000004
-#define SYMOPT_NO_CPP 0x00000008
-#define SYMOPT_LOAD_LINES 0x00000010
-#define SYMOPT_OMAP_FIND_NEAREST 0x00000020
-#define SYMOPT_LOAD_ANYTHING 0x00000040
-#define SYMOPT_IGNORE_CVREC 0x00000080
-#define SYMOPT_NO_UNQUALIFIED_LOADS 0x00000100
-#define SYMOPT_FAIL_CRITICAL_ERRORS 0x00000200
-#define SYMOPT_EXACT_SYMBOLS 0x00000400
-#define SYMOPT_ALLOW_ABSOLUTE_SYMBOLS 0x00000800
-#define SYMOPT_IGNORE_NT_SYMPATH 0x00001000
-#define SYMOPT_INCLUDE_32BIT_MODULES 0x00002000
-#define SYMOPT_PUBLICS_ONLY 0x00004000
-#define SYMOPT_NO_PUBLICS 0x00008000
-#define SYMOPT_AUTO_PUBLICS 0x00010000
-#define SYMOPT_NO_IMAGE_SEARCH 0x00020000
-#define SYMOPT_SECURE 0x00040000
-#define SYMOPT_DEBUG 0x80000000
-#define UNDNAME_COMPLETE (0x0000) // Enable full undecoration
-#define UNDNAME_NAME_ONLY (0x1000) // Crack only the name for primary declaration;
-#endif // _MSC_VER < 1300
-#pragma pack(pop)
-
-// Some missing defines (for VC5/6):
-#ifndef INVALID_FILE_ATTRIBUTES
-#define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
-#endif
-
-
-// secure-CRT_functions are only available starting with VC8
-#if _MSC_VER < 1400
-#define strcpy_s strcpy
-#define strncpy_s strncpy
-#define strcat_s(dst, len, src) strcat(dst, src)
-#define _snprintf_s _snprintf
-#define _tcscat_s _tcscat
-#endif
-
-static void MyStrCpy(char* szDest, size_t nMaxDestSize, const char* szSrc)
-{
- if (nMaxDestSize <= 0) return;
- if (strlen(szSrc) < nMaxDestSize)
- {
- strcpy_s(szDest, nMaxDestSize, szSrc);
- }
- else
- {
- strncpy_s(szDest, nMaxDestSize, szSrc, nMaxDestSize);
- szDest[nMaxDestSize-1] = 0;
- }
-} // MyStrCpy
-
-// Normally it should be enough to use 'CONTEXT_FULL' (better would be 'CONTEXT_ALL')
-#define USED_CONTEXT_FLAGS CONTEXT_FULL
-
-
-class StackWalkerInternal
-{
-public:
- StackWalkerInternal(StackWalker *parent, HANDLE hProcess)
- {
- m_parent = parent;
- m_hDbhHelp = NULL;
- pSC = NULL;
- m_hProcess = hProcess;
- m_szSymPath = NULL;
- pSFTA = NULL;
- pSGLFA = NULL;
- pSGMB = NULL;
- pSGMI = NULL;
- pSGO = NULL;
- pSGSFA = NULL;
- pSI = NULL;
- pSLM = NULL;
- pSSO = NULL;
- pSW = NULL;
- pUDSN = NULL;
- pSGSP = NULL;
- }
- ~StackWalkerInternal()
- {
- if (pSC != NULL)
- pSC(m_hProcess); // SymCleanup
- if (m_hDbhHelp != NULL)
- FreeLibrary(m_hDbhHelp);
- m_hDbhHelp = NULL;
- m_parent = NULL;
- if(m_szSymPath != NULL)
- free(m_szSymPath);
- m_szSymPath = NULL;
- }
- BOOL Init(LPCSTR szSymPath)
- {
- if (m_parent == NULL)
- return FALSE;
- // Dynamically load the Entry-Points for dbghelp.dll:
- // First try to load the newsest one from
- TCHAR szTemp[4096];
- // But before wqe do this, we first check if the ".local" file exists
- if (GetModuleFileName(NULL, szTemp, 4096) > 0)
- {
- _tcscat_s(szTemp, _T(".local"));
- if (GetFileAttributes(szTemp) == INVALID_FILE_ATTRIBUTES)
- {
- // ".local" file does not exist, so we can try to load the dbghelp.dll from the "Debugging Tools for Windows"
- // Ok, first try the new path according to the archtitecture:
-#ifdef _M_IX86
- if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
- {
- _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (x86)\\dbghelp.dll"));
- // now check if the file exists:
- if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
- {
- m_hDbhHelp = LoadLibrary(szTemp);
- }
- }
-#elif _M_X64
- if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
- {
- _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (x64)\\dbghelp.dll"));
- // now check if the file exists:
- if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
- {
- m_hDbhHelp = LoadLibrary(szTemp);
- }
- }
-#elif _M_IA64
- if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
- {
- _tcscat_s(szTemp, _T("\\Debugging Tools for Windows (ia64)\\dbghelp.dll"));
- // now check if the file exists:
- if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
- {
- m_hDbhHelp = LoadLibrary(szTemp);
- }
- }
-#endif
- // If still not found, try the old directories...
- if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
- {
- _tcscat_s(szTemp, _T("\\Debugging Tools for Windows\\dbghelp.dll"));
- // now check if the file exists:
- if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
- {
- m_hDbhHelp = LoadLibrary(szTemp);
- }
- }
-#if defined _M_X64 || defined _M_IA64
- // Still not found? Then try to load the (old) 64-Bit version:
- if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
- {
- _tcscat_s(szTemp, _T("\\Debugging Tools for Windows 64-Bit\\dbghelp.dll"));
- if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
- {
- m_hDbhHelp = LoadLibrary(szTemp);
- }
- }
-#endif
- }
- }
- if (m_hDbhHelp == NULL) // if not already loaded, try to load a default-one
- m_hDbhHelp = LoadLibrary( _T("dbghelp.dll") );
- if (m_hDbhHelp == NULL)
- return FALSE;
- pSI = (tSI) GetProcAddress(m_hDbhHelp, "SymInitialize" );
- pSC = (tSC) GetProcAddress(m_hDbhHelp, "SymCleanup" );
-
- pSW = (tSW) GetProcAddress(m_hDbhHelp, "StackWalk64" );
- pSGO = (tSGO) GetProcAddress(m_hDbhHelp, "SymGetOptions" );
- pSSO = (tSSO) GetProcAddress(m_hDbhHelp, "SymSetOptions" );
-
- pSFTA = (tSFTA) GetProcAddress(m_hDbhHelp, "SymFunctionTableAccess64" );
- pSGLFA = (tSGLFA) GetProcAddress(m_hDbhHelp, "SymGetLineFromAddr64" );
- pSGMB = (tSGMB) GetProcAddress(m_hDbhHelp, "SymGetModuleBase64" );
- pSGMI = (tSGMI) GetProcAddress(m_hDbhHelp, "SymGetModuleInfo64" );
- //pSGMI_V3 = (tSGMI_V3) GetProcAddress(m_hDbhHelp, "SymGetModuleInfo64" );
- pSGSFA = (tSGSFA) GetProcAddress(m_hDbhHelp, "SymGetSymFromAddr64" );
- pUDSN = (tUDSN) GetProcAddress(m_hDbhHelp, "UnDecorateSymbolName" );
- pSLM = (tSLM) GetProcAddress(m_hDbhHelp, "SymLoadModule64" );
- pSGSP =(tSGSP) GetProcAddress(m_hDbhHelp, "SymGetSearchPath" );
-
- if ( pSC == NULL || pSFTA == NULL || pSGMB == NULL || pSGMI == NULL ||
- pSGO == NULL || pSGSFA == NULL || pSI == NULL || pSSO == NULL ||
- pSW == NULL || pUDSN == NULL || pSLM == NULL )
- {
- FreeLibrary(m_hDbhHelp);
- m_hDbhHelp = NULL;
- pSC = NULL;
- return FALSE;
- }
-
- // SymInitialize
- if (szSymPath != NULL)
- m_szSymPath = _strdup(szSymPath);
- if (this->pSI(m_hProcess, m_szSymPath, FALSE) == FALSE)
- this->m_parent->OnDbgHelpErr("SymInitialize", GetLastError(), 0);
-
- DWORD symOptions = this->pSGO(); // SymGetOptions
- symOptions |= SYMOPT_LOAD_LINES;
- symOptions |= SYMOPT_FAIL_CRITICAL_ERRORS;
- //symOptions |= SYMOPT_NO_PROMPTS;
- // SymSetOptions
- symOptions = this->pSSO(symOptions);
-
- char buf[StackWalker::STACKWALK_MAX_NAMELEN] = {0};
- if (this->pSGSP != NULL)
- {
- if (this->pSGSP(m_hProcess, buf, StackWalker::STACKWALK_MAX_NAMELEN) == FALSE)
- this->m_parent->OnDbgHelpErr("SymGetSearchPath", GetLastError(), 0);
- }
- char szUserName[1024] = {0};
- DWORD dwSize = 1024;
- GetUserNameA(szUserName, &dwSize);
- this->m_parent->OnSymInit(buf, symOptions, szUserName);
-
- return TRUE;
- }
-
- StackWalker *m_parent;
-
- HMODULE m_hDbhHelp;
- HANDLE m_hProcess;
- LPSTR m_szSymPath;
-
-/*typedef struct IMAGEHLP_MODULE64_V3 {
- DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64)
- DWORD64 BaseOfImage; // base load address of module
- DWORD ImageSize; // virtual size of the loaded module
- DWORD TimeDateStamp; // date/time stamp from pe header
- DWORD CheckSum; // checksum from the pe header
- DWORD NumSyms; // number of symbols in the symbol table
- SYM_TYPE SymType; // type of symbols loaded
- CHAR ModuleName[32]; // module name
- CHAR ImageName[256]; // image name
- // new elements: 07-Jun-2002
- CHAR LoadedImageName[256]; // symbol file name
- CHAR LoadedPdbName[256]; // pdb file name
- DWORD CVSig; // Signature of the CV record in the debug directories
- CHAR CVData[MAX_PATH * 3]; // Contents of the CV record
- DWORD PdbSig; // Signature of PDB
- GUID PdbSig70; // Signature of PDB (VC 7 and up)
- DWORD PdbAge; // DBI age of pdb
- BOOL PdbUnmatched; // loaded an unmatched pdb
- BOOL DbgUnmatched; // loaded an unmatched dbg
- BOOL LineNumbers; // we have line number information
- BOOL GlobalSymbols; // we have internal symbol information
- BOOL TypeInfo; // we have type information
- // new elements: 17-Dec-2003
- BOOL SourceIndexed; // pdb supports source server
- BOOL Publics; // contains public symbols
-};
-*/
-
-#pragma pack(push,8)
-typedef struct IMAGEHLP_MODULE64_V2 {
- DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64)
- DWORD64 BaseOfImage; // base load address of module
- DWORD ImageSize; // virtual size of the loaded module
- DWORD TimeDateStamp; // date/time stamp from pe header
- DWORD CheckSum; // checksum from the pe header
- DWORD NumSyms; // number of symbols in the symbol table
- SYM_TYPE SymType; // type of symbols loaded
- CHAR ModuleName[32]; // module name
- CHAR ImageName[256]; // image name
- CHAR LoadedImageName[256]; // symbol file name
-};
-#pragma pack(pop)
-
-
- // SymCleanup()
- typedef BOOL (__stdcall *tSC)( IN HANDLE hProcess );
- tSC pSC;
-
- // SymFunctionTableAccess64()
- typedef PVOID (__stdcall *tSFTA)( HANDLE hProcess, DWORD64 AddrBase );
- tSFTA pSFTA;
-
- // SymGetLineFromAddr64()
- typedef BOOL (__stdcall *tSGLFA)( IN HANDLE hProcess, IN DWORD64 dwAddr,
- OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Line );
- tSGLFA pSGLFA;
-
- // SymGetModuleBase64()
- typedef DWORD64 (__stdcall *tSGMB)( IN HANDLE hProcess, IN DWORD64 dwAddr );
- tSGMB pSGMB;
-
- // SymGetModuleInfo64()
- typedef BOOL (__stdcall *tSGMI)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT IMAGEHLP_MODULE64_V2 *ModuleInfo );
- tSGMI pSGMI;
-
-// // SymGetModuleInfo64()
-// typedef BOOL (__stdcall *tSGMI_V3)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT IMAGEHLP_MODULE64_V3 *ModuleInfo );
-// tSGMI_V3 pSGMI_V3;
-
- // SymGetOptions()
- typedef DWORD (__stdcall *tSGO)( VOID );
- tSGO pSGO;
-
- // SymGetSymFromAddr64()
- typedef BOOL (__stdcall *tSGSFA)( IN HANDLE hProcess, IN DWORD64 dwAddr,
- OUT PDWORD64 pdwDisplacement, OUT PIMAGEHLP_SYMBOL64 Symbol );
- tSGSFA pSGSFA;
-
- // SymInitialize()
- typedef BOOL (__stdcall *tSI)( IN HANDLE hProcess, IN PSTR UserSearchPath, IN BOOL fInvadeProcess );
- tSI pSI;
-
- // SymLoadModule64()
- typedef DWORD64 (__stdcall *tSLM)( IN HANDLE hProcess, IN HANDLE hFile,
- IN PSTR ImageName, IN PSTR ModuleName, IN DWORD64 BaseOfDll, IN DWORD SizeOfDll );
- tSLM pSLM;
-
- // SymSetOptions()
- typedef DWORD (__stdcall *tSSO)( IN DWORD SymOptions );
- tSSO pSSO;
-
- // StackWalk64()
- typedef BOOL (__stdcall *tSW)(
- DWORD MachineType,
- HANDLE hProcess,
- HANDLE hThread,
- LPSTACKFRAME64 StackFrame,
- PVOID ContextRecord,
- PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
- PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
- PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
- PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress );
- tSW pSW;
-
- // UnDecorateSymbolName()
- typedef DWORD (__stdcall WINAPI *tUDSN)( PCSTR DecoratedName, PSTR UnDecoratedName,
- DWORD UndecoratedLength, DWORD Flags );
- tUDSN pUDSN;
-
- typedef BOOL (__stdcall WINAPI *tSGSP)(HANDLE hProcess, PSTR SearchPath, DWORD SearchPathLength);
- tSGSP pSGSP;
-
-
-private:
- // **************************************** ToolHelp32 ************************
- #define MAX_MODULE_NAME32 255
- #define TH32CS_SNAPMODULE 0x00000008
- #pragma pack( push, 8 )
- typedef struct tagMODULEENTRY32
- {
- DWORD dwSize;
- DWORD th32ModuleID; // This module
- DWORD th32ProcessID; // owning process
- DWORD GlblcntUsage; // Global usage count on the module
- DWORD ProccntUsage; // Module usage count in th32ProcessID's context
- BYTE * modBaseAddr; // Base address of module in th32ProcessID's context
- DWORD modBaseSize; // Size in bytes of module starting at modBaseAddr
- HMODULE hModule; // The hModule of this module in th32ProcessID's context
- char szModule[MAX_MODULE_NAME32 + 1];
- char szExePath[MAX_PATH];
- } MODULEENTRY32;
- typedef MODULEENTRY32 * PMODULEENTRY32;
- typedef MODULEENTRY32 * LPMODULEENTRY32;
- #pragma pack( pop )
-
- BOOL GetModuleListTH32(HANDLE hProcess, DWORD pid)
- {
- // CreateToolhelp32Snapshot()
- typedef HANDLE (__stdcall *tCT32S)(DWORD dwFlags, DWORD th32ProcessID);
- // Module32First()
- typedef BOOL (__stdcall *tM32F)(HANDLE hSnapshot, LPMODULEENTRY32 lpme);
- // Module32Next()
- typedef BOOL (__stdcall *tM32N)(HANDLE hSnapshot, LPMODULEENTRY32 lpme);
-
- // try both dlls...
- const TCHAR *dllname[] = { _T("kernel32.dll"), _T("tlhelp32.dll") };
- HINSTANCE hToolhelp = NULL;
- tCT32S pCT32S = NULL;
- tM32F pM32F = NULL;
- tM32N pM32N = NULL;
-
- HANDLE hSnap;
- MODULEENTRY32 me;
- me.dwSize = sizeof(me);
- BOOL keepGoing;
- size_t i;
-
- for (i = 0; i<(sizeof(dllname) / sizeof(dllname[0])); i++ )
- {
- hToolhelp = LoadLibrary( dllname[i] );
- if (hToolhelp == NULL)
- continue;
- pCT32S = (tCT32S) GetProcAddress(hToolhelp, "CreateToolhelp32Snapshot");
- pM32F = (tM32F) GetProcAddress(hToolhelp, "Module32First");
- pM32N = (tM32N) GetProcAddress(hToolhelp, "Module32Next");
- if ( (pCT32S != NULL) && (pM32F != NULL) && (pM32N != NULL) )
- break; // found the functions!
- FreeLibrary(hToolhelp);
- hToolhelp = NULL;
- }
-
- if (hToolhelp == NULL)
- return FALSE;
-
- hSnap = pCT32S( TH32CS_SNAPMODULE, pid );
- if (hSnap == (HANDLE) -1)
- {
- FreeLibrary(hToolhelp);
- return FALSE;
- }
-
- keepGoing = !!pM32F( hSnap, &me );
- int cnt = 0;
- while (keepGoing)
- {
- this->LoadModule(hProcess, me.szExePath, me.szModule, (DWORD64) me.modBaseAddr, me.modBaseSize);
- cnt++;
- keepGoing = !!pM32N( hSnap, &me );
- }
- CloseHandle(hSnap);
- FreeLibrary(hToolhelp);
- if (cnt <= 0)
- return FALSE;
- return TRUE;
- } // GetModuleListTH32
-
- // **************************************** PSAPI ************************
- typedef struct _MODULEINFO {
- LPVOID lpBaseOfDll;
- DWORD SizeOfImage;
- LPVOID EntryPoint;
- } MODULEINFO, *LPMODULEINFO;
-
- BOOL GetModuleListPSAPI(HANDLE hProcess)
- {
- // EnumProcessModules()
- typedef BOOL (__stdcall *tEPM)(HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded );
- // GetModuleFileNameEx()
- typedef DWORD (__stdcall *tGMFNE)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
- // GetModuleBaseName()
- typedef DWORD (__stdcall *tGMBN)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
- // GetModuleInformation()
- typedef BOOL (__stdcall *tGMI)(HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize );
-
- HINSTANCE hPsapi;
- tEPM pEPM;
- tGMFNE pGMFNE;
- tGMBN pGMBN;
- tGMI pGMI;
-
- DWORD i;
- //ModuleEntry e;
- DWORD cbNeeded;
- MODULEINFO mi;
- HMODULE *hMods = 0;
- char *tt = NULL;
- char *tt2 = NULL;
- const SIZE_T TTBUFLEN = 8096;
- int cnt = 0;
-
- hPsapi = LoadLibrary( _T("psapi.dll") );
- if (hPsapi == NULL)
- return FALSE;
-
- pEPM = (tEPM) GetProcAddress( hPsapi, "EnumProcessModules" );
- pGMFNE = (tGMFNE) GetProcAddress( hPsapi, "GetModuleFileNameExA" );
- pGMBN = (tGMFNE) GetProcAddress( hPsapi, "GetModuleBaseNameA" );
- pGMI = (tGMI) GetProcAddress( hPsapi, "GetModuleInformation" );
- if ( (pEPM == NULL) || (pGMFNE == NULL) || (pGMBN == NULL) || (pGMI == NULL) )
- {
- // we couldnīt find all functions
- FreeLibrary(hPsapi);
- return FALSE;
- }
-
- hMods = (HMODULE*) malloc(sizeof(HMODULE) * (TTBUFLEN / sizeof HMODULE));
- tt = (char*) malloc(sizeof(char) * TTBUFLEN);
- tt2 = (char*) malloc(sizeof(char) * TTBUFLEN);
- if ( (hMods == NULL) || (tt == NULL) || (tt2 == NULL) )
- goto cleanup;
-
- if ( ! pEPM( hProcess, hMods, TTBUFLEN, &cbNeeded ) )
- {
- //_ftprintf(fLogFile, _T("%lu: EPM failed, GetLastError = %lu\n"), g_dwShowCount, gle );
- goto cleanup;
- }
-
- if ( cbNeeded > TTBUFLEN )
- {
- //_ftprintf(fLogFile, _T("%lu: More than %lu module handles. Huh?\n"), g_dwShowCount, lenof( hMods ) );
- goto cleanup;
- }
-
- for ( i = 0; i < cbNeeded / sizeof hMods[0]; i++ )
- {
- // base address, size
- pGMI(hProcess, hMods[i], &mi, sizeof mi );
- // image file name
- tt[0] = 0;
- pGMFNE(hProcess, hMods[i], tt, TTBUFLEN );
- // module name
- tt2[0] = 0;
- pGMBN(hProcess, hMods[i], tt2, TTBUFLEN );
-
- DWORD dwRes = this->LoadModule(hProcess, tt, tt2, (DWORD64) mi.lpBaseOfDll, mi.SizeOfImage);
- if (dwRes != ERROR_SUCCESS)
- this->m_parent->OnDbgHelpErr("LoadModule", dwRes, 0);
- cnt++;
- }
-
- cleanup:
- if (hPsapi != NULL) FreeLibrary(hPsapi);
- if (tt2 != NULL) free(tt2);
- if (tt != NULL) free(tt);
- if (hMods != NULL) free(hMods);
-
- return cnt != 0;
- } // GetModuleListPSAPI
-
- DWORD LoadModule(HANDLE hProcess, LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size)
- {
- CHAR *szImg = _strdup(img);
- CHAR *szMod = _strdup(mod);
- DWORD result = ERROR_SUCCESS;
- if ( (szImg == NULL) || (szMod == NULL) )
- result = ERROR_NOT_ENOUGH_MEMORY;
- else
- {
- if (pSLM(hProcess, 0, szImg, szMod, baseAddr, size) == 0)
- result = GetLastError();
- }
- ULONGLONG fileVersion = 0;
- if ( (m_parent != NULL) && (szImg != NULL) )
- {
- // try to retrive the file-version:
- if ( (this->m_parent->m_options & StackWalker::RetrieveFileVersion) != 0)
- {
- VS_FIXEDFILEINFO *fInfo = NULL;
- DWORD dwHandle;
- DWORD dwSize = GetFileVersionInfoSizeA(szImg, &dwHandle);
- if (dwSize > 0)
- {
- LPVOID vData = malloc(dwSize);
- if (vData != NULL)
- {
- if (GetFileVersionInfoA(szImg, dwHandle, dwSize, vData) != 0)
- {
- UINT len;
- TCHAR szSubBlock[] = _T("\\");
- if (VerQueryValue(vData, szSubBlock, (LPVOID*) &fInfo, &len) == 0)
- fInfo = NULL;
- else
- {
- fileVersion = ((ULONGLONG)fInfo->dwFileVersionLS) + ((ULONGLONG)fInfo->dwFileVersionMS << 32);
- }
- }
- free(vData);
- }
- }
- }
-
- // Retrive some additional-infos about the module
- IMAGEHLP_MODULE64_V2 Module;
- const char *szSymType = "-unknown-";
- if (this->GetModuleInfo(hProcess, baseAddr, &Module) != FALSE)
- {
- switch(Module.SymType)
- {
- case SymNone:
- szSymType = "-nosymbols-";
- break;
- case SymCoff: // 1
- szSymType = "COFF";
- break;
- case SymCv: // 2
- szSymType = "CV";
- break;
- case SymPdb: // 3
- szSymType = "PDB";
- break;
- case SymExport: // 4
- szSymType = "-exported-";
- break;
- case SymDeferred: // 5
- szSymType = "-deferred-";
- break;
- case SymSym: // 6
- szSymType = "SYM";
- break;
- case 7: // SymDia:
- szSymType = "DIA";
- break;
- case 8: //SymVirtual:
- szSymType = "Virtual";
- break;
- }
- }
- this->m_parent->OnLoadModule(img, mod, baseAddr, size, result, szSymType, Module.LoadedImageName, fileVersion);
- }
- if (szImg != NULL) free(szImg);
- if (szMod != NULL) free(szMod);
- return result;
- }
-public:
- BOOL LoadModules(HANDLE hProcess, DWORD dwProcessId)
- {
- // first try toolhelp32
- if (GetModuleListTH32(hProcess, dwProcessId))
- return true;
- // then try psapi
- return GetModuleListPSAPI(hProcess);
- }
-
-
- BOOL GetModuleInfo(HANDLE hProcess, DWORD64 baseAddr, IMAGEHLP_MODULE64_V2 *pModuleInfo)
- {
- if(this->pSGMI == NULL)
- {
- SetLastError(ERROR_DLL_INIT_FAILED);
- return FALSE;
- }
- // First try to use the larger ModuleInfo-Structure
-// memset(pModuleInfo, 0, sizeof(IMAGEHLP_MODULE64_V3));
-// pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V3);
-// if (this->pSGMI_V3 != NULL)
-// {
-// if (this->pSGMI_V3(hProcess, baseAddr, pModuleInfo) != FALSE)
-// return TRUE;
-// // check if the parameter was wrong (size is bad...)
-// if (GetLastError() != ERROR_INVALID_PARAMETER)
-// return FALSE;
-// }
- // could not retrive the bigger structure, try with the smaller one (as defined in VC7.1)...
- pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2);
- void *pData = malloc(4096); // reserve enough memory, so the bug in v6.3.5.1 does not lead to memory-overwrites...
- if (pData == NULL)
- {
- SetLastError(ERROR_NOT_ENOUGH_MEMORY);
- return FALSE;
- }
- memcpy(pData, pModuleInfo, sizeof(IMAGEHLP_MODULE64_V2));
- if (this->pSGMI(hProcess, baseAddr, (IMAGEHLP_MODULE64_V2*) pData) != FALSE)
- {
- // only copy as much memory as is reserved...
- memcpy(pModuleInfo, pData, sizeof(IMAGEHLP_MODULE64_V2));
- pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2);
- free(pData);
- return TRUE;
- }
- free(pData);
- SetLastError(ERROR_DLL_INIT_FAILED);
- return FALSE;
- }
-};
-
-// #############################################################
-StackWalker::StackWalker(DWORD dwProcessId, HANDLE hProcess)
-{
- this->m_options = OptionsAll;
- this->m_modulesLoaded = FALSE;
- this->m_hProcess = hProcess;
- this->m_sw = new StackWalkerInternal(this, this->m_hProcess);
- this->m_dwProcessId = dwProcessId;
- this->m_szSymPath = NULL;
- this->m_MaxRecursionCount = 1000;
-}
-StackWalker::StackWalker(int options, LPCSTR szSymPath, DWORD dwProcessId, HANDLE hProcess)
-{
- this->m_options = options;
- this->m_modulesLoaded = FALSE;
- this->m_hProcess = hProcess;
- this->m_sw = new StackWalkerInternal(this, this->m_hProcess);
- this->m_dwProcessId = dwProcessId;
- if (szSymPath != NULL)
- {
- this->m_szSymPath = _strdup(szSymPath);
- this->m_options |= SymBuildPath;
- }
- else
- this->m_szSymPath = NULL;
- this->m_MaxRecursionCount = 1000;
-}
-
-StackWalker::~StackWalker()
-{
- if (m_szSymPath != NULL)
- free(m_szSymPath);
- m_szSymPath = NULL;
- if (this->m_sw != NULL)
- delete this->m_sw;
- this->m_sw = NULL;
-}
-
-BOOL StackWalker::LoadModules()
-{
- if (this->m_sw == NULL)
- {
- SetLastError(ERROR_DLL_INIT_FAILED);
- return FALSE;
- }
- if (m_modulesLoaded != FALSE)
- return TRUE;
-
- // Build the sym-path:
- char *szSymPath = NULL;
- if ( (this->m_options & SymBuildPath) != 0)
- {
- const size_t nSymPathLen = 4096;
- szSymPath = (char*) malloc(nSymPathLen);
- if (szSymPath == NULL)
- {
- SetLastError(ERROR_NOT_ENOUGH_MEMORY);
- return FALSE;
- }
- szSymPath[0] = 0;
- // Now first add the (optional) provided sympath:
- if (this->m_szSymPath != NULL)
- {
- strcat_s(szSymPath, nSymPathLen, this->m_szSymPath);
- strcat_s(szSymPath, nSymPathLen, ";");
- }
-
- strcat_s(szSymPath, nSymPathLen, ".;");
-
- const size_t nTempLen = 1024;
- char szTemp[nTempLen];
- // Now add the current directory:
- if (GetCurrentDirectoryA(nTempLen, szTemp) > 0)
- {
- szTemp[nTempLen-1] = 0;
- strcat_s(szSymPath, nSymPathLen, szTemp);
- strcat_s(szSymPath, nSymPathLen, ";");
- }
-
- // Now add the path for the main-module:
- if (GetModuleFileNameA(NULL, szTemp, nTempLen) > 0)
- {
- szTemp[nTempLen-1] = 0;
- for (char *p = (szTemp+strlen(szTemp)-1); p >= szTemp; --p)
- {
- // locate the rightmost path separator
- if ( (*p == '\\') || (*p == '/') || (*p == ':') )
- {
- *p = 0;
- break;
- }
- } // for (search for path separator...)
-
- if (szTemp[0] != '\0') // If szTemp is not empty (Note: This is more efficient than using strlen)
- {
- strcat_s(szSymPath, nSymPathLen, szTemp);
- strcat_s(szSymPath, nSymPathLen, ";");
- }
- }
- if (GetEnvironmentVariableA("_NT_SYMBOL_PATH", szTemp, nTempLen) > 0)
- {
- szTemp[nTempLen-1] = 0;
- strcat_s(szSymPath, nSymPathLen, szTemp);
- strcat_s(szSymPath, nSymPathLen, ";");
- }
- if (GetEnvironmentVariableA("_NT_ALTERNATE_SYMBOL_PATH", szTemp, nTempLen) > 0)
- {
- szTemp[nTempLen-1] = 0;
- strcat_s(szSymPath, nSymPathLen, szTemp);
- strcat_s(szSymPath, nSymPathLen, ";");
- }
- if (GetEnvironmentVariableA("SYSTEMROOT", szTemp, nTempLen) > 0)
- {
- szTemp[nTempLen-1] = 0;
- strcat_s(szSymPath, nSymPathLen, szTemp);
- strcat_s(szSymPath, nSymPathLen, ";");
- // also add the "system32"-directory:
- strcat_s(szTemp, nTempLen, "\\system32");
- strcat_s(szSymPath, nSymPathLen, szTemp);
- strcat_s(szSymPath, nSymPathLen, ";");
- }
-
- if ( (this->m_options & SymUseSymSrv) != 0)
- {
- if (GetEnvironmentVariableA("SYSTEMDRIVE", szTemp, nTempLen) > 0)
- {
- szTemp[nTempLen-1] = 0;
- strcat_s(szSymPath, nSymPathLen, "SRV*");
- strcat_s(szSymPath, nSymPathLen, szTemp);
- strcat_s(szSymPath, nSymPathLen, "\\websymbols");
- strcat_s(szSymPath, nSymPathLen, "*http://msdl.microsoft.com/download/symbols;");
- }
- else
- strcat_s(szSymPath, nSymPathLen, "SRV*c:\\websymbols*http://msdl.microsoft.com/download/symbols;");
- }
- } // if SymBuildPath
-
- // First Init the whole stuff...
- BOOL bRet = this->m_sw->Init(szSymPath);
- if (szSymPath != NULL) free(szSymPath); szSymPath = NULL;
- if (bRet == FALSE)
- {
- this->OnDbgHelpErr("Error while initializing dbghelp.dll", 0, 0);
- SetLastError(ERROR_DLL_INIT_FAILED);
- return FALSE;
- }
-
- bRet = this->m_sw->LoadModules(this->m_hProcess, this->m_dwProcessId);
- if (bRet != FALSE)
- m_modulesLoaded = TRUE;
- return bRet;
-}
-
-
-// The following is used to pass the "userData"-Pointer to the user-provided readMemoryFunction
-// This has to be done due to a problem with the "hProcess"-parameter in x64...
-// Because this class is in no case multi-threading-enabled (because of the limitations
-// of dbghelp.dll) it is "safe" to use a static-variable
-static StackWalker::PReadProcessMemoryRoutine s_readMemoryFunction = NULL;
-static LPVOID s_readMemoryFunction_UserData = NULL;
-
-BOOL StackWalker::ShowCallstack(HANDLE hThread, const CONTEXT *context, PReadProcessMemoryRoutine readMemoryFunction, LPVOID pUserData)
-{
- CONTEXT c;
- CallstackEntry csEntry;
- IMAGEHLP_SYMBOL64 *pSym = NULL;
- StackWalkerInternal::IMAGEHLP_MODULE64_V2 Module;
- IMAGEHLP_LINE64 Line;
- int frameNum;
- bool bLastEntryCalled = true;
- int curRecursionCount = 0;
-
- if (m_modulesLoaded == FALSE)
- this->LoadModules(); // ignore the result...
-
- if (this->m_sw->m_hDbhHelp == NULL)
- {
- SetLastError(ERROR_DLL_INIT_FAILED);
- return FALSE;
- }
-
- s_readMemoryFunction = readMemoryFunction;
- s_readMemoryFunction_UserData = pUserData;
-
- if (context == NULL)
- {
- // If no context is provided, capture the context
- if (hThread == GetCurrentThread())
- {
- GET_CURRENT_CONTEXT(c, USED_CONTEXT_FLAGS);
- }
- else
- {
- SuspendThread(hThread);
- memset(&c, 0, sizeof(CONTEXT));
- c.ContextFlags = USED_CONTEXT_FLAGS;
- if (GetThreadContext(hThread, &c) == FALSE)
- {
- ResumeThread(hThread);
- return FALSE;
- }
- }
- }
- else
- c = *context;
-
- // init STACKFRAME for first call
- STACKFRAME64 s; // in/out stackframe
- memset(&s, 0, sizeof(s));
- DWORD imageType;
-#ifdef _M_IX86
- // normally, call ImageNtHeader() and use machine info from PE header
- imageType = IMAGE_FILE_MACHINE_I386;
- s.AddrPC.Offset = c.Eip;
- s.AddrPC.Mode = AddrModeFlat;
- s.AddrFrame.Offset = c.Ebp;
- s.AddrFrame.Mode = AddrModeFlat;
- s.AddrStack.Offset = c.Esp;
- s.AddrStack.Mode = AddrModeFlat;
-#elif _M_X64
- imageType = IMAGE_FILE_MACHINE_AMD64;
- s.AddrPC.Offset = c.Rip;
- s.AddrPC.Mode = AddrModeFlat;
- s.AddrFrame.Offset = c.Rsp;
- s.AddrFrame.Mode = AddrModeFlat;
- s.AddrStack.Offset = c.Rsp;
- s.AddrStack.Mode = AddrModeFlat;
-#elif _M_IA64
- imageType = IMAGE_FILE_MACHINE_IA64;
- s.AddrPC.Offset = c.StIIP;
- s.AddrPC.Mode = AddrModeFlat;
- s.AddrFrame.Offset = c.IntSp;
- s.AddrFrame.Mode = AddrModeFlat;
- s.AddrBStore.Offset = c.RsBSP;
- s.AddrBStore.Mode = AddrModeFlat;
- s.AddrStack.Offset = c.IntSp;
- s.AddrStack.Mode = AddrModeFlat;
-#else
-#error "Platform not supported!"
-#endif
-
- pSym = (IMAGEHLP_SYMBOL64 *) malloc(sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN);
- if (!pSym) goto cleanup; // not enough memory...
- memset(pSym, 0, sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN);
- pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
- pSym->MaxNameLength = STACKWALK_MAX_NAMELEN;
-
- memset(&Line, 0, sizeof(Line));
- Line.SizeOfStruct = sizeof(Line);
-
- memset(&Module, 0, sizeof(Module));
- Module.SizeOfStruct = sizeof(Module);
-
- for (frameNum = 0; ; ++frameNum )
- {
- // get next stack frame (StackWalk64(), SymFunctionTableAccess64(), SymGetModuleBase64())
- // if this returns ERROR_INVALID_ADDRESS (487) or ERROR_NOACCESS (998), you can
- // assume that either you are done, or that the stack is so hosed that the next
- // deeper frame could not be found.
- // CONTEXT need not to be suplied if imageTyp is IMAGE_FILE_MACHINE_I386!
- if ( ! this->m_sw->pSW(imageType, this->m_hProcess, hThread, &s, &c, myReadProcMem, this->m_sw->pSFTA, this->m_sw->pSGMB, NULL) )
- {
- // INFO: "StackWalk64" does not set "GetLastError"...
- this->OnDbgHelpErr("StackWalk64", 0, s.AddrPC.Offset);
- break;
- }
-
- csEntry.offset = s.AddrPC.Offset;
- csEntry.name[0] = 0;
- csEntry.undName[0] = 0;
- csEntry.undFullName[0] = 0;
- csEntry.offsetFromSmybol = 0;
- csEntry.offsetFromLine = 0;
- csEntry.lineFileName[0] = 0;
- csEntry.lineNumber = 0;
- csEntry.loadedImageName[0] = 0;
- csEntry.moduleName[0] = 0;
- if (s.AddrPC.Offset == s.AddrReturn.Offset)
- {
- if ( (this->m_MaxRecursionCount > 0) && (curRecursionCount > m_MaxRecursionCount) )
- {
- this->OnDbgHelpErr("StackWalk64-Endless-Callstack!", 0, s.AddrPC.Offset);
- break;
- }
- curRecursionCount++;
- }
- else
- curRecursionCount = 0;
- if (s.AddrPC.Offset != 0)
- {
- // we seem to have a valid PC
- // show procedure info (SymGetSymFromAddr64())
- if (this->m_sw->pSGSFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromSmybol), pSym) != FALSE)
- {
- MyStrCpy(csEntry.name, STACKWALK_MAX_NAMELEN, pSym->Name);
- // UnDecorateSymbolName()
- this->m_sw->pUDSN( pSym->Name, csEntry.undName, STACKWALK_MAX_NAMELEN, UNDNAME_NAME_ONLY );
- this->m_sw->pUDSN( pSym->Name, csEntry.undFullName, STACKWALK_MAX_NAMELEN, UNDNAME_COMPLETE );
- }
- else
- {
- this->OnDbgHelpErr("SymGetSymFromAddr64", GetLastError(), s.AddrPC.Offset);
- }
-
- // show line number info, NT5.0-method (SymGetLineFromAddr64())
- if (this->m_sw->pSGLFA != NULL )
- { // yes, we have SymGetLineFromAddr64()
- if (this->m_sw->pSGLFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromLine), &Line) != FALSE)
- {
- csEntry.lineNumber = Line.LineNumber;
- MyStrCpy(csEntry.lineFileName, STACKWALK_MAX_NAMELEN, Line.FileName);
- }
- else
- {
- this->OnDbgHelpErr("SymGetLineFromAddr64", GetLastError(), s.AddrPC.Offset);
- }
- } // yes, we have SymGetLineFromAddr64()
-
- // show module info (SymGetModuleInfo64())
- if (this->m_sw->GetModuleInfo(this->m_hProcess, s.AddrPC.Offset, &Module ) != FALSE)
- { // got module info OK
- switch ( Module.SymType )
- {
- case SymNone:
- csEntry.symTypeString = "-nosymbols-";
- break;
- case SymCoff:
- csEntry.symTypeString = "COFF";
- break;
- case SymCv:
- csEntry.symTypeString = "CV";
- break;
- case SymPdb:
- csEntry.symTypeString = "PDB";
- break;
- case SymExport:
- csEntry.symTypeString = "-exported-";
- break;
- case SymDeferred:
- csEntry.symTypeString = "-deferred-";
- break;
- case SymSym:
- csEntry.symTypeString = "SYM";
- break;
-#if API_VERSION_NUMBER >= 9
- case SymDia:
- csEntry.symTypeString = "DIA";
- break;
-#endif
- case 8: //SymVirtual:
- csEntry.symTypeString = "Virtual";
- break;
- default:
- //_snprintf( ty, sizeof ty, "symtype=%ld", (long) Module.SymType );
- csEntry.symTypeString = NULL;
- break;
- }
-
- // TODO: Mache dies sicher...!
- MyStrCpy(csEntry.moduleName, STACKWALK_MAX_NAMELEN, Module.ModuleName);
- csEntry.baseOfImage = Module.BaseOfImage;
- MyStrCpy(csEntry.loadedImageName, STACKWALK_MAX_NAMELEN, Module.LoadedImageName);
- } // got module info OK
- else
- {
- this->OnDbgHelpErr("SymGetModuleInfo64", GetLastError(), s.AddrPC.Offset);
- }
- } // we seem to have a valid PC
-
- CallstackEntryType et = nextEntry;
- if (frameNum == 0)
- et = firstEntry;
- bLastEntryCalled = false;
- this->OnCallstackEntry(et, csEntry);
-
- if (s.AddrReturn.Offset == 0)
- {
- bLastEntryCalled = true;
- this->OnCallstackEntry(lastEntry, csEntry);
- SetLastError(ERROR_SUCCESS);
- break;
- }
- } // for ( frameNum )
-
- cleanup:
- if (pSym) free( pSym );
-
- if (bLastEntryCalled == false)
- this->OnCallstackEntry(lastEntry, csEntry);
-
- if (context == NULL)
- ResumeThread(hThread);
-
- return TRUE;
-}
-
-BOOL __stdcall StackWalker::myReadProcMem(
- HANDLE hProcess,
- DWORD64 qwBaseAddress,
- PVOID lpBuffer,
- DWORD nSize,
- LPDWORD lpNumberOfBytesRead
- )
-{
- if (s_readMemoryFunction == NULL)
- {
- SIZE_T st;
- BOOL bRet = ReadProcessMemory(hProcess, (LPVOID) qwBaseAddress, lpBuffer, nSize, &st);
- *lpNumberOfBytesRead = (DWORD) st;
- //printf("ReadMemory: hProcess: %p, baseAddr: %p, buffer: %p, size: %d, read: %d, result: %d\n", hProcess, (LPVOID) qwBaseAddress, lpBuffer, nSize, (DWORD) st, (DWORD) bRet);
- return bRet;
- }
- else
- {
- return s_readMemoryFunction(hProcess, qwBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead, s_readMemoryFunction_UserData);
- }
-}
-
-void StackWalker::OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
-{
- CHAR buffer[STACKWALK_MAX_NAMELEN];
- if (fileVersion == 0)
- _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);
- else
- {
- DWORD v4 = (DWORD) fileVersion & 0xFFFF;
- DWORD v3 = (DWORD) (fileVersion>>16) & 0xFFFF;
- DWORD v2 = (DWORD) (fileVersion>>32) & 0xFFFF;
- DWORD v1 = (DWORD) (fileVersion>>48) & 0xFFFF;
- _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);
- }
- OnOutput(buffer);
-}
-
-void StackWalker::OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry)
-{
- CHAR buffer[STACKWALK_MAX_NAMELEN];
- if ( (eType != lastEntry) && (entry.offset != 0) )
- {
- if (entry.name[0] == 0)
- MyStrCpy(entry.name, STACKWALK_MAX_NAMELEN, "(function-name not available)");
- if (entry.undName[0] != 0)
- MyStrCpy(entry.name, STACKWALK_MAX_NAMELEN, entry.undName);
- if (entry.undFullName[0] != 0)
- MyStrCpy(entry.name, STACKWALK_MAX_NAMELEN, entry.undFullName);
- if (entry.lineFileName[0] == 0)
- {
- MyStrCpy(entry.lineFileName, STACKWALK_MAX_NAMELEN, "(filename not available)");
- if (entry.moduleName[0] == 0)
- MyStrCpy(entry.moduleName, STACKWALK_MAX_NAMELEN, "(module-name not available)");
- _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "%p (%s): %s: %s\n", (LPVOID) entry.offset, entry.moduleName, entry.lineFileName, entry.name);
- }
- else
- _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "%s (%d): %s\n", entry.lineFileName, entry.lineNumber, entry.name);
- buffer[STACKWALK_MAX_NAMELEN-1] = 0;
- OnOutput(buffer);
- }
-}
-
-void StackWalker::OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr)
-{
- CHAR buffer[STACKWALK_MAX_NAMELEN];
- _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "ERROR: %s, GetLastError: %d (Address: %p)\n", szFuncName, gle, (LPVOID) addr);
- OnOutput(buffer);
-}
-
-void StackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName)
-{
- CHAR buffer[STACKWALK_MAX_NAMELEN];
- _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "SymInit: Symbol-SearchPath: '%s', symOptions: %d, UserName: '%s'\n", szSearchPath, symOptions, szUserName);
- OnOutput(buffer);
- // Also display the OS-version
-#if _MSC_VER <= 1200
- OSVERSIONINFOA ver;
- ZeroMemory(&ver, sizeof(OSVERSIONINFOA));
- ver.dwOSVersionInfoSize = sizeof(ver);
- if (GetVersionExA(&ver) != FALSE)
- {
- _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "OS-Version: %d.%d.%d (%s)\n",
- ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber,
- ver.szCSDVersion);
- OnOutput(buffer);
- }
-#else
- OSVERSIONINFOEXA ver;
- ZeroMemory(&ver, sizeof(OSVERSIONINFOEXA));
- ver.dwOSVersionInfoSize = sizeof(ver);
- if (GetVersionExA( (OSVERSIONINFOA*) &ver) != FALSE)
- {
- _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "OS-Version: %d.%d.%d (%s) 0x%x-0x%x\n",
- ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber,
- ver.szCSDVersion, ver.wSuiteMask, ver.wProductType);
- OnOutput(buffer);
- }
-#endif
-}
-
-void StackWalker::OnOutput(LPCSTR buffer)
-{
- OutputDebugStringA(buffer);
-}
diff --git a/src/StackWalker.h b/src/StackWalker.h
deleted file mode 100644
index a609f6840..000000000
--- a/src/StackWalker.h
+++ /dev/null
@@ -1,214 +0,0 @@
-/**********************************************************************
- *
- * StackWalker.h
- *
- *
- *
- * LICENSE (http://www.opensource.org/licenses/bsd-license.php)
- *
- * Copyright (c) 2005-2010, Jochen Kalmbach
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * Neither the name of Jochen Kalmbach nor the names of its contributors may be
- * used to endorse or promote products derived from this software without
- * specific prior written permission.
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * **********************************************************************/
-// #pragma once is supported starting with _MCS_VER 1000,
-// so we need not to check the version (because we only support _MSC_VER >= 1100)!
-#pragma once
-
-#include <windows.h>
-
-// special defines for VC5/6 (if no actual PSDK is installed):
-#if _MSC_VER < 1300
-typedef unsigned __int64 DWORD64, *PDWORD64;
-#if defined(_WIN64)
-typedef unsigned __int64 SIZE_T, *PSIZE_T;
-#else
-typedef unsigned long SIZE_T, *PSIZE_T;
-#endif
-#endif // _MSC_VER < 1300
-
-class StackWalkerInternal; // forward
-class StackWalker
-{
-public:
- typedef enum StackWalkOptions
- {
- // No addition info will be retrived
- // (only the address is available)
- RetrieveNone = 0,
-
- // Try to get the symbol-name
- RetrieveSymbol = 1,
-
- // Try to get the line for this symbol
- RetrieveLine = 2,
-
- // Try to retrieve the module-infos
- RetrieveModuleInfo = 4,
-
- // Also retrieve the version for the DLL/EXE
- RetrieveFileVersion = 8,
-
- // Contains all the abouve
- RetrieveVerbose = 0xF,
-
- // Generate a "good" symbol-search-path
- SymBuildPath = 0x10,
-
- // Also use the public Microsoft-Symbol-Server
- SymUseSymSrv = 0x20,
-
- // Contains all the abouve "Sym"-options
- SymAll = 0x30,
-
- // Contains all options (default)
- OptionsAll = 0x3F
- } StackWalkOptions;
-
- StackWalker(
- int options = OptionsAll, // 'int' is by design, to combine the enum-flags
- LPCSTR szSymPath = nullptr,
- DWORD dwProcessId = GetCurrentProcessId(),
- HANDLE hProcess = GetCurrentProcess()
- );
- StackWalker(DWORD dwProcessId, HANDLE hProcess);
- virtual ~StackWalker();
-
- typedef BOOL (__stdcall *PReadProcessMemoryRoutine)(
- HANDLE hProcess,
- DWORD64 qwBaseAddress,
- PVOID lpBuffer,
- DWORD nSize,
- LPDWORD lpNumberOfBytesRead,
- LPVOID pUserData // optional data, which was passed in "ShowCallstack"
- );
-
- BOOL LoadModules();
-
- BOOL ShowCallstack(
- HANDLE hThread = GetCurrentThread(),
- const CONTEXT *context = nullptr,
- PReadProcessMemoryRoutine readMemoryFunction = nullptr,
- LPVOID pUserData = nullptr // optional to identify some data in the 'readMemoryFunction'-callback
- );
-
-#if _MSC_VER >= 1300
-// due to some reasons, the "STACKWALK_MAX_NAMELEN" must be declared as "public"
-// in older compilers in order to use it... starting with VC7 we can declare it as "protected"
-protected:
-#endif
- enum { STACKWALK_MAX_NAMELEN = 1024 }; // max name length for found symbols
-
-protected:
- // Entry for each Callstack-Entry
- typedef struct CallstackEntry
- {
- DWORD64 offset; // if 0, we have no valid entry
- CHAR name[STACKWALK_MAX_NAMELEN];
- CHAR undName[STACKWALK_MAX_NAMELEN];
- CHAR undFullName[STACKWALK_MAX_NAMELEN];
- DWORD64 offsetFromSmybol;
- DWORD offsetFromLine;
- DWORD lineNumber;
- CHAR lineFileName[STACKWALK_MAX_NAMELEN];
- DWORD symType;
- LPCSTR symTypeString;
- CHAR moduleName[STACKWALK_MAX_NAMELEN];
- DWORD64 baseOfImage;
- CHAR loadedImageName[STACKWALK_MAX_NAMELEN];
- } CallstackEntry;
-
- typedef enum CallstackEntryType {firstEntry, nextEntry, lastEntry};
-
- virtual void OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName);
- virtual void OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion);
- virtual void OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry);
- virtual void OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr);
- virtual void OnOutput(LPCSTR szText);
-
- StackWalkerInternal *m_sw;
- HANDLE m_hProcess;
- DWORD m_dwProcessId;
- BOOL m_modulesLoaded;
- LPSTR m_szSymPath;
-
- int m_options;
- int m_MaxRecursionCount;
-
- static BOOL __stdcall myReadProcMem(HANDLE hProcess, DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize, LPDWORD lpNumberOfBytesRead);
-
- friend StackWalkerInternal;
-};
-
-
-// The "ugly" assembler-implementation is needed for systems before XP
-// If you have a new PSDK and you only compile for XP and later, then you can use
-// the "RtlCaptureContext"
-// Currently there is no define which determines the PSDK-Version...
-// So we just use the compiler-version (and assumes that the PSDK is
-// the one which was installed by the VS-IDE)
-
-// INFO: If you want, you can use the RtlCaptureContext if you only target XP and later...
-// But I currently use it in x64/IA64 environments...
-//#if defined(_M_IX86) && (_WIN32_WINNT <= 0x0500) && (_MSC_VER < 1400)
-
-#if defined(_M_IX86)
-#ifdef CURRENT_THREAD_VIA_EXCEPTION
-// TODO: The following is not a "good" implementation,
-// because the callstack is only valid in the "__except" block...
-#define GET_CURRENT_CONTEXT(c, contextFlags) \
- do { \
- memset(&c, 0, sizeof(CONTEXT)); \
- EXCEPTION_POINTERS *pExp = nullptr; \
- __try { \
- throw 0; \
- } __except( ( (pExp = GetExceptionInformation()) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_EXECUTE_HANDLER)) {} \
- if (pExp != nullptr) \
- memcpy(&c, pExp->ContextRecord, sizeof(CONTEXT)); \
- c.ContextFlags = contextFlags; \
- } while(0);
-#else
-// The following should be enough for walking the callstack...
-#define GET_CURRENT_CONTEXT(c, contextFlags) \
- do { \
- memset(&c, 0, sizeof(CONTEXT)); \
- c.ContextFlags = contextFlags; \
- __asm call x \
- __asm x: pop eax \
- __asm mov c.Eip, eax \
- __asm mov c.Ebp, ebp \
- __asm mov c.Esp, esp \
- } while(0);
-#endif
-
-#else
-
-// The following is defined for x86 (XP and higher), x64 and IA64:
-#define GET_CURRENT_CONTEXT(c, contextFlags) \
- do { \
- memset(&c, 0, sizeof(CONTEXT)); \
- c.ContextFlags = contextFlags; \
- RtlCaptureContext(&c); \
-} while(0);
-#endif
diff --git a/src/main.cpp b/src/main.cpp
index de194dc64..e3d4542dd 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -71,27 +71,6 @@ bool cRoot::m_RunAsService = false;
-/** If defined, a thorough leak finder will be used (debug MSVC only); leaks will be output to the Output window
-_X 2014_02_20: Disabled for canon repo, it makes the debug version too slow in MSVC2013
-and we haven't had a memory leak for over a year anyway.
-Synchronize this with Server.cpp to enable the "dumpmem" console command. */
-// #define ENABLE_LEAK_FINDER
-
-
-
-
-
-#if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER)
- #pragma warning(push)
- #pragma warning(disable:4100)
- #include "LeakFinder.h"
- #pragma warning(pop)
-#endif
-
-
-
-
-
#ifndef _DEBUG
static void NonCtrlHandler(int a_Signal)
{
@@ -470,10 +449,6 @@ static std::unique_ptr<cMemorySettingsRepository> ParseArguments(int argc, char
int main(int argc, char ** argv)
{
- #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER)
- InitLeakFinder();
- #endif
-
// Magic code to produce dump-files on Windows if the server crashes:
#if defined(_WIN32) && !defined(_WIN64) && defined(_MSC_VER) // 32-bit Windows app compiled in MSVC
HINSTANCE hDbgHelp = LoadLibrary(L"DBGHELP.DLL");
@@ -571,10 +546,5 @@ int main(int argc, char ** argv)
UniversalMain(ParseArguments(argc, argv));
}
}
-
- #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER)
- DeinitLeakFinder();
- #endif
-
return EXIT_SUCCESS;
}