summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRobert Griebl <robert.griebl@pelagicore.com>2020-02-06 18:43:19 +0100
committerRobert Griebl <robert.griebl@qt.io>2020-02-11 20:54:52 +0100
commit08143e670aea28fd6758fe8ae8186d1b66f6ab99 (patch)
tree4caee8c0397e0514d94e261cf9853aebeca4bddf
parentae18e41a739659fa46efe8891a049ad890958138 (diff)
Add a Windows crash handler for MSVC And MinGW
Backtraces are not supported on MinGW at the moment, because StackWalker doesn't compile due to a missing dbghelp import library. Also improved the async-safety of output functions. On the Linux side, I noticed a lot of dead-locks and crashes while generating the backtrace lately. In addition, the getOutputInformation kitchen-sink function has been split up a bit and moved to the logging.cpp where it logically belongs. Change-Id: I354c0e4e212a247338faddb6e15d8d0831852086 Reviewed-by: Dominik Holland <dominik.holland@qt.io>
-rw-r--r--3rdparty/stackwalker.pri2
-rw-r--r--3rdparty/stackwalker/LICENSE25
-rw-r--r--3rdparty/stackwalker/qt_attribution.json15
-rw-r--r--3rdparty/stackwalker/stackwalker.cpp1469
-rw-r--r--3rdparty/stackwalker/stackwalker.h255
-rw-r--r--3rdparty/stackwalker/stackwalker.pro26
-rw-r--r--application-manager.pro10
-rw-r--r--doc/configuration.qdoc6
-rw-r--r--doc/installation.qdoc12
-rw-r--r--qmake-features/am-config.prf3
-rw-r--r--src/common-lib/common-lib.pro3
-rw-r--r--src/common-lib/crashhandler.cpp753
-rw-r--r--src/common-lib/logging.cpp249
-rw-r--r--src/common-lib/logging.h17
-rw-r--r--src/common-lib/startuptimer.cpp14
-rw-r--r--src/common-lib/utilities.cpp169
-rw-r--r--src/common-lib/utilities.h2
-rw-r--r--src/crypto-lib/signature_win.cpp2
18 files changed, 2646 insertions, 386 deletions
diff --git a/3rdparty/stackwalker.pri b/3rdparty/stackwalker.pri
new file mode 100644
index 00000000..c77951b2
--- /dev/null
+++ b/3rdparty/stackwalker.pri
@@ -0,0 +1,2 @@
+
+QMAKE_USE_PRIVATE += stackwalker
diff --git a/3rdparty/stackwalker/LICENSE b/3rdparty/stackwalker/LICENSE
new file mode 100644
index 00000000..43fd8dba
--- /dev/null
+++ b/3rdparty/stackwalker/LICENSE
@@ -0,0 +1,25 @@
+BSD-2-Clause
+
+Copyright (c) 2005 - 2019, 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:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+2. 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.
+
+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 HOLDER 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.
diff --git a/3rdparty/stackwalker/qt_attribution.json b/3rdparty/stackwalker/qt_attribution.json
new file mode 100644
index 00000000..8a4adba4
--- /dev/null
+++ b/3rdparty/stackwalker/qt_attribution.json
@@ -0,0 +1,15 @@
+{
+ "Id": "stackwalker",
+ "Name": "StackWalker",
+ "QDocModule": "applicationmanager",
+ "QtUsage": "Automatically used in Qt ApplicationManager, if available. Configure with -config disable-stackwalker to avoid.",
+
+ "Description": "Walking the callstack in windows applications.",
+ "Homepage": "https://github.com/JochenKalmbach/StackWalker",
+ "Version": "2020-02-06",
+
+ "License": "BSD 2-clause \"Simplified\" License",
+ "LicenseId": "BSD-2-Clause",
+ "LicenseFile": "LICENSE",
+ "Copyright": "Copyright (C) 2005-2019 Jochen Kalmbach"
+}
diff --git a/3rdparty/stackwalker/stackwalker.cpp b/3rdparty/stackwalker/stackwalker.cpp
new file mode 100644
index 00000000..7008ac67
--- /dev/null
+++ b/3rdparty/stackwalker/stackwalker.cpp
@@ -0,0 +1,1469 @@
+/**********************************************************************
+ *
+ * StackWalker.cpp
+ * https://github.com/JochenKalmbach/StackWalker
+ *
+ * Old location: http://stackwalker.codeplex.com/
+ *
+ *
+ * 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 parameter)
+ * - 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 slightly corrected (<ORGANIZATION> replaced)
+ * 2009-11-01 v10 Moved to http://stackwalker.codeplex.com/
+ * 2009-11-02 v11 Now try to use IMAGEHLP_MODULE64_V3 if available
+ * 2010-04-15 v12 Added support for VS2010 RTM
+ * 2010-05-25 v13 Now using secure MyStrcCpy. Thanks to luke.simon:
+ * http://www.codeproject.com/KB/applications/leakfinder.aspx?msg=3477467#xx3477467xx
+ * 2013-01-07 v14 Runtime Check Error VS2010 Debug Builds fixed:
+ * http://stackwalker.codeplex.com/workitem/10511
+ *
+ *
+ * LICENSE (http://www.opensource.org/licenses/bsd-license.php)
+ *
+ * Copyright (c) 2005-2013, 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 "StackWalker.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <tchar.h>
+#include <windows.h>
+#pragma comment(lib, "version.lib") // for "VerQueryValue"
+#pragma warning(disable : 4826)
+
+
+// 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);
+
+// clang-format off
+#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;
+// clang-format on
+
+#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(dst, len, src) strcpy(dst, src)
+#define strncpy_s(dst, len, src, maxLen) strncpy(dst, len, src)
+#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;
+ strncpy_s(szDest, nMaxDestSize, szSrc, _TRUNCATE);
+ // INFO: _TRUNCATE will ensure that it is null-terminated;
+ // but with older compilers (<1400) it uses "strncpy" and this does not!)
+ 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 newest one from
+ TCHAR szTemp[4096];
+ // But before we 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 architecture:
+#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");
+ 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;
+
+#pragma pack(push, 8)
+ 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
+ CHAR LoadedImageName[256]; // symbol file name
+ // new elements: 07-Jun-2002
+ 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
+ };
+#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_V3* ModuleInfo);
+ tSGMI pSGMI;
+
+ // 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 retrieve 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);
+ }
+ }
+ }
+
+ // Retrieve some additional-infos about the module
+ IMAGEHLP_MODULE64_V3 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;
+ }
+ }
+ LPCSTR pdbName = Module.LoadedImageName;
+ if (Module.LoadedPdbName[0] != 0)
+ pdbName = Module.LoadedPdbName;
+ this->m_parent->OnLoadModule(img, mod, baseAddr, size, result, szSymType, pdbName,
+ 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_V3* pModuleInfo)
+ {
+ memset(pModuleInfo, 0, sizeof(IMAGEHLP_MODULE64_V3));
+ if (this->pSGMI == NULL)
+ {
+ SetLastError(ERROR_DLL_INIT_FAILED);
+ return FALSE;
+ }
+ // First try to use the larger ModuleInfo-Structure
+ pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V3);
+ 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_V3));
+ static bool s_useV3Version = true;
+ if (s_useV3Version)
+ {
+ if (this->pSGMI(hProcess, baseAddr, (IMAGEHLP_MODULE64_V3*)pData) != FALSE)
+ {
+ // only copy as much memory as is reserved...
+ memcpy(pModuleInfo, pData, sizeof(IMAGEHLP_MODULE64_V3));
+ pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V3);
+ free(pData);
+ return TRUE;
+ }
+ s_useV3Version = false; // to prevent unnecessary calls with the larger struct...
+ }
+
+ // could not retrieve the bigger structure, try with the smaller one (as defined in VC7.1)...
+ pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2);
+ memcpy(pData, pModuleInfo, sizeof(IMAGEHLP_MODULE64_V2));
+ if (this->pSGMI(hProcess, baseAddr, (IMAGEHLP_MODULE64_V3*)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 (strlen(szTemp) > 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 != 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_V3 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
+ // See: https://stackwalker.codeplex.com/discussions/446958
+#if _WIN32_WINNT <= 0x0501
+ // If we need to support XP, we need to use the "old way", because "GetThreadId" is not available!
+ if (hThread == GetCurrentThread())
+#else
+ if (GetThreadId(hThread) == GetCurrentThreadId())
+#endif
+ {
+ GET_CURRENT_CONTEXT_STACKWALKER_CODEPLEX(c, USED_CONTEXT_FLAGS);
+ }
+ else
+ {
+ SuspendThread(hThread);
+ memset(&c, 0, sizeof(CONTEXT));
+ c.ContextFlags = USED_CONTEXT_FLAGS;
+
+ // TODO: Detect if you want to get a thread context of a different process, which is running a different processor architecture...
+ // This does only work if we are x64 and the target process is x64 or x86;
+ // It cannot work, if this process is x64 and the target process is x64... this is not supported...
+ // See also: http://www.howzatt.demon.co.uk/articles/DebuggingInWin64.html
+ 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 supplied 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;
+ }
+
+ 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 StackWalker::ShowObject(LPVOID pObject)
+{
+ // Load modules if not done yet
+ if (m_modulesLoaded == FALSE)
+ this->LoadModules(); // ignore the result...
+
+ // Verify that the DebugHelp.dll was actually found
+ if (this->m_sw->m_hDbhHelp == NULL)
+ {
+ SetLastError(ERROR_DLL_INIT_FAILED);
+ return FALSE;
+ }
+
+ // SymGetSymFromAddr64() is required
+ if (this->m_sw->pSGSFA == NULL)
+ return FALSE;
+
+ // Show object info (SymGetSymFromAddr64())
+ DWORD64 dwAddress = DWORD64(pObject);
+ DWORD64 dwDisplacement = 0;
+ IMAGEHLP_SYMBOL64* pSym =
+ (IMAGEHLP_SYMBOL64*)malloc(sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN);
+ memset(pSym, 0, sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN);
+ pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
+ pSym->MaxNameLength = STACKWALK_MAX_NAMELEN;
+ if (this->m_sw->pSGSFA(this->m_hProcess, dwAddress, &dwDisplacement, pSym) == FALSE)
+ {
+ this->OnDbgHelpErr("SymGetSymFromAddr64", GetLastError(), dwAddress);
+ return FALSE;
+ }
+ // Object name output
+ this->OnOutput(pSym->Name);
+
+ free(pSym);
+ 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];
+ size_t maxLen = STACKWALK_MAX_NAMELEN;
+#if _MSC_VER >= 1400
+ maxLen = _TRUNCATE;
+#endif
+ if (fileVersion == 0)
+ _snprintf_s(buffer, maxLen, "%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, maxLen,
+ "%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);
+ }
+ buffer[STACKWALK_MAX_NAMELEN - 1] = 0; // be sure it is NULL terminated
+ OnOutput(buffer);
+}
+
+void StackWalker::OnCallstackEntry(CallstackEntryType eType, CallstackEntry& entry)
+{
+ CHAR buffer[STACKWALK_MAX_NAMELEN];
+ size_t maxLen = STACKWALK_MAX_NAMELEN;
+#if _MSC_VER >= 1400
+ maxLen = _TRUNCATE;
+#endif
+ 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, maxLen, "%p (%s): %s: %s\n", (LPVOID)entry.offset, entry.moduleName,
+ entry.lineFileName, entry.name);
+ }
+ else
+ _snprintf_s(buffer, maxLen, "%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];
+ size_t maxLen = STACKWALK_MAX_NAMELEN;
+#if _MSC_VER >= 1400
+ maxLen = _TRUNCATE;
+#endif
+ _snprintf_s(buffer, maxLen, "ERROR: %s, GetLastError: %d (Address: %p)\n", szFuncName, gle,
+ (LPVOID)addr);
+ buffer[STACKWALK_MAX_NAMELEN - 1] = 0;
+ OnOutput(buffer);
+}
+
+void StackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName)
+{
+ CHAR buffer[STACKWALK_MAX_NAMELEN];
+ size_t maxLen = STACKWALK_MAX_NAMELEN;
+#if _MSC_VER >= 1400
+ maxLen = _TRUNCATE;
+#endif
+ _snprintf_s(buffer, maxLen, "SymInit: Symbol-SearchPath: '%s', symOptions: %d, UserName: '%s'\n",
+ szSearchPath, symOptions, szUserName);
+ buffer[STACKWALK_MAX_NAMELEN - 1] = 0;
+ 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, maxLen, "OS-Version: %d.%d.%d (%s)\n", ver.dwMajorVersion,
+ ver.dwMinorVersion, ver.dwBuildNumber, ver.szCSDVersion);
+ buffer[STACKWALK_MAX_NAMELEN - 1] = 0;
+ OnOutput(buffer);
+ }
+#else
+ OSVERSIONINFOEXA ver;
+ ZeroMemory(&ver, sizeof(OSVERSIONINFOEXA));
+ ver.dwOSVersionInfoSize = sizeof(ver);
+#if _MSC_VER >= 1900
+#pragma warning(push)
+#pragma warning(disable : 4996)
+#endif
+ if (GetVersionExA((OSVERSIONINFOA*)&ver) != FALSE)
+ {
+ _snprintf_s(buffer, maxLen, "OS-Version: %d.%d.%d (%s) 0x%x-0x%x\n", ver.dwMajorVersion,
+ ver.dwMinorVersion, ver.dwBuildNumber, ver.szCSDVersion, ver.wSuiteMask,
+ ver.wProductType);
+ buffer[STACKWALK_MAX_NAMELEN - 1] = 0;
+ OnOutput(buffer);
+ }
+#if _MSC_VER >= 1900
+#pragma warning(pop)
+#endif
+#endif
+}
+
+void StackWalker::OnOutput(LPCSTR buffer)
+{
+ OutputDebugStringA(buffer);
+}
diff --git a/3rdparty/stackwalker/stackwalker.h b/3rdparty/stackwalker/stackwalker.h
new file mode 100644
index 00000000..0a004d96
--- /dev/null
+++ b/3rdparty/stackwalker/stackwalker.h
@@ -0,0 +1,255 @@
+#ifndef __STACKWALKER_H__
+#define __STACKWALKER_H__
+
+#if defined(_MSC_VER)
+
+/**********************************************************************
+ *
+ * StackWalker.h
+ *
+ *
+ *
+ * LICENSE (http://www.opensource.org/licenses/bsd-license.php)
+ *
+ * Copyright (c) 2005-2009, 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 _MSC_VER 1000,
+// so we need not to check the version (because we only support _MSC_VER >= 1100)!
+#pragma once
+
+#include <windows.h>
+
+#if _MSC_VER >= 1900
+#pragma warning(disable : 4091)
+#endif
+
+// 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 retrieved
+ // (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 above
+ RetrieveVerbose = 0xF,
+
+ // Generate a "good" symbol-search-path
+ SymBuildPath = 0x10,
+
+ // Also use the public Microsoft-Symbol-Server
+ SymUseSymSrv = 0x20,
+
+ // Contains all the above "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 = 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(),
+ const CONTEXT* context = NULL,
+ PReadProcessMemoryRoutine readMemoryFunction = NULL,
+ LPVOID pUserData = NULL // optional to identify some data in the 'readMemoryFunction'-callback
+ );
+
+ BOOL ShowObject(LPVOID pObject);
+
+#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
+ } CallstackEntryType;
+
+ 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;
+}; // class StackWalker
+
+// 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_STACKWALKER_CODEPLEX(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
+// clang-format off
+// The following should be enough for walking the callstack...
+#define GET_CURRENT_CONTEXT_STACKWALKER_CODEPLEX(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)
+// clang-format on
+#endif
+
+#else
+
+// The following is defined for x86 (XP and higher), x64 and IA64:
+#define GET_CURRENT_CONTEXT_STACKWALKER_CODEPLEX(c, contextFlags) \
+ do \
+ { \
+ memset(&c, 0, sizeof(CONTEXT)); \
+ c.ContextFlags = contextFlags; \
+ RtlCaptureContext(&c); \
+ } while (0);
+#endif
+
+#endif //defined(_MSC_VER)
+
+#endif // __STACKWALKER_H__
diff --git a/3rdparty/stackwalker/stackwalker.pro b/3rdparty/stackwalker/stackwalker.pro
new file mode 100644
index 00000000..19e68949
--- /dev/null
+++ b/3rdparty/stackwalker/stackwalker.pro
@@ -0,0 +1,26 @@
+requires(windows:msvc)
+
+TEMPLATE = lib
+TARGET = stackwalker
+
+load(am-config)
+
+CONFIG += \
+ static \
+ hide_symbols \
+ warn_off \
+ installed
+
+MODULE_INCLUDEPATH += $$PWD
+
+load(qt_helper_lib)
+
+QMAKE_CFLAGS += /D_CRT_SECURE_NO_WARNINGS
+
+INCLUDEPATH += $$PWD
+
+HEADERS += \
+ stackwalker.h
+
+SOURCES += \
+ stackwalker.cpp
diff --git a/application-manager.pro b/application-manager.pro
index 75bc665c..df058da1 100644
--- a/application-manager.pro
+++ b/application-manager.pro
@@ -52,6 +52,13 @@ linux:!android:!disable-libbacktrace:if(enable-libbacktrace|CONFIG(debug, debug|
check_libbacktrace = "no"
}
+windows:msvc:!disable-stackwalker:if(enable-stackwalker|CONFIG(debug, debug|release)|debug_and_release) {
+ check_stackwalker = "yes"
+ SUBDIRS += 3rdparty/stackwalker/stackwalker.pro
+} else {
+ check_stackwalker = "no"
+}
+
!tools-only: SUBDIRS += doc
load(qt_parts)
@@ -100,7 +107,8 @@ printConfigLine("Crypto backend", $$check_crypto, auto)
printConfigLine("SSDP support", $$yesNo(qtHaveModule(pssdp)), auto)
printConfigLine("Shellserver support", $$yesNo(qtHaveModule(pshellserver)), auto)
printConfigLine("Genivi support", $$yesNo(qtHaveModule(geniviextras)), auto)
-printConfigLine("libbacktrace support", $$check_libbacktrace, auto)
+unix:printConfigLine("libbacktrace support", $$check_libbacktrace, auto)
+windows:printConfigLine("StackWalker support", $$check_stackwalker, auto)
printConfigLine("Systemd workaround", $$yesNo(CONFIG(systemd-workaround)), auto)
printConfigLine("System libarchive", $$yesNo(config_libarchive:!no-system-libarchive), auto)
printConfigLine("System libyaml", $$yesNo(config_libyaml:!no-system-libyaml), auto)
diff --git a/doc/configuration.qdoc b/doc/configuration.qdoc
index 583ad6ec..1728a539 100644
--- a/doc/configuration.qdoc
+++ b/doc/configuration.qdoc
@@ -646,8 +646,10 @@ The following conditions are handled:
\row
\li \c printBacktrace
\li bool
- \li Tries to print a readable backtrace, using the primitive backtrace functionality from
- glibc, unless \c libbacktrace was enabled at configure time (default: true).
+ \li Tries to print a readable backtrace. On Linux, it uses the primitive backtrace
+ functionality from glibc, unless \c libbacktrace was enabled at configure time.
+ On Windows, backtraces are only printed if \c stackwalker was enabled at
+ configure time. (default: true).
\row
\li \c printQmlStack
\li bool
diff --git a/doc/installation.qdoc b/doc/installation.qdoc
index d6ba3be2..20b4a2ae 100644
--- a/doc/installation.qdoc
+++ b/doc/installation.qdoc
@@ -177,11 +177,19 @@ There are various options that can be given to \c qmake to tailor the build to s
\row
\li \c{-config enable-libbacktrace}
\li Enables building and linking against \c libbacktrace in the 3rdparty folder. This gives
- you readable backtraces on crash, but also increases the binary size slightly. For debug
- builds, this option is enabled by default.
+ you readable backtraces on Linux on crashes, but also increases the binary size slightly.
+ For debug builds, this option is enabled by default.
+\row
+ \li \c{-config enable-stackwalker}
+ \li Enables building and linking against \c stackwalker in the 3rdparty folder. This gives
+ you readable backtraces on Windows on crashes, but also increases the binary size slightly.
+ For debug builds, this option is enabled by default.
\row
\li \c{-config disable-libbacktrace}
\li Disables building and linking against \c libbacktrace in the 3rdparty folder.
+\row
+ \li \c{-config disable-stackwalker}
+ \li Disables building and linking against \c stackwalker in the 3rdparty folder.
\endtable
\section2 The Hardware ID
diff --git a/qmake-features/am-config.prf b/qmake-features/am-config.prf
index d115eb63..4edfc8fc 100644
--- a/qmake-features/am-config.prf
+++ b/qmake-features/am-config.prf
@@ -20,6 +20,7 @@ headless:DEFINES *= AM_HEADLESS
enable-widgets:DEFINES *= AM_ENABLE_WIDGETS
config_touchemulation:DEFINES += AM_ENABLE_TOUCH_EMULATION
linux:!android:!disable-libbacktrace:if(enable-libbacktrace|CONFIG(debug, debug|release)):DEFINES *= AM_USE_LIBBACKTRACE
+windows:msvc:!disable-stackwalker:if(enable-stackwalker|CONFIG(debug, debug|release)):DEFINES *= AM_USE_STACKWALKER
!force-single-process {
linux|macos {
@@ -54,7 +55,7 @@ linux|force-libcrypto:DEFINES *= AM_USE_LIBCRYPTO
!win32:load(am-coverage.prf)
-# Unlike MSVC, MingW does not add a dummy manifest, leading to UAC prompts on executable
+# Unlike MSVC, MinGW does not add a dummy manifest, leading to UAC prompts on executable
# filenames containing "bad" words like setup, install, update, patch, ...
# RC files cannot be compiled into static libs, so we just generate one for each app.
win32-g++*:equals(TEMPLATE, "app") {
diff --git a/src/common-lib/common-lib.pro b/src/common-lib/common-lib.pro
index 4d0e3efa..ed98d0ad 100644
--- a/src/common-lib/common-lib.pro
+++ b/src/common-lib/common-lib.pro
@@ -10,6 +10,8 @@ android:QT *= androidextras
qtHaveModule(dbus):QT *= dbus
qtHaveModule(qml):QT *= qml qml-private
+linux:LIBS += -ldl
+
versionAtLeast(QT.geniviextras.VERSION, 1.1.0) {
DEFINES += AM_GENIVIEXTRAS_LAZY_INIT
}
@@ -19,6 +21,7 @@ CONFIG -= create_cmake
include($$SOURCE_DIR/3rdparty/libyaml.pri)
contains(DEFINES, "AM_USE_LIBBACKTRACE"):include($$SOURCE_DIR/3rdparty/libbacktrace.pri)
+contains(DEFINES, "AM_USE_STACKWALKER"):include($$SOURCE_DIR/3rdparty/stackwalker.pri)
SOURCES += \
exception.cpp \
diff --git a/src/common-lib/crashhandler.cpp b/src/common-lib/crashhandler.cpp
index e1528a9c..5f1841b8 100644
--- a/src/common-lib/crashhandler.cpp
+++ b/src/common-lib/crashhandler.cpp
@@ -40,68 +40,48 @@
**
****************************************************************************/
-#include "crashhandler.h"
-#include "global.h"
-
-#if !defined(Q_OS_LINUX) || defined(Q_OS_ANDROID)
-
-QT_BEGIN_NAMESPACE_AM
-
-void CrashHandler::setCrashActionConfiguration(const QVariantMap &config)
-{
- Q_UNUSED(config)
-}
-
-void CrashHandler::setQmlEngine(QQmlEngine *engine)
-{
- Q_UNUSED(engine)
-}
-
-QT_END_NAMESPACE_AM
-
-#else
+#include <inttypes.h>
#if defined(QT_QML_LIB)
# include <QQmlEngine>
# include <QtQml/private/qv4engine_p.h>
#endif
-#include <cxxabi.h>
-#include <execinfo.h>
-#include <setjmp.h>
-#include <signal.h>
-#include <inttypes.h>
-#include <sys/syscall.h>
-#include <pthread.h>
-#include <stdio.h>
+#include "crashhandler.h"
+#include "global.h"
+#include "utilities.h"
+#include "logging.h"
-#if defined(AM_USE_LIBBACKTRACE)
-# include <libbacktrace/backtrace.h>
-# include <libbacktrace/backtrace-supported.h>
+#if defined(Q_OS_UNIX)
+# include<unistd.h>
+# if defined(Q_OS_MACOS)
+# define AM_PTHREAD_T_FMT "%p"
+# else
+# define AM_PTHREAD_T_FMT "%lx"
+# endif
+#elif defined(Q_OS_WINDOWS)
+# include <io.h>
+# if !defined(STDERR_FILENO)
+# define STDERR_FILENO _fileno(stderr)
+# endif
+# define write(a, b, c) _write(a, b, static_cast<unsigned int>(c))
#endif
-#include "unixsignalhandler.h"
-#include "logging.h"
-#include "utilities.h"
-#include "processtitle.h"
-
QT_BEGIN_NAMESPACE_AM
-enum PrintDestination { Console, Dlt };
-
static bool printBacktrace;
static bool printQmlStack;
-static bool useAnsiColor;
static bool dumpCore;
static int waitForGdbAttach;
static char *demangleBuffer;
static size_t demangleBufferSize;
-// this will make it run before all other static constructor functions
-static void initBacktrace() __attribute__((constructor(101)));
+static QByteArray *backtraceLineOut;
+static QByteArray *backtraceLineTmp;
+
+static QQmlEngine *qmlEngine;
-static Q_NORETURN void crashHandler(const char *why, int stackFramesToIgnore);
void CrashHandler::setCrashActionConfiguration(const QVariantMap &config)
{
@@ -111,14 +91,47 @@ void CrashHandler::setCrashActionConfiguration(const QVariantMap &config)
dumpCore = config.value(qSL("dumpCore"), dumpCore).toBool();
}
-#if defined(QT_QML_LIB)
-static QQmlEngine *qmlEngine;
void CrashHandler::setQmlEngine(QQmlEngine *engine)
{
+#if defined(QT_QML_LIB)
qmlEngine = engine;
-}
+#else
+ Q_UNUSED(engine)
#endif
+}
+
+#if defined(Q_OS_WINDOWS) || (defined(Q_OS_UNIX) && !defined(Q_OS_ANDROID))
+
+# if defined(Q_OS_UNIX)
+// this will make it run before all other static constructor functions
+static void initBacktrace() __attribute__((constructor(101)));
+
+static void initBacktraceUnix();
+
+# elif defined(Q_OS_WINDOWS) && defined(Q_CC_MSVC)
+// this will make it run before all other static constructor functions
+# pragma warning(push)
+# pragma warning(disable: 4074)
+# pragma init_seg(compiler)
+
+static void initBacktrace();
+static void initBacktraceWindows();
+
+static struct InitBacktrace
+{
+ InitBacktrace() { initBacktrace(); }
+} dummy;
+# pragma warning(pop)
+
+# elif defined(Q_OS_WINDOWS) && defined(Q_CC_MINGW)
+# include <cxxabi.h>
+// this will make it run before all other static constructor functions
+static void initBacktrace() __attribute__((constructor(101)));
+
+static void initBacktraceWindows();
+
+# endif
static void initBacktrace()
{
@@ -143,24 +156,172 @@ static void initBacktrace()
dumpCore = true;
waitForGdbAttach = 0;
- getOutputInformation(&useAnsiColor, nullptr, nullptr);
-
demangleBufferSize = 768;
demangleBuffer = static_cast<char *>(malloc(demangleBufferSize));
+ backtraceLineOut = new QByteArray();
+ backtraceLineOut->reserve(2 * int(demangleBufferSize));
+ backtraceLineTmp = new QByteArray();
+ backtraceLineTmp->reserve(32);
+
+ Console::init();
+
+# if defined(Q_OS_UNIX)
+ initBacktraceUnix();
+# elif defined(Q_OS_WINDOWS)
+ initBacktraceWindows();
+# endif
+}
+
+enum LogToDestination { Console = 0, Dlt = 1 };
+
+static void logMsg(LogToDestination logTo, const char *msg, int msgLen = -1)
+{
+ if (logTo == Console) {
+ write(STDERR_FILENO, msg, msgLen >= 0 ? size_t(msgLen) : strlen(msg));
+ write(STDERR_FILENO, "\n", 1);
+ } else if (logTo == Dlt) {
+ Logging::logToDlt(QtMsgType::QtFatalMsg, QMessageLogContext(), QLatin1String(msg, msgLen));
+ }
+}
+
+static void logMsgF(LogToDestination logTo, const char *format, ...) Q_ATTRIBUTE_FORMAT_PRINTF(2, 3);
+static void logMsgF(LogToDestination logTo, const char *format, ...)
+{
+ char buffer[512];
+ va_list arglist;
+ va_start(arglist, format);
+ int len = vsnprintf(buffer, sizeof(buffer), format, arglist);
+ va_end(arglist);
+ logMsg(logTo, buffer, qMin(len, int(sizeof(buffer)) - 1));
+}
+
+
+static void logBacktraceLine(LogToDestination logTo, int level, const char *symbol,
+ uintptr_t offset = 0, const char *file = nullptr, int line = -1)
+{
+ bool wantClickableUrl = (Console::isRunningInQtCreator && !Console::hasConsoleWindow);
+ bool forceNoColor = wantClickableUrl || (logTo != Console);
+
+ backtraceLineOut->clear();
+ backtraceLineTmp->setNum(level);
+ backtraceLineOut->append(4 - backtraceLineTmp->size(), ' ');
+ backtraceLineOut->append(*backtraceLineTmp);
+ backtraceLineOut->append(": ");
+ Console::colorize(*backtraceLineOut, Console::BrightFlag, forceNoColor);
+ backtraceLineOut->append(symbol ? symbol : "?");
+ Console::colorize(*backtraceLineOut, Console::Off, forceNoColor);
+ if (offset) {
+ backtraceLineTmp->setNum(static_cast<qulonglong>(offset), 16);
+
+ backtraceLineOut->append(" [");
+ Console::colorize(*backtraceLineOut, Console::Cyan, forceNoColor);
+ backtraceLineOut->append(*backtraceLineTmp);
+ Console::colorize(*backtraceLineOut, Console::Off, forceNoColor);
+ backtraceLineOut->append(']');
+ }
+ if (file) {
+ bool lineValid = (line > 0 && line <= 9999999);
+ if (lineValid || wantClickableUrl)
+ backtraceLineTmp->setNum(lineValid ? line : 0);
+
+ backtraceLineOut->append(" in ");
+ Console::colorize(*backtraceLineOut, Console::Magenta, forceNoColor);
+
+ static const char *filePrefix =
+# if defined(Q_OS_WINDOWS)
+ "file:///";
+# else
+ "file://";
+# endif
+
+ bool isFileUrl = (strncmp(file, filePrefix, sizeof(filePrefix) - 1) == 0);
+ if (!isFileUrl && wantClickableUrl)
+ backtraceLineOut->append(filePrefix);
+ backtraceLineOut->append((isFileUrl && !wantClickableUrl) ? file + sizeof(filePrefix) - 1 : file);
+ Console::colorize(*backtraceLineOut, Console::Off, forceNoColor);
+
+ if (lineValid || wantClickableUrl) {
+ backtraceLineOut->append(':');
+ Console::colorize(*backtraceLineOut, Console::BrightFlag | Console::Magenta, forceNoColor);
+ backtraceLineOut->append(*backtraceLineTmp);
+ Console::colorize(*backtraceLineOut, Console::Off, forceNoColor);
+ }
+ }
+
+ logMsg(logTo, backtraceLineOut->constData());
+}
+
+static void logQmlBacktrace(LogToDestination logTo)
+{
+# if defined(QT_QML_LIB)
+ if (printQmlStack && qmlEngine) {
+ const QV4::ExecutionEngine *qv4engine = qmlEngine->handle();
+ if (qv4engine) {
+ const QV4::StackTrace stackTrace = qv4engine->stackTrace();
+ if (stackTrace.size()) {
+ logMsg(logTo, "\n > QML backtrace:");
+ for (int frame = 0; frame < stackTrace.size(); ++frame) {
+ const auto &stackFrame = stackTrace.at(frame);
+ logBacktraceLine(logTo, frame, stackFrame.function.toLocal8Bit().constData(),
+ 0, stackFrame.source.toLocal8Bit().constData(), stackFrame.line);
+ }
+ } else {
+ logMsg(logTo, "\n > QML backtrace: empty");
+ }
+ }
+ }
+# endif
+}
+
+#endif // defined(Q_OS_WINDOWS) || (defined(Q_OS_UNIX) && !defined(Q_OS_ANDROID))
+
+QT_END_NAMESPACE_AM
+
+#if defined(Q_OS_UNIX) && !defined(Q_OS_ANDROID)
+
+# include <cxxabi.h>
+# include <execinfo.h>
+# include <setjmp.h>
+# include <signal.h>
+# include <sys/syscall.h>
+# include <pthread.h>
+# include <stdio.h>
+
+# if defined(AM_USE_LIBBACKTRACE)
+# include <libbacktrace/backtrace.h>
+# include <libbacktrace/backtrace-supported.h>
+# endif
+# if defined(Q_OS_LINUX)
+# include <dlfcn.h>
+# endif
+
+# include "unixsignalhandler.h"
+# include "processtitle.h"
+
+QT_BEGIN_NAMESPACE_AM
+
+static Q_NORETURN void crashHandler(const char *why, int stackFramesToIgnore);
+
+static void initBacktraceUnix()
+{
+# if defined(Q_OS_LINUX)
+ dlopen("libgcc_s.so.1", RTLD_GLOBAL | RTLD_LAZY);
+# endif
+
UnixSignalHandler::instance()->install(UnixSignalHandler::RawSignalHandler,
{ SIGFPE, SIGSEGV, SIGILL, SIGBUS, SIGPIPE, SIGABRT },
[](int sig) {
UnixSignalHandler::instance()->resetToDefault(sig);
- static char buffer[256];
+ char buffer[256];
snprintf(buffer, sizeof(buffer), "uncaught signal %d (%s)", sig, UnixSignalHandler::signalName(sig));
- // 6 means to remove 6 stack frames: this way the backtrace starts at the point where
+ // 8 means to remove 8 stack frames: this way the backtrace starts at the point where
// the signal reception interrupted the normal program flow
- crashHandler(buffer, 6);
+ crashHandler(buffer, 8);
});
std::set_terminate([]() {
- static char buffer [1024];
+ char buffer [1024];
auto type = abi::__cxa_current_exception_type();
if (!type) {
@@ -180,6 +341,10 @@ static void initBacktrace()
throw;
} catch (const std::exception &exc) {
snprintf(buffer, sizeof(buffer), "uncaught exception of type %s (%s)", typeName, exc.what());
+ } catch (const std::exception *exc) {
+ snprintf(buffer, sizeof(buffer), "uncaught exception of type %s (%s)", typeName, exc->what());
+ } catch (const char *exc) {
+ snprintf(buffer, sizeof(buffer), "uncaught exception of type 'const char *' (%s)", exc);
} catch (...) {
snprintf(buffer, sizeof(buffer), "uncaught exception of type %s", typeName);
}
@@ -189,36 +354,13 @@ static void initBacktrace()
});
}
-static void printMsgToConsole(const char *format, ...) Q_ATTRIBUTE_FORMAT_PRINTF(1, 2);
-static void printMsgToConsole(const char *format, ...)
+static void logCrashInfo(LogToDestination logTo, const char *why, int stackFramesToIgnore)
{
- va_list arglist;
- va_start(arglist, format);
- vfprintf(stderr, format, arglist);
- va_end(arglist);
- fputs("\n", stderr);
-}
-
-static void printMsgToDlt(const char *format, ...) Q_ATTRIBUTE_FORMAT_PRINTF(1, 2);
-static void printMsgToDlt(const char *format, ...)
-{
- va_list arglist;
- va_start(arglist, format);
- Logging::logToDlt(QtMsgType::QtFatalMsg, QMessageLogContext(), QString::vasprintf(format, arglist));
- va_end(arglist);
-}
-
-static void printCrashInfo(PrintDestination dest, const char *why, int stackFramesToIgnore)
-{
- using printMsgType = void (*)(const char *format, ...);
- static printMsgType printMsg;
- printMsg = (dest == Dlt) ? printMsgToDlt : printMsgToConsole;
-
const char *title = ProcessTitle::title();
char who[256];
if (!title) {
- int whoLen = readlink("/proc/self/exe", who, sizeof(who) -1);
- who[qMax(0, whoLen)] = '\0';
+ ssize_t whoLen = readlink("/proc/self/exe", who, sizeof(who) -1);
+ who[std::max(ssize_t(0), whoLen)] = '\0';
title = who;
}
@@ -231,100 +373,90 @@ static void printCrashInfo(PrintDestination dest, const char *why, int stackFram
else if (pthread_getname_np(pthreadId, threadName, sizeof(threadName)))
strcpy(threadName, "unknown");
- printMsg("\n*** process %s (%d) crashed ***", title, pid);
- printMsg("\n > why: %s", why);
- printMsg("\n > where: %s thread, TID: %d, pthread ID: %p", threadName, tid, pthreadId);
+ logMsgF(logTo, "\n*** process %s (%d) crashed ***", title, pid);
+ logMsgF(logTo, "\n > why: %s", why);
+ logMsgF(logTo, "\n > where: %s thread, TID: %ld, pthread ID: " AM_PTHREAD_T_FMT,
+ threadName, tid, pthreadId);
if (printBacktrace) {
-#if defined(AM_USE_LIBBACKTRACE) && defined(BACKTRACE_SUPPORTED)
+# if defined(AM_USE_LIBBACKTRACE) && defined(BACKTRACE_SUPPORTED)
struct btData
{
+ LogToDestination logTo;
backtrace_state *state;
int level;
};
- static auto printBacktraceLine = [](int level, const char *symbol, uintptr_t offset,
- const char *file = nullptr, int line = -1) {
- if (file) {
- printMsg(useAnsiColor ? " %3d: \x1b[1m%s\x1b[0m [\x1b[36m%" PRIxPTR "\x1b[0m]"
- " in \x1b[35m%s\x1b[0m:\x1b[35;1m%d\x1b[0m"
- : " %3d: %s [%" PRIxPTR "] in %s:%d", level, symbol, offset, file, line);
- } else {
- printMsg(useAnsiColor ? " %3d: \x1b[1m%s\x1b[0m [\x1b[36m%" PRIxPTR "\x1b[0m]"
- : " %3d: %s [%" PRIxPTR "]", level, symbol, offset);
- }
- };
-
static auto errorCallback = [](void *data, const char *msg, int errnum) {
- const char *fmt = " %3d: ERROR: %s (%d)\n";
- if (useAnsiColor)
- fmt = " %3d: \x1b[31;1mERROR: \x1b[0;1m%s (%d)\x1b[0m";
+ auto btdata = static_cast<btData *>(data);
- printMsg(fmt, static_cast<btData *>(data)->level, msg, errnum);
+ snprintf(demangleBuffer, demangleBufferSize, "ERROR: %s (%d)", msg, errnum);
+ logBacktraceLine(btdata->logTo, btdata->level, demangleBuffer);
};
- static auto syminfoCallback = [](void *data, uintptr_t pc, const char *symname, uintptr_t symval,
- uintptr_t symsize) {
+ static auto syminfoCallback = [](void *data, uintptr_t pc, const char *symname,
+ uintptr_t symval, uintptr_t symsize) {
Q_UNUSED(symval)
Q_UNUSED(symsize)
- int level = static_cast<btData *>(data)->level;
+ auto btdata = static_cast<btData *>(data);
+ const char *name = nullptr;
+
if (symname) {
int status;
demangleBuffer = abi::__cxa_demangle(symname, demangleBuffer, &demangleBufferSize, &status);
-
- if (status == 0 && *demangleBuffer)
- printBacktraceLine(level, demangleBuffer, pc);
- else
- printBacktraceLine(level, symname, pc);
- } else {
- printBacktraceLine(level, nullptr, pc);
+ name = (status == 0 && *demangleBuffer) ? demangleBuffer : symname;
}
+ logBacktraceLine(btdata->logTo, btdata->level, name, pc);
};
static auto fullCallback = [](void *data, uintptr_t pc, const char *filename, int lineno,
const char *function) -> int {
+ auto btdata = static_cast<btData *>(data);
+
if (function) {
int status;
demangleBuffer = abi::__cxa_demangle(function, demangleBuffer, &demangleBufferSize, &status);
- printBacktraceLine(static_cast<btData *>(data)->level,
- (status == 0 && *demangleBuffer) ? demangleBuffer : function,
- pc, filename ? filename : "<unknown>", lineno);
+ logBacktraceLine(btdata->logTo, btdata->level,
+ (status == 0 && *demangleBuffer) ? demangleBuffer : function,
+ pc, filename, lineno);
} else {
- backtrace_syminfo (static_cast<btData *>(data)->state, pc, syminfoCallback, errorCallback, data);
+ backtrace_syminfo(btdata->state, pc, syminfoCallback, errorCallback, data);
}
return 0;
};
static auto simpleCallback = [](void *data, uintptr_t pc) -> int {
- backtrace_pcinfo(static_cast<btData *>(data)->state, pc, fullCallback, errorCallback, data);
- static_cast<btData *>(data)->level++;
+ auto btdata = static_cast<btData *>(data);
+ backtrace_pcinfo(btdata->state, pc, fullCallback, errorCallback, data);
+ btdata->level++;
return 0;
};
struct backtrace_state *state = backtrace_create_state(nullptr, BACKTRACE_SUPPORTS_THREADS,
errorCallback, nullptr);
- printMsg("\n > backtrace:");
- btData data = { state, 0 };
+ logMsg(logTo, "\n > C++ backtrace:");
+ btData data = { logTo, state, 0 };
//backtrace_print(state, stackFramesToIgnore, stderr);
backtrace_simple(state, stackFramesToIgnore, simpleCallback, errorCallback, &data);
-#else // !defined(AM_USE_LIBBACKTRACE) && defined(BACKTRACE_SUPPORTED)
+
+# else // !defined(AM_USE_LIBBACKTRACE) && defined(BACKTRACE_SUPPORTED)
Q_UNUSED(stackFramesToIgnore);
void *addrArray[1024];
int addrCount = backtrace(addrArray, sizeof(addrArray) / sizeof(*addrArray));
if (!addrCount) {
- printMsg(" > no backtrace available");
+ logMsg(logTo, " > no backtrace available");
} else {
- char **symbols = backtrace_symbols(addrArray, addrCount);
//backtrace_symbols_fd(addrArray, addrCount, 2);
+ char **symbols = backtrace_symbols(addrArray, addrCount);
if (!symbols) {
- printMsg(" > no symbol names available");
+ logMsg(logTo, " > no symbol names available");
} else {
- printMsg("\n > backtrace:");
+ logMsg(logTo, "\n > backtrace:");
for (int i = 1; i < addrCount; ++i) {
char *function = nullptr;
char *offset = nullptr;
@@ -339,48 +471,27 @@ static void printCrashInfo(PrintDestination dest, const char *why, int stackFram
end = ptr;
}
+ const char *name = nullptr;
+
if (function && offset && end && (function != offset)) {
*offset = 0;
*end = 0;
int status;
demangleBuffer = abi::__cxa_demangle(function, demangleBuffer, &demangleBufferSize, &status);
-
- if (status == 0 && *demangleBuffer) {
- printMsg(" %3d: %s [+%s]", i, demangleBuffer, offset + 1);
- } else {
- printMsg(" %3d: %s [+%s]", i, function, offset + 1);
- }
- } else {
- printMsg(" %3d: %s", i, symbols[i]);
+ name = (status == 0 && *demangleBuffer) ? demangleBuffer : function;
+ } else {
+ name = symbols[i];
+ if (function && (function == offset))
+ *(function - 1) = 0;
}
+ logBacktraceLine(logTo, i, name, offset ? strtoull(offset + 1, nullptr, 16) : 0);
}
}
}
-#endif // defined(AM_USE_LIBBACKTRACE) && defined(BACKTRACE_SUPPORTED)
+# endif // defined(AM_USE_LIBBACKTRACE) && defined(BACKTRACE_SUPPORTED)
}
-
-#if defined(QT_QML_LIB)
- if (printQmlStack && qmlEngine) {
- const QV4::ExecutionEngine *qv4engine = qmlEngine->handle();
- if (qv4engine) {
- const QV4::StackTrace stackTrace = qv4engine->stackTrace();
- if (stackTrace.size()) {
- printMsg("\n > qml stack:");
- int frame = 0;
- for (const auto &stackFrame : stackTrace) {
- printMsg(useAnsiColor ? " %3d: \x1b[1m%s\x1b[0m in \x1b[35m%s\x1b[0m:\x1b[35;1m%d\x1b[0m"
- : " %3d: %s in %s:%d",
- frame, stackFrame.function.toLocal8Bit().constData(),
- stackFrame.source.toLocal8Bit().constData(), stackFrame.line);
- frame++;
- }
- } else {
- printMsg("\n > qml stack: empty");
- }
- }
- }
-#endif
+ logQmlBacktrace(logTo);
}
static void crashHandler(const char *why, int stackFramesToIgnore)
@@ -391,11 +502,11 @@ static void crashHandler(const char *why, int stackFramesToIgnore)
// 3) SIGINT, so that you can Ctrl+C the app if the crash handler ends up freezing
UnixSignalHandler::instance()->resetToDefault({ SIGFPE, SIGSEGV, SIGILL, SIGBUS, SIGPIPE, SIGABRT, SIGINT });
- printCrashInfo(Console, why, stackFramesToIgnore);
+ logCrashInfo(Console, why, stackFramesToIgnore);
if (waitForGdbAttach > 0) {
- fprintf(stderr, "\n > the process will be suspended for %d seconds and you can attach a debugger"
- " to it via\n\n gdb -p %d\n", waitForGdbAttach, getpid());
+ logMsgF(Console, "\n > the process will be suspended for %d seconds and you can attach a debugger"
+ " to it via\n\n gdb -p %d\n", waitForGdbAttach, getpid());
static jmp_buf jmpenv;
signal(SIGALRM, [](int) {
longjmp(jmpenv, 1);
@@ -408,22 +519,22 @@ static void crashHandler(const char *why, int stackFramesToIgnore)
sigaddset(&mask, SIGALRM);
sigsuspend(&mask);
} else {
- fprintf(stderr, "\n > no gdb attached\n");
+ logMsg(Console, "\n > no gdb attached\n");
}
}
if (Logging::deferredMessages()) {
- fprintf(stderr, "\n > Accumulated logging output\n");
+ logMsg(Console, "\n > Accumulated logging output\n");
Logging::completeSetup();
}
- if (Logging::isDltEnabled()) {
- useAnsiColor = false;
- printCrashInfo(Dlt, why, stackFramesToIgnore);
- }
+# if defined(Q_OS_LINUX)
+ if (Logging::isDltEnabled())
+ logCrashInfo(Dlt, why, stackFramesToIgnore);
+# endif
if (dumpCore) {
- fprintf(stderr, "\n > the process will be aborted (core dumped)\n\n");
+ logMsg(Console, "\n > the process will be aborted (core dumped)\n\n");
abort();
}
@@ -432,4 +543,322 @@ static void crashHandler(const char *why, int stackFramesToIgnore)
QT_END_NAMESPACE_AM
-#endif // !Q_OS_LINUX || defined(Q_OS_ANDROID)
+#elif defined(Q_OS_WINDOWS)
+
+# include <Windows.h>
+# include <DbgHelp.h>
+# if defined(AM_USE_STACKWALKER)
+# include <stackwalker.h>
+# endif
+
+QT_BEGIN_NAMESPACE_AM
+
+static DWORD mainThreadId = GetCurrentThreadId();
+
+# if defined(AM_USE_STACKWALKER)
+
+class AMStackWalker : public StackWalker
+{
+public:
+ AMStackWalker(LogToDestination logTo, int stackFramesToIgnore)
+ : StackWalker(RetrieveLine | RetrieveSymbol)
+ , logToDestination(logTo)
+ , ignoreUpToLevel(stackFramesToIgnore)
+ { }
+ void OnOutput(LPCSTR) override { }
+ void OnDbgHelpErr(LPCSTR, DWORD, DWORD64) override { }
+ void OnSymInit(LPCSTR, DWORD, LPCSTR) override { }
+ void OnLoadModule(LPCSTR, LPCSTR, DWORD64, DWORD, DWORD, LPCSTR, LPCSTR, ULONGLONG) override { }
+ void OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry) override
+ {
+ if (eType == firstEntry)
+ level = 0;
+ else
+ ++level;
+ if ((eType == lastEntry) || (entry.offset == 0) || (level < ignoreUpToLevel))
+ return;
+
+ const char *symbol = entry.undFullName[0] ? entry.undFullName
+ : entry.undName[0] ? entry.undName
+ : entry.name[0] ? entry.name
+ : nullptr;
+ const char *file = entry.lineFileName[0] ? entry.lineFileName : nullptr;
+
+ logBacktraceLine(logToDestination, level - ignoreUpToLevel, symbol, entry.offset,
+ file, entry.lineNumber);
+ }
+
+private:
+ LogToDestination logToDestination;
+ int level = 0;
+ int ignoreUpToLevel = 0;
+};
+
+# endif // defined(AM_USE_STACKWALKER)
+
+static void logCrashInfo(LogToDestination logTo, const char *why, int stackFramesToIgnore, CONTEXT *context)
+{
+ WCHAR title[256];
+ DWORD titleLen = sizeof(title) / sizeof(*title);
+ if (QueryFullProcessImageName(GetCurrentProcess(), /*PROCESS_NAME_NATIVE*/0, title, &titleLen)) {
+ title[qMax(DWORD(0), titleLen)] = '\0';
+ }
+
+ DWORD pid = GetCurrentProcessId();
+ DWORD tid = GetCurrentThreadId();
+ WCHAR threadName[256];
+ // Qt uses the the legacy RaiseException mechanism to attach the thread name instead of the
+ // modern setThreadDescription() call, but this name is only visible to debuggers.
+ if (tid == mainThreadId) {
+ wcscpy(threadName, L"main");
+ } else {
+ wcscpy(threadName, L"unknown");
+
+ // GetThreadDescription is only available from Windows 10, 1607 onwards, regardless of the
+ // SDK used to compile this code
+ typedef HRESULT(WINAPI* GetThreadDescriptionType)(HANDLE hThread, PWSTR *description);
+ if (auto GetThreadDescriptionFunc = reinterpret_cast<GetThreadDescriptionType>(
+ GetProcAddress(::GetModuleHandle(L"kernel32.dll"), "GetThreadDescription"))) {
+ WCHAR *desc = nullptr;
+ if (SUCCEEDED(GetThreadDescriptionFunc(GetCurrentThread(), &desc)))
+ wcscpy_s(threadName, sizeof(threadName) / sizeof(*threadName), desc);
+ }
+ }
+
+ logMsgF(logTo, "\n*** process %S (%lu) crashed ***", title, pid);
+ logMsgF(logTo, "\n > why: %s", why);
+ logMsgF(logTo, "\n > where: %S thread, TID: %lu", threadName, tid);
+
+ if (printBacktrace && context) {
+# if defined(AM_USE_STACKWALKER)
+ logMsg(logTo, "\n > C++ backtrace:");
+ AMStackWalker sw(logTo, stackFramesToIgnore);
+ sw.ShowCallstack(GetCurrentThread(), context);
+# else
+ logMsg(logTo, "\n > C++ backtrace: cannot be generated"
+# if defined(Q_CC_MSVC)
+ ", StackWalker is not enabled"
+# elif defined(Q_CC_MINGW)
+ ", MinGW is not supported"
+# endif
+ );
+ Q_UNUSED(context)
+ Q_UNUSED(stackFramesToIgnore)
+# endif // defined(AM_USE_STACKWALKER)
+ }
+ logQmlBacktrace(logTo);
+}
+
+
+# if defined(Q_CC_MSVC)
+// From Dr. Dobbs: https://www.drdobbs.com/visual-c-exception-handling-instrumentat/184416600
+// These types are known to the compiler without declaration.
+
+// This had been adapted for 64bit and 32bit platforms
+// all pointers are not real pointers on 64bit Windows, but 32bit offsets relative to HINSTANCE!
+
+struct _PMD
+{
+ qint32 mdisp;
+ qint32 pdisp;
+ qint32 vdisp;
+};
+
+// information of a type that can be caught by a catch block
+struct _s__CatchableType
+{
+ quint32 properties; // type properties bit flags: 1 - type is a pointer
+ quint32 /* type info * */ pType;
+ _PMD thisDisplacement; // displacement of this from the beginning of the object
+ qint32 sizeOrOffset; // size of the type
+ quint32 /* void (*)() */ copyFunction; // != 0 if the type has a copy constructor
+};
+
+// a counted array of the types that can be caught by a catch block
+struct _s__CatchableTypeArray
+{
+ qint32 nCatchableTypes;
+# pragma warning(push)
+# pragma warning(disable: 4200)
+ quint32 /* const _s__CatchableType * */ arrayOfCatchableTypes[];
+# pragma warning(pop)
+
+};
+
+// this structure holds the information about the exception object being thrown
+struct _s__ThrowInfo
+{
+ quint32 attributes; // 1: ptr to const obj / 2: ptr to volatile obj
+ quint32 /* void * */ pmfnUnwind; // exception object destructor
+ quint32 /* void * */ pForwardCompat;
+ // array of sub-types of the object or other types to which it could be implicitly cast.
+ // Used to find the matching catch block
+ const quint32 /* const _s__CatchableTypeArray * */ pCatchableTypeArray;
+};
+# endif // defined(Q_CC_MSVC)
+
+# define EXCEPTION_CPP_EXCEPTION 0xE06D7363 // internal MSVC value
+# define EXCEPTION_MINGW_EXCEPTION 0xE014e9aa // custom AM value
+
+static LONG WINAPI windowsExceptionFilter(EXCEPTION_POINTERS *ep)
+{
+ static char buffer [1024];
+ bool suppressBacktrace = false;
+ int stackFramesToIgnore = 0;
+
+ switch (ep->ExceptionRecord->ExceptionCode) {
+ case EXCEPTION_ACCESS_VIOLATION : strcpy(buffer, "access violation"); break;
+ case EXCEPTION_DATATYPE_MISALIGNMENT : strcpy(buffer, "datatype misalignment"); break;
+ case EXCEPTION_BREAKPOINT : strcpy(buffer, "breakpoint"); break;
+ case EXCEPTION_SINGLE_STEP : strcpy(buffer, "single step"); break;
+ case EXCEPTION_ARRAY_BOUNDS_EXCEEDED : strcpy(buffer, "array bounds exceeded"); break;
+ case EXCEPTION_FLT_DENORMAL_OPERAND : strcpy(buffer, "denormal float operand"); break;
+ case EXCEPTION_FLT_DIVIDE_BY_ZERO : strcpy(buffer, "float divide-by-zero"); break;
+ case EXCEPTION_FLT_INEXACT_RESULT : strcpy(buffer, "inexact float result"); break;
+ case EXCEPTION_FLT_INVALID_OPERATION : strcpy(buffer, "invalid float operation"); break;
+ case EXCEPTION_FLT_OVERFLOW : strcpy(buffer, "float overflow"); break;
+ case EXCEPTION_FLT_STACK_CHECK : strcpy(buffer, "float state check"); break;
+ case EXCEPTION_FLT_UNDERFLOW : strcpy(buffer, "float underflow"); break;
+ case EXCEPTION_INT_DIVIDE_BY_ZERO : strcpy(buffer, "integer divide-by-zero"); break;
+ case EXCEPTION_INT_OVERFLOW : strcpy(buffer, "integer overflow"); break;
+ case EXCEPTION_PRIV_INSTRUCTION : strcpy(buffer, "private instruction"); break;
+ case EXCEPTION_IN_PAGE_ERROR : strcpy(buffer, "in-page error"); break;
+ case EXCEPTION_ILLEGAL_INSTRUCTION : strcpy(buffer, "illegal instruction"); break;
+ case EXCEPTION_NONCONTINUABLE_EXCEPTION: strcpy(buffer, "noncontinuable exception"); break;
+ case EXCEPTION_STACK_OVERFLOW : strcpy(buffer, "stack overflow"); suppressBacktrace = true; break;
+ case EXCEPTION_INVALID_DISPOSITION : strcpy(buffer, "invalid disposition"); break;
+ case EXCEPTION_GUARD_PAGE : strcpy(buffer, "guard page"); break;
+ case EXCEPTION_INVALID_HANDLE : strcpy(buffer, "invalid handle"); break;
+# if defined(Q_CC_MINGW)
+ case EXCEPTION_MINGW_EXCEPTION: {
+ if ((ep->ExceptionRecord->NumberParameters == 1)
+ && (ep->ExceptionRecord->ExceptionInformation[0])) {
+ strcpy_s(buffer, sizeof(buffer),
+ reinterpret_cast<const char *>(ep->ExceptionRecord->ExceptionInformation[0]));
+ }
+ break;
+ }
+# elif defined(Q_CC_MSVC)
+ case EXCEPTION_CPP_EXCEPTION: {
+ // MSVC bug: std::current_exception is null, even though the standard says it shouldn't
+ // be in this situation (it even is null in a set_terminate() handler).
+ // So we have to use the compiler internal structure and functions to (a) get the type-name
+ // of the exception and to (b) re-throw it in order to print the what() of a std::exception
+ // derived instance.
+
+ // (a) get the type_info
+
+ std::type_info *type = nullptr;
+ bool is64bit = (sizeof(void *) == 8);
+ if (ep->ExceptionRecord->NumberParameters == (is64bit ? 4 : 3)) {
+ auto hInstance = (is64bit ? reinterpret_cast<char *>(ep->ExceptionRecord->ExceptionInformation[3])
+ : nullptr);
+
+ // since all "pointers" are 32bit values even on 64bit Windows, we have to add the
+ // hInstance segment pointer to each of the 32bit pointers to get a real 64bit address
+ if (!is64bit || hInstance) {
+ const auto *ti = reinterpret_cast<_s__ThrowInfo *>(ep->ExceptionRecord->ExceptionInformation[2]);
+ if (ti) {
+ auto cta = reinterpret_cast<_s__CatchableTypeArray *>(hInstance + ti->pCatchableTypeArray);
+ if (cta && (cta->nCatchableTypes > 0) && (cta->nCatchableTypes < 100)) {
+ auto ct = reinterpret_cast<_s__CatchableType *>(hInstance + cta->arrayOfCatchableTypes[0]);
+ if (ct)
+ type = reinterpret_cast<std::type_info *>(hInstance + ct->pType);
+ }
+ }
+ }
+ }
+ const char *typeName = type ? type->name() : "<unknown type>";
+
+ // (b) re-throw and catch the exception
+ try {
+ RaiseException(EXCEPTION_CPP_EXCEPTION,
+ EXCEPTION_NONCONTINUABLE,
+ ep->ExceptionRecord->NumberParameters,
+ ep->ExceptionRecord->ExceptionInformation);
+ } catch (const std::exception &exc) {
+ snprintf(buffer, sizeof(buffer), "uncaught exception of type %s (%s)", typeName, exc.what());
+ } catch (const std::exception *exc) {
+ snprintf(buffer, sizeof(buffer), "uncaught exception of type %s (%s)", typeName, exc->what());
+ } catch (const char *exc) {
+ snprintf(buffer, sizeof(buffer), "uncaught exception of type 'const char *' (%s)", exc);
+ } catch (...) {
+ snprintf(buffer, sizeof(buffer), "uncaught exception of type %s", typeName);
+ }
+
+ stackFramesToIgnore = 2; // CxxThrowException + RaiseException
+ break;
+ }
+# endif // defined(Q_CC_MSVC)
+ default:
+ snprintf(buffer, sizeof(buffer), "unknown Windows exception, code: %lx",
+ ep->ExceptionRecord->ExceptionCode);
+ break;
+ }
+
+ logCrashInfo(Console, buffer, stackFramesToIgnore,
+ suppressBacktrace ? nullptr : ep->ContextRecord);
+
+ if (Logging::deferredMessages()) {
+ logMsg(Console, "\n > Accumulated logging output\n");
+ Logging::completeSetup();
+ }
+
+ TerminateProcess(GetCurrentProcess(), ep->ExceptionRecord->ExceptionCode);
+ return EXCEPTION_EXECUTE_HANDLER;
+}
+
+static void initBacktraceWindows()
+{
+ // create a "process group", so that child process are automatically killed if this process dies
+ HANDLE hJob = CreateJobObject(nullptr, nullptr);
+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits;
+ memset(&limits, 0, sizeof(limits));
+ limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+ SetInformationJobObject(hJob, JobObjectExtendedLimitInformation, &limits, sizeof(limits));
+ AssignProcessToJobObject(hJob, GetCurrentProcess());
+
+ // handle Windows' Structured Exceptions
+ SetUnhandledExceptionFilter(windowsExceptionFilter);
+
+#if defined(Q_CC_MINGW)
+ // MinGW does handle the exceptions like gcc does on Unix, instead of using a structured
+ // Windows exception, so we have to adapt:
+
+ std::set_terminate([]() {
+ char buffer [1024];
+
+ auto type = abi::__cxa_current_exception_type();
+ if (!type) {
+ strcpy(buffer, "terminate was called although no exception was thrown");
+ } else {
+ const char *typeName = type->name();
+ if (typeName) {
+ int status;
+ demangleBuffer = abi::__cxa_demangle(typeName, demangleBuffer, &demangleBufferSize, &status);
+ if (status == 0 && *demangleBuffer) {
+ typeName = demangleBuffer;
+ }
+ }
+ try {
+ throw;
+ } catch (const std::exception &exc) {
+ snprintf(buffer, sizeof(buffer), "uncaught exception of type %s (%s)", typeName, exc.what());
+ } catch (const std::exception *exc) {
+ snprintf(buffer, sizeof(buffer), "uncaught exception of type %s (%s)", typeName, exc->what());
+ } catch (const char *exc) {
+ snprintf(buffer, sizeof(buffer), "uncaught exception of type 'const char *' (%s)", exc);
+ } catch (...) {
+ snprintf(buffer, sizeof(buffer), "uncaught exception of type %s", typeName);
+ }
+ }
+ ULONG_PTR args[1] = { reinterpret_cast<ULONG_PTR>(buffer) };
+ RaiseException(EXCEPTION_MINGW_EXCEPTION, EXCEPTION_NONCONTINUABLE, 1, args);
+ });
+# endif // defined(Q_CC_MINGW)
+}
+
+QT_END_NAMESPACE_AM
+
+#endif // defined(Q_OS_WINDOWS)
+
diff --git a/src/common-lib/logging.cpp b/src/common-lib/logging.cpp
index c59b0fc9..d9d8eb1d 100644
--- a/src/common-lib/logging.cpp
+++ b/src/common-lib/logging.cpp
@@ -41,17 +41,40 @@
**
****************************************************************************/
+#if defined(_WIN32) && (_WIN32_WINNT-0 < _WIN32_WINNT_VISTA)
+// needed for QueryFullProcessImageNameW
+# undef WINVER
+# undef _WIN32_WINNT
+# define WINVER _WIN32_WINNT_VISTA
+# define _WIN32_WINNT _WIN32_WINNT_VISTA
+#endif
+
#include <QThreadStorage>
#include <QAtomicInteger>
+#include <QCoreApplication>
#include "global.h"
#include "logging.h"
#include "utilities.h"
+#include "unixsignalhandler.h"
#include <stdio.h>
+
#if defined(Q_OS_WIN)
+# include <Windows.h>
+# include <io.h>
+# include <QOperatingSystemVersion>
+# include <QThread>
+
Q_CORE_EXPORT void qWinMsgHandler(QtMsgType t, const char* str);
-# include <windows.h>
+#else
+# include <unistd.h>
+# include <sys/ioctl.h>
+# include <termios.h>
+# include <signal.h>
+# if defined(Q_OS_MACOS)
+# include <libproc.h>
+# endif
#endif
#if defined(Q_OS_ANDROID)
# include <QCoreApplication>
@@ -233,10 +256,8 @@ static void colorLogToStderr(QtMsgType msgType, const QMessageLogContext &contex
out.reserve(512);
out.resize(0);
- int consoleWidth = -1;
- bool ansiColorSupport = false;
- bool runningInCreator = false;
- getOutputInformation(&ansiColorSupport, &runningInCreator, &consoleWidth);
+ Console::init();
+ int consoleWidth = Console::width();
// Find out, if we have a valid code location and prepare the output strings
const char *filename = nullptr;
@@ -262,32 +283,9 @@ static void colorLogToStderr(QtMsgType msgType, const QMessageLogContext &contex
linenumber[linenumberLength] = 0;
}
- enum ConsoleColor { Off = 0, Black, Red, Green, Yellow, Blue, Magenta, Cyan, Gray, BrightFlag = 0x80 };
-
- // helper function to append ANSI color codes to a string
- static auto color = [ansiColorSupport](QByteArray &out, int consoleColor) -> void {
- static const char *ansiColors[] = {
- "\x1b[1m", // bright
- "\x1b[0m", // off
- "\x1b[30m", // black
- "\x1b[31m", // red
- "\x1b[32m", // green
- "\x1b[33m", // yellow
- "\x1b[34m", // blue
- "\x1b[35m", // magenta
- "\x1b[36m", // cyan
- "\x1b[37m" // gray
- };
-
- if (!ansiColorSupport)
- return;
- if (consoleColor & BrightFlag)
- out.append(ansiColors[0]);
- out.append(ansiColors[1 + (consoleColor & ~BrightFlag)]);
- };
-
static const char *msgTypeStr[] = { "DBG ", "WARN", "CRIT", "FATL", "INFO" };
- static const ConsoleColor msgTypeColor[] = { Green, Yellow, Red, Magenta, Blue };
+ static const Console::Color msgTypeColor[] = { Console::Green, Console::Yellow, Console::Red,
+ Console::Magenta, Console::Blue };
int categoryLength = int(qstrlen(context.category));
QByteArray msg = message.toLocal8Bit(); // sadly this allocates, but there's no other way in Qt
@@ -295,23 +293,23 @@ static void colorLogToStderr(QtMsgType msgType, const QMessageLogContext &contex
int outLength = 10 + int(qstrlen(context.category)) + msg.length(); // 10 = strlen("[XXXX | ] ")
out.append('[');
- color(out, BrightFlag | msgTypeColor[msgType]);
+ Console::colorize(out, Console::BrightFlag | msgTypeColor[msgType]);
out.append(msgTypeStr[msgType], 4); // all msgTypeStrs are 4 characters
- color(out, Off);
+ Console::colorize(out, Console::Off);
out.append(" | ");
- color(out, Red + qHash(QByteArray::fromRawData(context.category, categoryLength)) % 7);
+ Console::colorize(out, Console::Red + qHash(QByteArray::fromRawData(context.category, categoryLength)) % 7);
out.append(context.category, categoryLength);
- color(out, Off);
+ Console::colorize(out, Console::Off);
const QByteArray appId = Logging::applicationId();
if (!appId.isEmpty()) {
out.append(" | ");
- color(out, Red + qHash(appId) % 7);
+ Console::colorize(out, Console::Red + qHash(appId) % 7);
out.append(appId);
- color(out, Off);
+ Console::colorize(out, Console::Off);
outLength += (3 + appId.length()); // 3 == strlen(" | ")
}
@@ -337,15 +335,15 @@ static void colorLogToStderr(QtMsgType msgType, const QMessageLogContext &contex
out.append(spacing, ' ');
out.append('[');
- color(out, Magenta);
+ Console::colorize(out, Console::Magenta);
out.append(filename, filenameLength);
- color(out, Off);
+ Console::colorize(out, Console::Off);
out.append(':');
- color(out, BrightFlag | Magenta);
+ Console::colorize(out, Console::BrightFlag | Console::Magenta);
out.append(linenumber, linenumberLength);
- color(out, Off);
+ Console::colorize(out, Console::Off);
out.append("]\n");
} else {
@@ -550,4 +548,175 @@ void Logging::logToDlt(QtMsgType msgType, const QMessageLogContext &context, con
void am_trace(QDebug)
{ }
+bool Console::supportsAnsiColor = false;
+bool Console::isRunningInQtCreator = false;
+bool Console::hasConsoleWindow = false;
+QAtomicInt Console::consoleWidthCached(0);
+
+void Console::init()
+{
+ static bool once = false;
+ if (!once) {
+ once = true;
+
+ enum { ColorAuto, ColorOff, ColorOn } forceColor = ColorAuto;
+ const QByteArray forceColorOutput = qgetenv("AM_FORCE_COLOR_OUTPUT");
+ if (forceColorOutput == "off" || forceColorOutput == "0")
+ forceColor = ColorOff;
+ else if (forceColorOutput == "on" || forceColorOutput == "1")
+ forceColor = ColorOn;
+
+#if defined(Q_OS_UNIX)
+ if (::isatty(STDERR_FILENO)) {
+ hasConsoleWindow = true;
+ supportsAnsiColor = true;
+ }
+
+#elif defined(Q_OS_WIN)
+ HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
+ if (h != INVALID_HANDLE_VALUE) {
+
+ if (QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows10) {
+ // enable ANSI mode on Windows 10
+ DWORD mode = 0;
+ if (GetConsoleMode(h, &mode)) {
+ mode |= 0x04;
+ if (SetConsoleMode(h, mode)) {
+ supportsAnsiColor = true;
+ hasConsoleWindow = true;
+ }
+ }
+ }
+ }
+#endif
+
+ qint64 pid = QCoreApplication::applicationPid();
+ forever {
+ pid = getParentPid(pid);
+ if (pid <= 1)
+ break;
+
+#if defined(Q_OS_LINUX)
+ static QString checkCreator = qSL("/proc/%1/exe");
+ QFileInfo fi(checkCreator.arg(pid));
+ if (fi.symLinkTarget().contains(qSL("qtcreator"))) {
+ isRunningInQtCreator = true;
+ break;
+ }
+#elif defined(Q_OS_MACOS)
+ static char buffer[PROC_PIDPATHINFO_MAXSIZE + 1];
+ int len = proc_pidpath(pid, buffer, sizeof(buffer) - 1);
+ if ((len > 0) && QByteArray::fromRawData(buffer, len).contains("Qt Creator")) {
+ isRunningInQtCreator = true;
+ break;
+ }
+#elif defined(Q_OS_WIN)
+ HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid);
+ if (hProcess) {
+ wchar_t exeName[1024] = { 0 };
+ DWORD exeNameSize = sizeof(exeName) - 1;
+ if (QueryFullProcessImageNameW(hProcess, 0, exeName, &exeNameSize)) {
+ if (QString::fromWCharArray(exeName, exeNameSize).contains(qSL("qtcreator.exe")))
+ isRunningInQtCreator = true;
+ }
+ }
+#endif
+ }
+
+ if (forceColor != ColorAuto)
+ supportsAnsiColor = (forceColor == ColorOn);
+ else if (!supportsAnsiColor)
+ supportsAnsiColor = isRunningInQtCreator;
+
+#if defined(Q_OS_UNIX) && defined(SIGWINCH)
+ UnixSignalHandler::instance()->install(UnixSignalHandler::RawSignalHandler, SIGWINCH, [](int) {
+ // we are in a signal handler, so we just clear the cached value in the atomic int
+ consoleWidthCached = 0;
+ });
+#elif defined(Q_OS_WIN)
+ class ConsoleThread : public QThread
+ {
+ public:
+ ConsoleThread(QObject *parent)
+ : QThread(parent)
+ { }
+
+ ~ConsoleThread()
+ {
+ terminate();
+ wait();
+ }
+
+ protected:
+ void run() override
+ {
+ HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
+ DWORD mode = 0;
+ if (!GetConsoleMode(h, &mode))
+ return;
+ if (!SetConsoleMode(h, mode | ENABLE_WINDOW_INPUT))
+ return;
+
+ INPUT_RECORD ir;
+ DWORD irRead = 0;
+ while (ReadConsoleInputW(h, &ir, 1, &irRead)) {
+ if ((irRead == 1) && (ir.EventType == WINDOW_BUFFER_SIZE_EVENT))
+ consoleWidthCached = 0;
+ }
+ }
+ };
+ (new ConsoleThread(qApp))->start();
+#endif // Q_OS_WIN
+ }
+}
+
+int Console::width()
+{
+ int consoleWidthCalculated = consoleWidthCached;
+
+ if (consoleWidthCalculated <= 0) {
+ if (hasConsoleWindow) {
+#if defined(Q_OS_UNIX)
+ struct ::winsize ws;
+ if ((::ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == 0) && (ws.ws_col > 0))
+ consoleWidthCalculated = ws.ws_col;
+#elif defined(Q_OS_WIN)
+ HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
+ CONSOLE_SCREEN_BUFFER_INFO csbi;
+ if (GetConsoleScreenBufferInfo(h, &csbi))
+ consoleWidthCalculated = csbi.dwSize.X;
+#endif
+ }
+ consoleWidthCached = consoleWidthCalculated;
+ }
+ if ((consoleWidthCalculated <= 0) && isRunningInQtCreator)
+ return 120;
+ else
+ return consoleWidthCalculated;
+}
+
+QByteArray &Console::colorize(QByteArray &out, int ansiColor, bool forceNoColor)
+{
+ static const char *ansiColors[] = {
+ "\x1b[1m", // bright
+ "\x1b[0m", // off
+ "\x1b[30m", // black
+ "\x1b[31m", // red
+ "\x1b[32m", // green
+ "\x1b[33m", // yellow
+ "\x1b[34m", // blue
+ "\x1b[35m", // magenta
+ "\x1b[36m", // cyan
+ "\x1b[37m" // gray
+ };
+
+ if (forceNoColor || !supportsAnsiColor)
+ return out;
+ if (ansiColor & BrightFlag)
+ out.append(ansiColors[0]);
+ if (ansiColor != BrightFlag)
+ out.append(ansiColors[1 + (ansiColor & ~BrightFlag)]);
+ return out;
+}
+
QT_END_NAMESPACE_AM
diff --git a/src/common-lib/logging.h b/src/common-lib/logging.h
index 643687fd..d696c078 100644
--- a/src/common-lib/logging.h
+++ b/src/common-lib/logging.h
@@ -109,4 +109,21 @@ template <typename T, typename... TRest> void am_trace(QDebug dbg, T t, TRest...
QT_PREPEND_NAMESPACE_AM(am_trace(QMessageLogger(__FILE__, __LINE__, __FUNCTION__, category().categoryName()).debug(), "TRACE", __FUNCTION__, __VA_ARGS__)); \
}
+class Console
+{
+public:
+ static void init();
+
+ static bool supportsAnsiColor;
+ static bool isRunningInQtCreator;
+ static bool hasConsoleWindow;
+ static int width();
+
+ enum Color { Off = 0, Black, Red, Green, Yellow, Blue, Magenta, Cyan, Gray, BrightFlag = 0x80 };
+ static QByteArray &colorize(QByteArray &out, int color, bool forceNoColor = false);
+
+private:
+ static QAtomicInt consoleWidthCached;
+};
+
QT_END_NAMESPACE_AM
diff --git a/src/common-lib/startuptimer.cpp b/src/common-lib/startuptimer.cpp
index 5e143093..2aabf056 100644
--- a/src/common-lib/startuptimer.cpp
+++ b/src/common-lib/startuptimer.cpp
@@ -40,14 +40,8 @@
**
****************************************************************************/
-#ifdef _WIN32
-// needed for QueryFullProcessImageNameW
-# define WINVER _WIN32_WINNT_VISTA
-# define _WIN32_WINNT _WIN32_WINNT_VISTA
-#endif
-
#include "startuptimer.h"
-#include "utilities.h"
+#include "logging.h"
#if defined(Q_OS_WIN)
# include <windows.h>
@@ -448,8 +442,10 @@ void StartupTimer::createReport(const QString &title)
{
if (m_output && !m_checkpoints.isEmpty()) {
bool ansiColorSupport = false;
- if (m_output == stderr)
- getOutputInformation(&ansiColorSupport, nullptr, nullptr);
+ if (m_output == stderr) {
+ Console::init();
+ ansiColorSupport = Console::supportsAnsiColor;
+ }
constexpr const char *plainFormat = "\n== STARTUP TIMING REPORT: %s ==\n";
constexpr const char *colorFormat = "\n\033[33m== STARTUP TIMING REPORT: %s ==\033[0m\n";
diff --git a/src/common-lib/utilities.cpp b/src/common-lib/utilities.cpp
index cc21dfed..2cd4fb17 100644
--- a/src/common-lib/utilities.cpp
+++ b/src/common-lib/utilities.cpp
@@ -41,14 +41,6 @@
**
****************************************************************************/
-#if defined(_WIN32) && (_WIN32_WINNT-0 < _WIN32_WINNT_VISTA)
-// needed for QueryFullProcessImageNameW
-# undef WINVER
-# undef _WIN32_WINNT
-# define WINVER _WIN32_WINNT_VISTA
-# define _WIN32_WINNT _WIN32_WINNT_VISTA
-#endif
-
#include <QFile>
#include <QFileInfo>
#include <QDir>
@@ -60,31 +52,21 @@
#include "utilities.h"
#include "exception.h"
-#include "unixsignalhandler.h"
#include <errno.h>
#if defined(Q_OS_UNIX)
# include <unistd.h>
-# include <sys/ioctl.h>
-# include <termios.h>
-# include <signal.h>
#endif
#if defined(Q_OS_WIN)
-# include <QThread>
-# include <windows.h>
-# include <io.h>
-# include <tlhelp32.h>
+# include <Windows.h>
+# include <TlHelp32.h>
#elif defined(Q_OS_MACOS) || defined(Q_OS_IOS)
# include <unistd.h>
# include <sys/mount.h>
# include <sys/statvfs.h>
# include <sys/sysctl.h>
-# if defined(Q_OS_MACOS)
-# include <libproc.h>
-# endif
#else
-# include <stdio.h>
# include <mntent.h>
# include <sys/stat.h>
# if defined(Q_OS_ANDROID)
@@ -94,9 +76,6 @@
# include <sys/statvfs.h>
# endif
# include <qplatformdefs.h>
-
-// the process environment from the C library
-extern char **environ;
#endif
QT_BEGIN_NAMESPACE_AM
@@ -226,150 +205,6 @@ bool safeRemove(const QString &path, RecursiveOperationType type)
return false;
}
-void getOutputInformation(bool *ansiColorSupport, bool *runningInCreator, int *consoleWidth)
-{
- static bool ansiColorSupportDetected = false;
- static bool runningInCreatorDetected = false;
- static QAtomicInteger<int> consoleWidthCached(0);
- static int consoleWidthCalculated = -1;
- static bool once = false;
-
- if (!once) {
- enum { ColorAuto, ColorOff, ColorOn } forceColor = ColorAuto;
- QByteArray forceColorOutput = qgetenv("AM_FORCE_COLOR_OUTPUT");
- if (forceColorOutput == "off" || forceColorOutput == "0")
- forceColor = ColorOff;
- else if (forceColorOutput == "on" || forceColorOutput == "1")
- forceColor = ColorOn;
-
-#if defined(Q_OS_UNIX)
- if (::isatty(STDERR_FILENO))
- ansiColorSupportDetected = true;
-
-#elif defined(Q_OS_WIN)
- HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
- if (h != INVALID_HANDLE_VALUE) {
- if (QSysInfo::windowsVersion() >= QSysInfo::WV_10_0) {
- // enable ANSI mode on Windows 10
- DWORD mode = 0;
- if (GetConsoleMode(h, &mode)) {
- mode |= 0x04;
- if (SetConsoleMode(h, mode))
- ansiColorSupportDetected = true;
- }
- }
- }
-#endif
-
- qint64 pid = QCoreApplication::applicationPid();
- forever {
- pid = getParentPid(pid);
- if (pid <= 1)
- break;
-
-#if defined(Q_OS_LINUX)
- static QString checkCreator = qSL("/proc/%1/exe");
- QFileInfo fi(checkCreator.arg(pid));
- if (fi.symLinkTarget().contains(qSL("qtcreator"))) {
- runningInCreatorDetected = true;
- break;
- }
-#elif defined(Q_OS_MACOS)
- static char buffer[PROC_PIDPATHINFO_MAXSIZE + 1];
- int len = proc_pidpath(pid, buffer, sizeof(buffer) - 1);
- if ((len > 0) && QByteArray::fromRawData(buffer, len).contains("Qt Creator")) {
- runningInCreatorDetected = true;
- break;
- }
-#elif defined(Q_OS_WIN)
- HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid);
- if (hProcess) {
- wchar_t exeName[1024] = { 0 };
- DWORD exeNameSize = sizeof(exeName) - 1;
- if (QueryFullProcessImageNameW(hProcess, 0, exeName, &exeNameSize)) {
- if (QString::fromWCharArray(exeName, exeNameSize).contains(qSL("qtcreator.exe")))
- runningInCreatorDetected = true;
- }
- }
-#endif
- }
-
- if (forceColor != ColorAuto)
- ansiColorSupportDetected = (forceColor == ColorOn);
- else if (!ansiColorSupportDetected)
- ansiColorSupportDetected = runningInCreatorDetected;
-
-#if defined(Q_OS_UNIX) && defined(SIGWINCH)
- UnixSignalHandler::instance()->install(UnixSignalHandler::RawSignalHandler, SIGWINCH, [](int) {
- consoleWidthCached = 0;
- });
-#elif defined(Q_OS_WIN)
- class ConsoleThread : public QThread
- {
- public:
- ConsoleThread(QObject *parent)
- : QThread(parent)
- { }
-
- ~ConsoleThread()
- {
- terminate();
- wait();
- }
-
- protected:
- void run() override
- {
- HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
- DWORD mode = 0;
- if (!GetConsoleMode(h, &mode))
- return;
- if (!SetConsoleMode(h, mode | ENABLE_WINDOW_INPUT))
- return;
-
- INPUT_RECORD ir;
- DWORD irRead = 0;
- while (ReadConsoleInputW(h, &ir, 1, &irRead)) {
- if ((irRead == 1) && (ir.EventType == WINDOW_BUFFER_SIZE_EVENT))
- consoleWidthCached = 0;
- }
- }
- };
- (new ConsoleThread(qApp))->start();
-#endif // Q_OS_WIN
- once = true;
- }
-
- if (ansiColorSupport)
- *ansiColorSupport = ansiColorSupportDetected;
- if (runningInCreator)
- *runningInCreator = runningInCreatorDetected;
- if (consoleWidth) {
- if (!consoleWidthCached) {
- consoleWidthCached = 1;
- consoleWidthCalculated = -1;
-#if defined(Q_OS_UNIX)
- if (::isatty(STDERR_FILENO)) {
- struct ::winsize ws;
- if ((::ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == 0) && (ws.ws_col > 0))
- consoleWidthCalculated = ws.ws_col;
- }
-#elif defined(Q_OS_WIN)
- HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
- if (h != INVALID_HANDLE_VALUE && h != NULL) {
- CONSOLE_SCREEN_BUFFER_INFO csbi;
- if (GetConsoleScreenBufferInfo(h, &csbi))
- consoleWidthCalculated = csbi.dwSize.X;
- }
-#endif
- }
- if ((consoleWidthCalculated <= 0) && runningInCreatorDetected)
- *consoleWidth = 120;
- else
- *consoleWidth = consoleWidthCalculated;
- }
-}
-
qint64 getParentPid(qint64 pid)
{
qint64 ppid = 0;
diff --git a/src/common-lib/utilities.h b/src/common-lib/utilities.h
index dd07913c..0d51fc6f 100644
--- a/src/common-lib/utilities.h
+++ b/src/common-lib/utilities.h
@@ -135,8 +135,6 @@ bool recursiveOperation(const QDir &path, const std::function<bool(const QString
// makes files and directories writable, then deletes them
bool safeRemove(const QString &path, RecursiveOperationType type);
-void getOutputInformation(bool *ansiColorSupport, bool *runningInCreator, int *consoleWidth);
-
qint64 getParentPid(qint64 pid);
QVector<QObject *> loadPlugins_helper(const char *type, const QStringList &files, const char *iid) Q_DECL_NOEXCEPT_EXPR(false);
diff --git a/src/crypto-lib/signature_win.cpp b/src/crypto-lib/signature_win.cpp
index 31cc5fc3..be14d1f3 100644
--- a/src/crypto-lib/signature_win.cpp
+++ b/src/crypto-lib/signature_win.cpp
@@ -42,7 +42,9 @@
#ifdef _WIN32
// needed for crypto API compatibility - otherwise this will only work on Win8+
+# undef WINVER
# define WINVER _WIN32_WINNT_WIN7
+# undef _WIN32_WINNT
# define _WIN32_WINNT _WIN32_WINNT_WIN7
#endif