Initial version of crash dump generator on Windows
authorVictor Kirhenshtein <victor@netxms.org>
Fri, 9 Feb 2007 17:31:58 +0000 (17:31 +0000)
committerVictor Kirhenshtein <victor@netxms.org>
Fri, 9 Feb 2007 17:31:58 +0000 (17:31 +0000)
23 files changed:
.gitattributes
include/nms_threads.h
src/libnetxms/Makefile.am
src/libnetxms/StackWalker.cpp [new file with mode: 0644]
src/libnetxms/StackWalker.h [new file with mode: 0644]
src/libnetxms/libnetxms.dsp
src/libnetxms/libnetxms.h
src/libnetxms/main.cpp
src/libnetxms/seh.cpp [new file with mode: 0644]
src/libnxmap/libnxmap.dsp
src/libnxsl/libnxsl.dsp
src/libnxsnmp/libnxsnmp.dsp
src/server/core/config.cpp
src/server/core/main.cpp
src/server/core/nxcore.dsp
src/server/include/nms_core.h
src/server/include/nxsrvapi.h
src/server/libnxsrv/agent.cpp
src/server/libnxsrv/libnxsrv.dsp
src/server/netxmsd/netxmsd.cpp
src/server/netxmsd/netxmsd.dsp
src/server/tools/nxget/nxget.cpp
src/server/tools/nxget/nxget.dsp

index c541110..d31a92c 100644 (file)
@@ -1008,6 +1008,8 @@ src/install/windows/nxcon.exe.manifest -text
 src/install/windows/nxnotify.exe.manifest -text
 src/libnetxms/Makefile.am -text
 src/libnetxms/Makefile.nw -text
+src/libnetxms/StackWalker.cpp -text
+src/libnetxms/StackWalker.h -text
 src/libnetxms/c_lgcc3.cpp -text
 src/libnetxms/config.cpp -text
 src/libnetxms/crypto.cpp -text
@@ -1034,6 +1036,7 @@ src/libnetxms/queue.cpp -text
 src/libnetxms/regex.c -text
 src/libnetxms/rwlock.cpp -text
 src/libnetxms/scandir.c -text
+src/libnetxms/seh.cpp -text
 src/libnetxms/serial.cpp -text
 src/libnetxms/sha1.cpp -text
 src/libnetxms/sha1.h -text
index d729407..8458b1b 100644 (file)
@@ -59,6 +59,21 @@ typedef unsigned int THREAD_ID;
 #define THREAD_CALL
 #else
 #define THREAD_CALL     __stdcall
+
+typedef struct
+{
+       THREAD_RESULT (THREAD_CALL *start_address)(void *);
+       void *args;
+} THREAD_START_DATA;
+
+THREAD_RESULT LIBNETXMS_EXPORTABLE THREAD_CALL SEHThreadStarter(void *);
+
+void LIBNETXMS_EXPORTABLE SetExceptionHandler(void (*pfHandler)(EXCEPTION_POINTERS *),
+                                                                                                                        void (*pfWriter)(char *));
+void LIBNETXMS_EXPORTABLE SEHDefaultConsoleHandler(EXCEPTION_POINTERS *pInfo);
+TCHAR LIBNETXMS_EXPORTABLE *SEHExceptionName(DWORD code);
+void LIBNETXMS_EXPORTABLE SEHShowCallStack(CONTEXT *pCtx);
+
 #endif
 
 
@@ -80,7 +95,7 @@ inline void ThreadSleepMs(DWORD dwMilliseconds)
    Sleep(dwMilliseconds);
 }
 
-inline BOOL ThreadCreate(THREAD_RESULT (THREAD_CALL *start_address )(void *), int stack_size, void *args)
+inline BOOL ThreadCreate(THREAD_RESULT (THREAD_CALL *start_address)(void *), int stack_size, void *args)
 {
    HANDLE hThread;
    THREAD_ID dwThreadId;
@@ -88,21 +103,27 @@ inline BOOL ThreadCreate(THREAD_RESULT (THREAD_CALL *start_address )(void *), in
 #ifdef UNDER_CE
        hThread = CreateThread(NULL, (DWORD)stack_size, start_address, args, 0, &dwThreadId);
 #else
-   hThread = (HANDLE)_beginthreadex(NULL, stack_size, start_address, args, 0, &dwThreadId);
+       THREAD_START_DATA *data = (THREAD_START_DATA *)malloc(sizeof(THREAD_START_DATA));
+       data->start_address = start_address;
+       data->args = args;
+   hThread = (HANDLE)_beginthreadex(NULL, stack_size, SEHThreadStarter, data, 0, &dwThreadId);
 #endif
    if (hThread != NULL)
       CloseHandle(hThread);
    return (hThread != NULL);
 }
 
-inline THREAD ThreadCreateEx(THREAD_RESULT (THREAD_CALL *start_address )(void *), int stack_size, void *args)
+inline THREAD ThreadCreateEx(THREAD_RESULT (THREAD_CALL *start_address)(void *), int stack_size, void *args)
 {
    THREAD_ID dwThreadId;
 
 #ifdef UNDER_CE
        return CreateThread(NULL, (DWORD)stack_size, start_address, args, 0, &dwThreadId);
 #else
-   return (HANDLE)_beginthreadex(NULL, stack_size, start_address, args, 0, &dwThreadId);
+       THREAD_START_DATA *data = (THREAD_START_DATA *)malloc(sizeof(THREAD_START_DATA));
+       data->start_address = start_address;
+       data->args = args;
+   return (HANDLE)_beginthreadex(NULL, stack_size, SEHThreadStarter, data, 0, &dwThreadId);
 #endif
 }
 
index 4020da2..7d9ef79 100644 (file)
@@ -9,4 +9,5 @@ EXTRA_DIST = \
        libnetxms.vcp libnetxms.vcw \
        Makefile.nw netxms.def \
        libnetxms.h md5.h sha1.h uuidP.h \
-       regex.c c_lgcc3.cpp dir.c getopt.c
+       regex.c c_lgcc3.cpp dir.c getopt.c \
+       seh.cpp StackWalker.cpp StackWalker.h
diff --git a/src/libnetxms/StackWalker.cpp b/src/libnetxms/StackWalker.cpp
new file mode 100644 (file)
index 0000000..8151748
--- /dev/null
@@ -0,0 +1,1044 @@
+/**********************************************************************
+ * 
+ * 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)
+ *
+ **********************************************************************/
+#include <windows.h>
+#include <tchar.h>
+#include <stdio.h>
+#pragma comment(lib, "version.lib")  // for "VerQueryValue"
+
+#include "StackWalker.h"
+#include <dbghelp.h>
+
+// 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 strcat_s(dst, len, src) strcat(dst, src)
+#define _snprintf_s _snprintf
+#define _tcscat_s _tcscat
+#endif
+
+// 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;
+  }
+  ~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)
+  {
+    // 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"
+        if (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);
+          }
+        }
+          // Still not found? Then try to load the 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);
+          }
+        }
+      }
+    }
+    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" );
+    pSGMI_V2 = (tSGMI_V2) 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;
+    symOptions &= ~SYMOPT_UNDNAME;
+    symOptions &= ~SYMOPT_DEFERRED_LOADS;
+    // 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
+};
+*/
+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
+};
+
+
+  // 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 PIMAGEHLP_MODULE64 ModuleInfo );
+  tSGMI pSGMI;
+
+//  // SymGetModuleInfo64()
+//  typedef BOOL (__stdcall *tSGMI_V3)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT IMAGEHLP_MODULE64_V3 *ModuleInfo );
+//  tSGMI_V3 pSGMI_V3;
+
+  // SymGetModuleInfo64()
+  typedef BOOL (__stdcall *tSGMI_V2)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT IMAGEHLP_MODULE64_V2 *ModuleInfo );
+  tSGMI_V2 pSGMI_V2;
+
+  // 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;
+    int 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)
+      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, DWORD pid)
+  {
+    // 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 ( ! 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 );
+
+      this->LoadModule(hProcess, tt, tt2, (DWORD64) mi.lpBaseOfDll, mi.SizeOfImage);
+      cnt++;
+    }
+
+  cleanup:
+    if (hPsapi)
+      FreeLibrary(hPsapi);
+    free(tt2);
+    free(tt);
+    free(hMods);
+
+    return cnt != 0;
+  }  // GetModuleListPSAPI
+
+  void LoadModule(HANDLE hProcess, LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size)
+  {
+    CHAR *i = _strdup(img);
+    CHAR *m = _strdup(mod);
+    DWORD result = ERROR_SUCCESS;
+    if (pSLM(hProcess, 0, i, m, baseAddr, size) == 0)
+      result = GetLastError();
+    ULONGLONG fileVersion = 0;
+    if (m_parent != NULL)
+    {
+      // try to retrive the file-version:
+      if ( (this->m_parent->m_options & StackWalker::RetrieveFileVersion) != 0)
+      {
+        LPVOID vData = NULL;
+        VS_FIXEDFILEINFO *fInfo = NULL;
+        DWORD dwHandle;
+        // Fix for VC7.0-PSDK (GetFileVersionInfoSize is wrongly defined)
+        LPSTR szImg = _strdup(img);
+        DWORD dwSize = GetFileVersionInfoSizeA(szImg, &dwHandle);
+        if (dwSize > 0)
+        {
+          vData = malloc(dwSize);
+          if (GetFileVersionInfoA(szImg, dwHandle, dwSize, vData) != 0)
+          {
+            UINT len;
+            if (VerQueryValue(vData, _T("\\"), (LPVOID*) &fInfo, &len) == 0)
+              fInfo = NULL;
+            else
+            {
+              fileVersion = ((ULONGLONG)fInfo->dwFileVersionLS) + ((ULONGLONG)fInfo->dwFileVersionMS << 32);
+            }
+          }
+        }
+        if (szImg != NULL)
+          free(szImg);
+        if (vData != NULL)
+          free(vData);
+      }
+
+      // Retrive some additional-infos about the module
+      IMAGEHLP_MODULE64_V2 Module;
+      this->GetModuleInfo(hProcess, baseAddr, &Module);
+      const char *szSymType = "-unknown-";
+      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;
+#if API_VERSION_NUMBER >= 9
+        case SymDia:
+          szSymType = "DIA";
+          break;
+#endif
+        case 8: //SymVirtual:
+          szSymType = "Virtual";
+          break;
+      }
+      this->m_parent->OnLoadModule(img, mod, baseAddr, size, result, szSymType, Module.LoadedImageName, fileVersion);
+    }
+    free(i);
+    free(m);
+  }
+public:
+  BOOL LoadModules(HANDLE hProcess, DWORD dwProcessId)
+  {
+    // first try toolhelp32
+    if (GetModuleListTH32(hProcess, dwProcessId))
+      return true;
+    // then try psapi
+    return GetModuleListPSAPI(hProcess, dwProcessId);
+  }
+
+
+  BOOL GetModuleInfo(HANDLE hProcess, DWORD64 baseAddr, IMAGEHLP_MODULE64_V2 *pModuleInfo)
+  {
+    if(this->pSGMI_V2 == 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...
+    memcpy(pData, pModuleInfo, sizeof(IMAGEHLP_MODULE64_V2));
+    if (this->pSGMI_V2 != NULL)
+    {
+      if (this->pSGMI_V2(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);
+      return FALSE;
+    }
+    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;
+}
+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;
+}
+
+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);
+    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)
+    {
+      strcat_s(szSymPath, nSymPathLen, szTemp);
+      strcat_s(szSymPath, nSymPathLen, ";");
+    }
+
+    // Now add the path for the main-module:
+    if (GetModuleFileNameA(NULL, szTemp, nTempLen) > 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 (strlen(szTemp) > 0)
+      {
+        strcat_s(szSymPath, nSymPathLen, szTemp);
+        strcat_s(szSymPath, nSymPathLen, ";");
+      }
+    }
+    if (GetEnvironmentVariableA("_NT_SYMBOL_PATH", szTemp, nTempLen) > 0)
+    {
+      strcat_s(szSymPath, nSymPathLen, szTemp);
+      strcat_s(szSymPath, nSymPathLen, ";");
+    }
+    if (GetEnvironmentVariableA("_NT_ALTERNATE_SYMBOL_PATH", szTemp, nTempLen) > 0)
+    {
+      strcat_s(szSymPath, nSymPathLen, szTemp);
+      strcat_s(szSymPath, nSymPathLen, ";");
+    }
+    if (GetEnvironmentVariableA("SYSTEMROOT", szTemp, nTempLen) > 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 & SymBuildPath) != 0)
+    {
+      if (GetEnvironmentVariableA("SYSTEMDRIVE", szTemp, nTempLen) > 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;");
+    }
+  }
+
+  // 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, CONTEXT *context, PReadProcessMemoryRoutine readMemoryFunction, LPVOID pUserData)
+{
+  CONTEXT c;;
+  CallstackEntry csEntry;
+  IMAGEHLP_SYMBOL64 *pSym = NULL;
+  StackWalkerInternal::IMAGEHLP_MODULE64_V2 Module;
+  IMAGEHLP_LINE64 Line;
+  int frameNum;
+
+  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) )
+    {
+      this->OnDbgHelpErr("StackWalk64", GetLastError(), 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 != 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)
+      {
+        // TODO: Mache dies sicher...!
+        strcpy_s(csEntry.name, 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;
+          // TODO: Mache dies sicher...!
+          strcpy_s(csEntry.lineFileName, 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
+        default:
+          //_snprintf( ty, sizeof ty, "symtype=%ld", (long) Module.SymType );
+          csEntry.symTypeString = NULL;
+          break;
+        }
+
+        // TODO: Mache dies sicher...!
+        strcpy_s(csEntry.moduleName, Module.ModuleName);
+        csEntry.baseOfImage = Module.BaseOfImage;
+        strcpy_s(csEntry.loadedImageName, 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;
+    this->OnCallstackEntry(et, csEntry);
+    
+    if (s.AddrReturn.Offset == 0)
+    {
+      this->OnCallstackEntry(lastEntry, csEntry);
+      SetLastError(ERROR_SUCCESS);
+      break;
+    }
+  } // for ( frameNum )
+
+  cleanup:
+    if (pSym) free( pSym );
+
+  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)
+      strcpy_s(entry.name, "(function-name not available)");
+    if (entry.undName[0] != 0)
+      strcpy_s(entry.name, entry.undName);
+    if (entry.undFullName[0] != 0)
+      strcpy_s(entry.name, entry.undFullName);
+    if (entry.lineFileName[0] == 0)
+    {
+      strcpy_s(entry.lineFileName, "(filename not available)");
+      if (entry.moduleName[0] == 0)
+        strcpy_s(entry.moduleName, "(module-name not available)");
+      _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "[%s:%p]: %s\n", entry.moduleName, (LPVOID)entry.offset, entry.name);
+    }
+    else
+        {
+      _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "[%s:%s:%d]: %s\n", entry.moduleName, entry.lineFileName, entry.lineNumber, entry.name);
+    }
+    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
+  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);
+  }
+}
+
+void StackWalker::OnOutput(LPCSTR buffer)
+{
+  OutputDebugStringA(buffer);
+}
diff --git a/src/libnetxms/StackWalker.h b/src/libnetxms/StackWalker.h
new file mode 100644 (file)
index 0000000..044d862
--- /dev/null
@@ -0,0 +1,185 @@
+/**********************************************************************
+ * 
+ * StackWalker.h
+ *
+ *
+ * History:
+ *  2005-07-27   v1    - First public release on http://www.codeproject.com/
+ *  (for additional changes see History in 'StackWalker.cpp'!
+ *
+ **********************************************************************/
+// #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, 
+    LPCSTR szSymPath = NULL, 
+    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(), 
+    CONTEXT *context = NULL, 
+    PReadProcessMemoryRoutine readMemoryFunction = NULL,
+    LPVOID pUserData = NULL  // optional to identify some data in the 'readMemoryFunction'-callback
+    );
+
+#if _MSCVER >= 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;
+
+  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)
+#if defined(_M_IX86) && (_WIN32_WINNT <= 0x0500) && (_MSC_VER < 1400)
+
+#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 = NULL; \
+    __try { \
+      throw 0; \
+    } __except( ( (pExp = GetExceptionInformation()) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_EXECUTE_HANDLER)) {} \
+    if (pExp != NULL) \
+      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
index b958409..c7de9d0 100644 (file)
@@ -57,11 +57,11 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib /nologo /version:0.1 /dll /machine:I386
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib dbghelp.lib /nologo /version:0.1 /dll /debug /machine:I386 /pdbtype:sept
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Release\libnetxms.dll C:\NetXMS\bin
+PostBuild_Cmds=copy Release\libnetxms.dll C:\NetXMS\bin        copy Release\libnetxms.pdb C:\NetXMS\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "libnetxms - Win32 Debug"
@@ -88,12 +88,12 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib /nologo /version:0.1 /dll /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib dbghelp.lib /nologo /version:0.1 /dll /debug /machine:I386 /pdbtype:sept
 # SUBTRACT LINK32 /pdb:none
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Debug\libnetxms.dll ..\..\bin
+PostBuild_Cmds=copy Debug\libnetxms.dll ..\..\bin      copy Debug\libnetxms.pdb ..\..\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "libnetxms - Win32 Debug AMD64"
@@ -108,7 +108,7 @@ PostBuild_Cmds=copy Debug\libnetxms.dll ..\..\bin
 # PROP Use_Debug_Libraries 1
 # PROP Output_Dir "Debug64"
 # PROP Intermediate_Dir "Debug64"
-# PROP Ignore_Export_Lib 1
+# PROP Ignore_Export_Lib 0
 # PROP Target_Dir ""
 # ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\..\include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBNETXMS_EXPORTS" /YX /FD /GZ /c
 # ADD CPP /nologo /MDd /W3 /Gm /Zi /Od /I "..\..\include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBNETXMS_EXPORTS" /D "__64BIT__" /FD /GZ /Wp64 /c
@@ -121,7 +121,7 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib /nologo /version:0.1 /dll /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 bufferoverflowU.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib /nologo /version:0.1 /dll /debug /machine:IX86 /pdbtype:sept /machine:AMD64
+# ADD LINK32 bufferoverflowU.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib dbghelp.lib /nologo /version:0.1 /dll /debug /machine:IX86 /pdbtype:sept /machine:AMD64
 # SUBTRACT LINK32 /pdb:none
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
@@ -154,7 +154,7 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib /nologo /version:0.1 /dll /machine:I386
-# ADD LINK32 bufferoverflowU.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib /nologo /version:0.1 /dll /machine:IX86 /machine:AMD64
+# ADD LINK32 bufferoverflowU.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib dbghelp.lib /nologo /version:0.1 /dll /machine:IX86 /machine:AMD64
 # SUBTRACT LINK32 /pdb:none
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
@@ -174,7 +174,7 @@ PostBuild_Cmds=copy Release64\libnetxms.dll C:\NetXMS\bin64
 # PROP Use_Debug_Libraries 1
 # PROP Output_Dir "Debug_UNICODE"
 # PROP Intermediate_Dir "Debug_UNICODE"
-# PROP Ignore_Export_Lib 1
+# PROP Ignore_Export_Lib 0
 # PROP Target_Dir ""
 # ADD BASE CPP /nologo /MDd /W3 /Gm /ZI /Od /I "..\..\include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBNETXMS_EXPORTS" /YX /FD /GZ /c
 # ADD CPP /nologo /MDd /W3 /Gm /ZI /Od /I "..\..\include" /D "UNICODE" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBNETXMS_EXPORTS" /YX /FD /GZ /c
@@ -188,7 +188,7 @@ BSC32=bscmake.exe
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib /nologo /version:0.1 /dll /debug /machine:I386 /pdbtype:sept
 # SUBTRACT BASE LINK32 /pdb:none
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib /nologo /version:0.1 /dll /debug /machine:I386 /out:"Debug_UNICODE/libnetxmsw.dll" /pdbtype:sept
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib dbghelp.lib /nologo /version:0.1 /dll /debug /machine:I386 /out:"Debug_UNICODE/libnetxmsw.dll" /pdbtype:sept
 # SUBTRACT LINK32 /pdb:none
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
@@ -221,7 +221,7 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib ntdll.lib /nologo /version:0.1 /dll /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib /nologo /version:0.1 /dll /machine:I386 /out:"Release_UNICODE/libnetxmsw.dll"
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libeay32.lib dbghelp.lib /nologo /version:0.1 /dll /machine:I386 /out:"Release_UNICODE/libnetxmsw.dll"
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
@@ -315,6 +315,10 @@ SOURCE=.\scandir.c
 # End Source File
 # Begin Source File
 
+SOURCE=.\seh.cpp
+# End Source File
+# Begin Source File
+
 SOURCE=.\serial.cpp
 # End Source File
 # Begin Source File
@@ -323,6 +327,10 @@ SOURCE=.\sha1.cpp
 # End Source File
 # Begin Source File
 
+SOURCE=.\StackWalker.cpp
+# End Source File
+# Begin Source File
+
 SOURCE=.\string.cpp
 # End Source File
 # Begin Source File
@@ -411,6 +419,10 @@ SOURCE=.\sha1.h
 # End Source File
 # Begin Source File
 
+SOURCE=.\StackWalker.h
+# End Source File
+# Begin Source File
+
 SOURCE=..\..\include\unicode.h
 # End Source File
 # Begin Source File
index 9156781..423556b 100644 (file)
@@ -1,7 +1,8 @@
+/* $Id: libnetxms.h,v 1.8 2007-02-09 17:31:57 victor Exp $ */
 /* 
 ** NetXMS - Network Management System
 ** Utility Library
-** Copyright (C) 2003, 2004 Victor Kirhenshtein
+** Copyright (C) 2003, 2004, 2005, 2006, 2007 Victor Kirhenshtein
 **
 ** This program is free software; you can redistribute it and/or modify
 ** it under the terms of the GNU General Public License as published by
@@ -17,7 +18,7 @@
 ** along with this program; if not, write to the Free Software
 ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 **
-** $module: libnetxms.h
+** File: libnetxms.h
 **
 **/
 
 
 #define MAX_CODEPAGE_LEN               64
 
+
+//
+// Functions
+//
+
+void SEHInit(void);
+
+
 #endif   /* _libnetxms_h_ */
index b2eb6e5..390a84c 100644 (file)
@@ -1,7 +1,8 @@
+/* $Id: main.cpp,v 1.12 2007-02-09 17:31:57 victor Exp $ */
 /* 
 ** NetXMS - Network Management System
 ** Utility Library
-** Copyright (C) 2003 Victor Kirhenshtein
+** Copyright (C) 2003, 2004, 2005, 2006, 2007 Victor Kirhenshtein
 **
 ** This program is free software; you can redistribute it and/or modify
 ** it under the terms of the GNU General Public License as published by
@@ -17,7 +18,7 @@
 ** along with this program; if not, write to the Free Software
 ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 **
-** $module: main.cpp
+** File: main.cpp
 **
 **/
 
@@ -112,7 +113,10 @@ void LIBNETXMS_EXPORTABLE strupr(char *in)
 BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
 {
    if (dwReason == DLL_PROCESS_ATTACH)
+       {
       DisableThreadLibraryCalls(hInstance);
+               SEHInit();
+       }
    return TRUE;
 }
 #endif // UNDER_CE
diff --git a/src/libnetxms/seh.cpp b/src/libnetxms/seh.cpp
new file mode 100644 (file)
index 0000000..a6794d2
--- /dev/null
@@ -0,0 +1,218 @@
+/* 
+** NetXMS - Network Management System
+** Copyright (C) 2005, 2006, 2007 Victor Kirhenshtein
+**
+** This program is free software; you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation; either version 2 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program; if not, write to the Free Software
+** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+**
+** File: seh.cpp
+**
+**/
+
+#include "libnetxms.h"
+#include <dbghelp.h>
+#include "StackWalker.h"
+
+
+//
+// Customized StackWalker class
+//
+
+class NxStackWalker : public StackWalker
+{
+protected:
+       virtual void OnOutput(LPCSTR pszText);
+       virtual void OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName) { }
+       virtual void OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr) { }
+
+public:
+       NxStackWalker(int options, LPCSTR szSymPath, DWORD dwProcessId, HANDLE hProcess)
+               : StackWalker(options, szSymPath, dwProcessId, hProcess) { }
+};
+
+
+//
+// Static data
+//
+
+static void (*m_pfExceptionHandler)(EXCEPTION_POINTERS *) = NULL;
+static void (*m_pfWriter)(char *pszText) = NULL;
+static HANDLE m_hExceptionLock = INVALID_HANDLE_VALUE;
+
+
+//
+// Output for stack walker
+//
+
+void NxStackWalker::OnOutput(LPCSTR pszText)
+{
+       if (m_pfWriter != NULL)
+       {
+               m_pfWriter("  ");
+               m_pfWriter((char *)pszText);
+       }
+       else
+       {
+               fputs("  ", stdout);
+               fputs(pszText, stdout);
+       }
+}
+
+
+//
+// Initialize SEH functions
+//
+
+void SEHInit(void)
+{
+       m_hExceptionLock = CreateMutex(NULL, FALSE, NULL);
+}
+
+
+//
+// Set exception handler
+//
+
+void LIBNETXMS_EXPORTABLE SetExceptionHandler(void (*pfHandler)(EXCEPTION_POINTERS *),
+                                                                                                                        void (*pfWriter)(char *))
+{
+       m_pfExceptionHandler = pfHandler;
+       m_pfWriter = pfWriter;
+}
+
+
+//
+// Get exception name from code
+//
+
+TCHAR LIBNETXMS_EXPORTABLE *SEHExceptionName(DWORD code)
+{
+   static struct 
+   {
+      DWORD code;
+      char *name;
+   } exceptionList[] =
+   {
+      { EXCEPTION_ACCESS_VIOLATION, _T("Access violation") },
+      { EXCEPTION_ARRAY_BOUNDS_EXCEEDED, _T("Array bounds exceeded") },
+      { EXCEPTION_BREAKPOINT, _T("Breakpoint") },
+      { EXCEPTION_DATATYPE_MISALIGNMENT, _T("Alignment error") },
+      { EXCEPTION_FLT_DENORMAL_OPERAND, _T("FLT_DENORMAL_OPERAND") },
+      { EXCEPTION_FLT_DIVIDE_BY_ZERO, _T("FLT_DIVIDE_BY_ZERO") },
+      { EXCEPTION_FLT_INEXACT_RESULT, _T("FLT_INEXACT_RESULT") },
+      { EXCEPTION_FLT_INVALID_OPERATION, _T("FLT_INVALID_OPERATION") },
+      { EXCEPTION_FLT_OVERFLOW, _T("Floating point overflow") },
+      { EXCEPTION_FLT_STACK_CHECK, _T("FLT_STACK_CHECK") },
+      { EXCEPTION_FLT_UNDERFLOW, _T("Floating point underflow") },
+      { EXCEPTION_ILLEGAL_INSTRUCTION, _T("Illegal instruction") },
+      { EXCEPTION_IN_PAGE_ERROR, _T("Page error") },
+      { EXCEPTION_INT_DIVIDE_BY_ZERO, _T("Divide by zero") },
+      { EXCEPTION_INT_OVERFLOW, _T("Integer overflow") },
+      { EXCEPTION_INVALID_DISPOSITION, _T("Invalid disposition") },
+      { EXCEPTION_NONCONTINUABLE_EXCEPTION, _T("Non-continuable exception") },
+      { EXCEPTION_PRIV_INSTRUCTION, _T("Priveledged instruction") },
+      { EXCEPTION_SINGLE_STEP, _T("Single step") },
+      { EXCEPTION_STACK_OVERFLOW, _T("Stack overflow") },
+      { 0, NULL }
+   };
+   int i;
+
+   for(i = 0; exceptionList[i].name != NULL; i++)
+      if (code == exceptionList[i].code)
+         return exceptionList[i].name;
+
+   return _T("Unknown");
+}
+
+
+//
+// Default exception handler for console applications
+//
+
+void LIBNETXMS_EXPORTABLE SEHDefaultConsoleHandler(EXCEPTION_POINTERS *pInfo)
+{
+       _tprintf(_T("EXCEPTION: %08X (%s) at %08X\n"),
+            pInfo->ExceptionRecord->ExceptionCode,
+                               SEHExceptionName(pInfo->ExceptionRecord->ExceptionCode),
+                               pInfo->ExceptionRecord->ExceptionAddress);
+#ifdef _X86_
+   _tprintf(_T("\nRegister information:\n")
+                               _T("  eax=%08X  ebx=%08X  ecx=%08X  edx=%08X\n")
+            _T("  esi=%08X  edi=%08X  ebp=%08X  esp=%08X\n")
+            _T("  cs=%04X  ds=%04X  es=%04X  ss=%04X  fs=%04X  gs=%04X  flags=%08X\n"),
+            pInfo->ContextRecord->Eax, pInfo->ContextRecord->Ebx,
+                               pInfo->ContextRecord->Ecx, pInfo->ContextRecord->Edx,
+                               pInfo->ContextRecord->Esi, pInfo->ContextRecord->Edi,
+            pInfo->ContextRecord->Ebp, pInfo->ContextRecord->Esp,
+            pInfo->ContextRecord->SegCs, pInfo->ContextRecord->SegDs,
+                               pInfo->ContextRecord->SegEs, pInfo->ContextRecord->SegSs,
+                               pInfo->ContextRecord->SegFs, pInfo->ContextRecord->SegGs,
+            pInfo->ContextRecord->EFlags);
+#endif
+
+       _tprintf("\nCall stack:\n");
+       NxStackWalker sw(NxStackWalker::StackWalkOptions::OptionsAll, NULL, GetCurrentProcessId(), GetCurrentProcess());
+       sw.ShowCallstack(GetCurrentThread(), pInfo->ContextRecord);
+
+       _tprintf(_T("\nPROCESS TERMINATED\n"));
+}
+
+
+//
+// Show call stack
+//
+
+void LIBNETXMS_EXPORTABLE SEHShowCallStack(CONTEXT *pCtx)
+{
+       NxStackWalker sw(NxStackWalker::StackWalkOptions::OptionsAll, NULL, GetCurrentProcessId(), GetCurrentProcess());
+       sw.ShowCallstack(GetCurrentThread(), pCtx);
+}
+
+
+//
+// Exception handler
+//
+
+static int ExceptionHandler(EXCEPTION_POINTERS *pInfo)
+{
+       if (m_pfExceptionHandler != NULL)
+       {
+               // Only one exception handler can be executed at a time
+               // We will never release mutex because __except block
+               // will call ExitProcess anyway and we want to log only first
+               // exception in case of multiple simultaneous exceptions
+               WaitForSingleObject(m_hExceptionLock, INFINITE);
+               m_pfExceptionHandler(pInfo);
+               return EXCEPTION_EXECUTE_HANDLER;
+       }
+       return EXCEPTION_CONTINUE_SEARCH;
+}
+
+
+//
+// Starter for threads
+//
+
+THREAD_RESULT LIBNETXMS_EXPORTABLE THREAD_CALL SEHThreadStarter(void *pArg)
+{
+       __try
+       {
+               ((THREAD_START_DATA *)pArg)->start_address(((THREAD_START_DATA *)pArg)->args);
+       }
+       __except(ExceptionHandler((EXCEPTION_POINTERS *)_exception_info()))
+       {
+               ExitProcess(99);
+       }
+       return THREAD_OK;
+}
index 684149e..c3d00da 100644 (file)
@@ -55,11 +55,11 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libnetxms.lib ws2_32.lib /nologo /version:0.1 /dll /machine:I386 /libpath:"..\libnetxms\Release"
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libnetxms.lib ws2_32.lib /nologo /version:0.1 /dll /debug /machine:I386 /pdbtype:sept /libpath:"..\libnetxms\Release"
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Release\libnxmap.dll C:\NetXMS\bin
+PostBuild_Cmds=copy Release\libnxmap.dll C:\NetXMS\bin copy Release\libnxmap.pdb C:\NetXMS\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "libnxmap - Win32 Debug"
@@ -89,7 +89,7 @@ LINK32=link.exe
 # ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libnetxms.lib ws2_32.lib /nologo /version:0.1 /dll /debug /machine:I386 /pdbtype:sept /libpath:"..\libnetxms\Debug"
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
-PostBuild_Cmds=copy Debug\libnxmap.dll ..\..\bin
+PostBuild_Cmds=copy Debug\libnxmap.dll ..\..\bin       copy Debug\libnxmap.pdb ..\..\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "libnxmap - Win32 Debug UNICODE"
index 0653d86..ee93e04 100644 (file)
@@ -55,11 +55,11 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libnetxms.lib ws2_32.lib /nologo /dll /machine:I386 /libpath:"..\libnetxms\Release"
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libnetxms.lib ws2_32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept /libpath:"..\libnetxms\Release"
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Release\libnxsl.dll C:\NetXMS\bin
+PostBuild_Cmds=copy Release\libnxsl.dll C:\NetXMS\bin  copy Release\libnxsl.pdb C:\NetXMS\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "libnxsl - Win32 Debug"
@@ -90,7 +90,7 @@ LINK32=link.exe
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Debug\libnxsl.dll ..\..\bin
+PostBuild_Cmds=copy Debug\libnxsl.dll ..\..\bin        copy Debug\libnxsl.pdb ..\..\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "libnxsl - Win32 Release AMD64"
index d67e43c..5dfdd06 100644 (file)
@@ -57,11 +57,11 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libnetxms.lib zlib1.lib /nologo /version:0.1 /dll /machine:I386 /libpath:"..\libnetxms\Release"
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libnetxms.lib zlib1.lib /nologo /version:0.1 /dll /debug /machine:I386 /pdbtype:sept /libpath:"..\libnetxms\Release"
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Release\libnxsnmp.dll C:\NetXMS\bin
+PostBuild_Cmds=copy Release\libnxsnmp.dll C:\NetXMS\bin        copy Release\libnxsnmp.pdb C:\NetXMS\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "libnxsnmp - Win32 Debug"
@@ -92,7 +92,7 @@ LINK32=link.exe
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Debug\libnxsnmp.dll ..\..\bin
+PostBuild_Cmds=copy Debug\libnxsnmp.dll ..\..\bin      copy Debug\libnxsnmp.pdb ..\..\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "libnxsnmp - Win32 Release AMD64"
index 15c0fb1..bf03b8e 100644 (file)
@@ -1,6 +1,7 @@
+/* $Id: config.cpp,v 1.45 2007-02-09 17:31:57 victor Exp $ */
 /* 
-** Project X - Network Management System
-** Copyright (C) 2003 Victor Kirhenshtein
+** NetXMS - Network Management System
+** Copyright (C) 2003, 2004, 2005, 2006, 2007 Victor Kirhenshtein
 **
 ** This program is free software; you can redistribute it and/or modify
 ** it under the terms of the GNU General Public License as published by
@@ -16,7 +17,7 @@
 ** along with this program; if not, write to the Free Software
 ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 **
-** $module: config.cpp
+** File: config.cpp
 **
 **/
 
@@ -38,12 +39,14 @@ static TCHAR m_szCodePage[256] = ICONV_DEFAULT_CODEPAGE;
 static NX_CFG_TEMPLATE m_cfgTemplate[] =
 {
    { "CodePage", CT_STRING, 0, 0, 256, 0, m_szCodePage },
+   { "CreateCrashDumps", CT_BOOLEAN, 0, 0, AF_CATCH_EXCEPTIONS, 0, &g_dwFlags },
    { "DBDriver", CT_STRING, 0, 0, MAX_PATH, 0, g_szDbDriver },
    { "DBDrvParams", CT_STRING, 0, 0, MAX_PATH, 0, g_szDbDrvParams },
    { "DBLogin", CT_STRING, 0, 0, MAX_DB_LOGIN, 0, g_szDbLogin },
    { "DBName", CT_STRING, 0, 0, MAX_DB_NAME, 0, g_szDbName },
    { "DBPassword", CT_STRING, 0, 0, MAX_DB_PASSWORD, 0, g_szDbPassword },
    { "DBServer", CT_STRING, 0, 0, MAX_PATH, 0, g_szDbServer },
+   { "DumpDirectory", CT_STRING, 0, 0, MAX_PATH, 0, g_szDumpDir },
    { "LogFailedSQLQueries", CT_BOOLEAN, 0, 0, AF_LOG_SQL_ERRORS, 0, &g_dwFlags },
    { "LogFile", CT_STRING, 0, 0, MAX_PATH, 0, g_szLogFile },
    { "", CT_END_OF_LIST, 0, 0, 0, 0, NULL }
index 97779bb..7b08898 100644 (file)
@@ -74,6 +74,7 @@ THREAD_RESULT THREAD_CALL SyslogDaemon(void *pArg);
 
 char NXCORE_EXPORTABLE g_szConfigFile[MAX_PATH] = DEFAULT_CONFIG_FILE;
 char NXCORE_EXPORTABLE g_szLogFile[MAX_PATH] = DEFAULT_LOG_FILE;
+char NXCORE_EXPORTABLE g_szDumpDir[MAX_PATH] = DEFAULT_DUMP_DIR;
 #ifndef _WIN32
 char NXCORE_EXPORTABLE g_szPIDFile[MAX_PATH] = "/var/run/netxmsd.pid";
 #endif
index a69594d..222babd 100644 (file)
@@ -55,11 +55,11 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
-# ADD LINK32 minidump.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libnetxms.lib libnxsrv.lib libnxsnmp.lib iphlpapi.lib libeay32.lib version.lib psapi.lib libnxsl.lib libnxmap.lib /nologo /dll /machine:I386 /libpath:"..\..\libnetxms\Release" /libpath:"..\..\libnxsnmp\Release" /libpath:"..\libnxsrv\Release" /libpath:"..\..\libnxsl\Release" /libpath:"..\..\libnxmap\Release"
+# ADD LINK32 minidump.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libnetxms.lib libnxsrv.lib libnxsnmp.lib iphlpapi.lib libeay32.lib version.lib psapi.lib libnxsl.lib libnxmap.lib /nologo /dll /debug /machine:I386 /pdbtype:sept /libpath:"..\..\libnetxms\Release" /libpath:"..\..\libnxsnmp\Release" /libpath:"..\libnxsrv\Release" /libpath:"..\..\libnxsl\Release" /libpath:"..\..\libnxmap\Release"
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Release\nxcore.dll C:\NetXMS\bin
+PostBuild_Cmds=copy Release\nxcore.dll C:\NetXMS\bin   copy Release\nxcore.pdb C:\NetXMS\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "nxcore - Win32 Debug"
@@ -90,7 +90,7 @@ LINK32=link.exe
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Debug\nxcore.dll ..\..\..\bin
+PostBuild_Cmds=copy Debug\nxcore.dll ..\..\..\bin      copy Debug\nxcore.pdb ..\..\..\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "nxcore - Win32 Release AMD64"
index 93b70e9..b77e9cc 100644 (file)
@@ -666,6 +666,7 @@ void DumpProcess(void);
 
 extern char NXCORE_EXPORTABLE g_szConfigFile[];
 extern char NXCORE_EXPORTABLE g_szLogFile[];
+extern char NXCORE_EXPORTABLE g_szDumpDir[];
 #ifndef _WIN32
 extern char NXCORE_EXPORTABLE g_szPIDFile[];
 #endif
index 077456d..cf81f51 100644 (file)
@@ -56,6 +56,7 @@
 # define DEFAULT_SHELL         "cmd.exe"
 # define DEFAULT_LOG_FILE      "C:\\NetXMS.log"
 # define DEFAULT_DATA_DIR      "C:\\NetXMS\\var"
+# define DEFAULT_DUMP_DIR      "C:\\"
 
 # define DDIR_MIBS             "\\mibs"
 # define DDIR_IMAGES           "\\images"
@@ -76,6 +77,7 @@
 
 # define DEFAULT_LOG_FILE      DATADIR"/log/netxmsd.log"
 # define DEFAULT_DATA_DIR      DATADIR
+# define DEFAULT_DUMP_DIR      "/"
 
 # define DDIR_MIBS             "/mibs"
 # define DDIR_IMAGES           "/images"
 #define AF_DEBUG_OBJECTS                  0x00040000
 #define AF_DEBUG_ALL                      0x0006FF00
 #define AF_RESOLVE_NODE_NAMES             0x00100000
+#define AF_CATCH_EXCEPTIONS                                    0x00200000
 #define AF_DB_LOCKED                      0x01000000
 #define AF_ENABLE_MULTIPLE_DB_CONN        0x02000000
 #define AF_DB_CONNECTION_LOST             0x04000000
index 24b03af..1b38013 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: agent.cpp,v 1.49 2007-01-14 14:17:57 victor Exp $ */
+/* $Id: agent.cpp,v 1.50 2007-02-09 17:31:57 victor Exp $ */
 /* 
 ** NetXMS - Network Management System
 ** Server Library
@@ -200,6 +200,7 @@ void AgentConnection::ReceiverThread(void)
    pDecryptionBuffer = (BYTE *)malloc(RECEIVER_BUFFER_SIZE);
 #endif
 
+//char *p=NULL;*p=1;
    // Message receiving loop
    while(1)
    {
index 5bd2d9d..c89a957 100644 (file)
@@ -55,11 +55,12 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libnetxms.lib libnxsnmp.lib /nologo /version:0.1 /dll /machine:I386 /libpath:"..\..\libnetxms\Release" /libpath:"..\..\libnxsnmp\Release"
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libnetxms.lib libnxsnmp.lib /nologo /version:0.1 /dll /debug /machine:I386 /pdbtype:sept /libpath:"..\..\libnetxms\Release" /libpath:"..\..\libnxsnmp\Release"
+# SUBTRACT LINK32 /map
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Release\libnxsrv.dll C:\NetXMS\bin
+PostBuild_Cmds=copy Release\libnxsrv.dll C:\NetXMS\bin copy Release\libnxsrv.pdb C:\NetXMS\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "libnxsrv - Win32 Debug"
@@ -90,7 +91,7 @@ LINK32=link.exe
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Debug\libnxsrv.dll ..\..\..\bin
+PostBuild_Cmds=copy Debug\libnxsrv.dll ..\..\..\bin    copy Debug\libnxsrv.pdb ..\..\..\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "libnxsrv - Win32 Release AMD64"
index 100ad5a..1dc07d7 100644 (file)
@@ -1,8 +1,8 @@
-/* $Id: netxmsd.cpp,v 1.16 2006-11-21 11:35:30 victor Exp $ */
+/* $Id: netxmsd.cpp,v 1.17 2007-02-09 17:31:57 victor Exp $ */
 /* 
 ** NetXMS - Network Management System
 ** Server startup module
-** Copyright (C) 2003, 2004, 2005, 2006 NetXMS Team
+** Copyright (C) 2003, 2004, 2005, 2006, 2007 NetXMS Team
 **
 ** This program is free software; you can redistribute it and/or modify
 ** it under the terms of the GNU General Public License as published by
@@ -23,6 +23,7 @@
 **/
 
 #include "netxmsd.h"
+#include <dbghelp.h>
 
 
 //
@@ -84,6 +85,169 @@ static char help_text[]="NetXMS Server Version " NETXMS_VERSION_STRING "\n"
 
 
 //
+// Windows exception handling
+// ****************************************************
+//
+
+#ifdef _WIN32
+
+
+//
+// Static data
+//
+
+static FILE *m_pExInfoFile = NULL;
+
+
+//
+// Writer for SEHShowCallStack()
+//
+
+static void ExceptionDataWriter(char *pszText)
+{
+       if (m_pExInfoFile != NULL)
+               fputs(pszText, m_pExInfoFile);
+}
+
+
+//
+// Exception handler
+//
+
+static void ExceptionHandler(EXCEPTION_POINTERS *pInfo)
+{
+       char szBuffer[MAX_PATH];
+       HANDLE hFile;
+       time_t t;
+       MINIDUMP_EXCEPTION_INFORMATION mei;
+       OSVERSIONINFO ver;
+   SYSTEM_INFO sysInfo;
+
+       t = time(NULL);
+
+       // Create info file
+       _snprintf(szBuffer, MAX_PATH, "%s\\netxmsd-%d-%u.info",
+                 g_szDumpDir, GetCurrentProcessId(), (DWORD)t);
+       m_pExInfoFile = fopen(szBuffer, "w");
+       if (m_pExInfoFile != NULL)
+       {
+               fprintf(m_pExInfoFile, "NETXMSD CRASH DUMP\n%s\n", ctime(&t));
+               fprintf(m_pExInfoFile, "EXCEPTION: %08X (%s) at %08X\n",
+                       pInfo->ExceptionRecord->ExceptionCode,
+                       SEHExceptionName(pInfo->ExceptionRecord->ExceptionCode),
+                       pInfo->ExceptionRecord->ExceptionAddress);
+
+               // NetXMS and OS version
+               ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+               GetVersionEx(&ver);
+               if (ver.dwMajorVersion == 5)
+               {
+                       switch(ver.dwMinorVersion)
+                       {
+                               case 0:
+                                       strcpy(szBuffer, "2000");
+                                       break;
+                               case 1:
+                                       strcpy(szBuffer, "XP");
+                                       break;
+                               case 2:
+                                       strcpy(szBuffer, "Server 2003");
+                                       break;
+                               default:
+                                       sprintf(szBuffer, "NT %d.%d", ver.dwMajorVersion, ver.dwMinorVersion);
+                                       break;
+                       }
+               }
+               else
+               {
+                       sprintf(szBuffer, "NT %d.%d", ver.dwMajorVersion, ver.dwMinorVersion);
+               }
+               fprintf(m_pExInfoFile, "\nNetXMS Server Version: " NETXMS_VERSION_STRING "\n"
+                                      "OS Version: Windows %s Build %d %s\n",
+                       szBuffer, ver.dwBuildNumber, ver.szCSDVersion);
+
+               // Processor architecture
+               fprintf(m_pExInfoFile, "Processor architecture: ");
+               GetSystemInfo(&sysInfo);
+               switch(sysInfo.wProcessorArchitecture)
+               {
+                       case PROCESSOR_ARCHITECTURE_INTEL:
+                               fprintf(m_pExInfoFile, "Intel x86\n");
+                               break;
+                       case PROCESSOR_ARCHITECTURE_MIPS:
+                               fprintf(m_pExInfoFile, "MIPS\n");
+                               break;
+                       case PROCESSOR_ARCHITECTURE_ALPHA:
+                               fprintf(m_pExInfoFile, "ALPHA\n");
+                               break;
+                       case PROCESSOR_ARCHITECTURE_PPC:
+                               fprintf(m_pExInfoFile, "PowerPC\n");
+                               break;
+                       case PROCESSOR_ARCHITECTURE_IA64:
+                               fprintf(m_pExInfoFile, "Intel IA-64\n");
+                               break;
+                       case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
+                               fprintf(m_pExInfoFile, "Intel x86 on Win64\n");
+                               break;
+                       case PROCESSOR_ARCHITECTURE_AMD64:
+                               fprintf(m_pExInfoFile, "AMD64 (Intel EM64T)\n");
+                               break;
+                       default:
+                               fprintf(m_pExInfoFile, "UNKNOWN\n");
+                               break;
+               }
+
+#ifdef _X86_
+               fprintf(m_pExInfoFile, "\nRegister information:\n"
+                       "  eax=%08X  ebx=%08X  ecx=%08X  edx=%08X\n"
+                       "  esi=%08X  edi=%08X  ebp=%08X  esp=%08X\n"
+                       "  cs=%04X  ds=%04X  es=%04X  ss=%04X  fs=%04X  gs=%04X  flags=%08X\n",
+                       pInfo->ContextRecord->Eax, pInfo->ContextRecord->Ebx,
+                       pInfo->ContextRecord->Ecx, pInfo->ContextRecord->Edx,
+                       pInfo->ContextRecord->Esi, pInfo->ContextRecord->Edi,
+                       pInfo->ContextRecord->Ebp, pInfo->ContextRecord->Esp,
+                       pInfo->ContextRecord->SegCs, pInfo->ContextRecord->SegDs,
+                       pInfo->ContextRecord->SegEs, pInfo->ContextRecord->SegSs,
+                       pInfo->ContextRecord->SegFs, pInfo->ContextRecord->SegGs,
+                       pInfo->ContextRecord->EFlags);
+#endif
+
+               fprintf(m_pExInfoFile, "\nCall stack:\n");
+               SEHShowCallStack(pInfo->ContextRecord);
+
+               fclose(m_pExInfoFile);
+       }
+
+       // Create minidump
+       _snprintf(szBuffer, MAX_PATH, "%s\\netxmsd-%d-%u.mdmp",
+                 g_szDumpDir, GetCurrentProcessId(), (DWORD)t);
+   hFile = CreateFile(szBuffer, GENERIC_WRITE, 0, NULL,
+                      CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+   if (hFile != INVALID_HANDLE_VALUE)
+   {
+               mei.ThreadId = GetCurrentThreadId();
+               mei.ExceptionPointers = pInfo;
+               mei.ClientPointers = FALSE;
+      MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile,
+                        MiniDumpNormal, &mei, NULL, NULL);
+      CloseHandle(hFile);
+   }
+
+       if (IsStandalone())
+       {
+               printf("\n\n*************************************************************\n"
+                      "EXCEPTION: %08X (%s) at %08X\nPROCESS TERMINATED",
+             pInfo->ExceptionRecord->ExceptionCode,
+             SEHExceptionName(pInfo->ExceptionRecord->ExceptionCode),
+             pInfo->ExceptionRecord->ExceptionAddress);
+       }
+}
+
+
+#endif /* _WIN32 */
+
+
+//
 // Execute command and wait
 //
 
@@ -344,6 +508,12 @@ int main(int argc, char *argv[])
       return 1;
    }
 
+       // Set exception handler
+#ifdef _WIN32
+       if (g_dwFlags & AF_CATCH_EXCEPTIONS)
+               SetExceptionHandler(ExceptionHandler, ExceptionDataWriter);
+#endif
+
    // Check database before start if requested
    if (g_bCheckDB)
    {
index cac1d49..4a962a5 100644 (file)
@@ -52,11 +52,11 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib nxcore.lib libnxsrv.lib /nologo /subsystem:console /machine:I386 /libpath:"..\core\Release" /libpath:"..\libnxsrv\Release"
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib nxcore.lib libnxsrv.lib dbghelp.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\core\Release" /libpath:"..\libnxsrv\Release"
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Release\netxmsd.exe C:\NetXMS\bin
+PostBuild_Cmds=copy Release\netxmsd.exe C:\NetXMS\bin  copy Release\netxmsd.pdb C:\NetXMS\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "netxmsd - Win32 Debug"
@@ -81,11 +81,11 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib nxcore.lib libnxsrv.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\core\Debug" /libpath:"..\libnxsrv\Debug"
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib nxcore.lib libnxsrv.lib dbghelp.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\core\Debug" /libpath:"..\libnxsrv\Debug"
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Debug\netxmsd.exe ..\..\..\bin
+PostBuild_Cmds=copy Debug\netxmsd.exe ..\..\..\bin     copy Debug\netxmsd.pdb ..\..\..\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "netxmsd - Win32 Release AMD64"
@@ -112,7 +112,7 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib nxcore.lib /nologo /subsystem:console /machine:I386 /libpath:"..\core\Release"
-# ADD LINK32 bufferoverflowU.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib nxcore.lib libnxsrv.lib /nologo /subsystem:console /machine:I386 /libpath:"..\core\Release64" /machine:AMD64
+# ADD LINK32 bufferoverflowU.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib nxcore.lib libnxsrv.lib dbghelp.lib /nologo /subsystem:console /machine:I386 /libpath:"..\core\Release64" /machine:AMD64
 # SUBTRACT LINK32 /pdb:none
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
@@ -144,7 +144,7 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib nxcore.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\core\Debug"
-# ADD LINK32 bufferoverflowU.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib nxcore.lib libnxsrv.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\core\Debug64" /machine:AMD64
+# ADD LINK32 bufferoverflowU.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib nxcore.lib libnxsrv.lib dbghelp.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\core\Debug64" /machine:AMD64
 # SUBTRACT LINK32 /pdb:none
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
index 39c439a..23b6f02 100644 (file)
@@ -208,6 +208,9 @@ int main(int argc, char *argv[])
    RSA *pServerKey = NULL;
 
    InitThreadLibrary();
+#ifdef _WIN32
+       SetExceptionHandler(SEHDefaultConsoleHandler, NULL);
+#endif
 
    // Parse command line
    opterr = 1;
index 664f75e..b5e9114 100644 (file)
@@ -50,11 +50,11 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libnetxms.lib libnxsrv.lib /nologo /version:0.1 /subsystem:console /machine:I386 /libpath:"..\..\..\libnetxms\Release" /libpath:"..\..\libnxsrv\Release"
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib libnetxms.lib libnxsrv.lib /nologo /version:0.1 /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\..\..\libnetxms\Release" /libpath:"..\..\libnxsrv\Release"
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy files
-PostBuild_Cmds=copy Release\nxget.exe C:\NetXMS\bin
+PostBuild_Cmds=copy Release\nxget.exe C:\NetXMS\bin    copy Release\nxget.pdb C:\NetXMS\bin
 # End Special Build Tool
 
 !ELSEIF  "$(CFG)" == "nxget - Win32 Debug"
@@ -83,7 +83,7 @@ LINK32=link.exe
 # Begin Special Build Tool
 SOURCE="$(InputPath)"
 PostBuild_Desc=Copy Files
-PostBuild_Cmds=copy Debug\nxget.exe ..\..\..\..\bin
+PostBuild_Cmds=copy Debug\nxget.exe ..\..\..\..\bin    copy Debug\nxget.pdb ..\..\..\..\bin
 # End Special Build Tool
 
 !ENDIF