From b1a3f9e52072a827a85129fcf9090036019078f2 Mon Sep 17 00:00:00 2001 From: Meltie2013 Date: Mon, 28 Aug 2023 09:22:31 -0500 Subject: [PATCH] Support drop for x86 architecture (#154) --- cmake/compiler/msvc/settings.cmake | 13 - cmake/macros/CheckPlatform.cmake | 8 +- src/common/CompilerDefs.h | 4 +- .../Debugging/WheatyExceptionReport.cpp | 1132 ++++++++--------- src/common/Logging/Log.h | 2 +- src/common/Metric/Metric.h | 2 +- src/common/Platform/ServiceWin32.cpp | 4 +- src/common/Platform/ServiceWin32.h | 4 +- src/common/Threading/ProcessPriority.cpp | 8 +- src/common/Utilities/Util.cpp | 6 +- src/server/authserver/Main.cpp | 7 +- .../database/Database/MySQLConnection.cpp | 2 +- .../database/Database/MySQLWorkaround.h | 2 +- src/server/database/Updater/DBUpdater.cpp | 2 +- src/server/game/Scripting/ScriptReloadMgr.cpp | 2 +- src/server/shared/Networking/AsyncAcceptor.h | 2 +- .../worldserver/CommandLine/CliRunnable.cpp | 242 ++-- src/server/worldserver/FCSoap/FCSoap.cpp | 207 +-- src/server/worldserver/Main.cpp | 21 +- src/tools/map_extractor/System.cpp | 6 +- src/tools/mmaps_generator/PathCommon.h | 15 +- src/tools/vmap4_extractor/mpqfile.h | 2 +- src/tools/vmap4_extractor/vmapexport.cpp | 5 +- 23 files changed, 793 insertions(+), 905 deletions(-) diff --git a/cmake/compiler/msvc/settings.cmake b/cmake/compiler/msvc/settings.cmake index ed7992f4..dbfbf333 100644 --- a/cmake/compiler/msvc/settings.cmake +++ b/cmake/compiler/msvc/settings.cmake @@ -33,19 +33,6 @@ if(PLATFORM EQUAL 64) INTERFACE -D_WIN64) message(STATUS "MSVC: 64-bit platform, enforced -D_WIN64 parameter") - -else() - # mark 32 bit executables large address aware so they can use > 2GB address space - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /LARGEADDRESSAWARE") - message(STATUS "MSVC: Enabled large address awareness") - - target_compile_options(fc-compile-option-interface - INTERFACE - /arch:SSE2) - message(STATUS "MSVC: Enabled SSE2 support") - - set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} /SAFESEH:NO") - message(STATUS "MSVC: Disabled Safe Exception Handlers for debug builds") endif() # Set build-directive (used in core to tell which buildtype we used) diff --git a/cmake/macros/CheckPlatform.cmake b/cmake/macros/CheckPlatform.cmake index 0f41a9c1..fe106f2a 100644 --- a/cmake/macros/CheckPlatform.cmake +++ b/cmake/macros/CheckPlatform.cmake @@ -1,10 +1,10 @@ -# check what platform we're on (64-bit or 32-bit), and create a simpler test than CMAKE_SIZEOF_VOID_P +# check what platform we're on 64-bit, and create a simpler test than CMAKE_SIZEOF_VOID_P if(CMAKE_SIZEOF_VOID_P MATCHES 8) set(PLATFORM 64) - MESSAGE(STATUS "Detected 64-bit platform") + message(STATUS "Detected 64-bit platform - ok") else() - set(PLATFORM 32) - MESSAGE(STATUS "Detected 32-bit platform") + set(PLATFORM 32) + message(FATAL_ERROR "FirelandsCore doesn't support x86, please use x64 architecture.") endif() if(WIN32) diff --git a/src/common/CompilerDefs.h b/src/common/CompilerDefs.h index da4800b3..5e0ce136 100644 --- a/src/common/CompilerDefs.h +++ b/src/common/CompilerDefs.h @@ -23,11 +23,9 @@ #define FC_PLATFORM_APPLE 2 #define FC_PLATFORM_INTEL 3 -// must be first (win 64 also define _WIN32) +// must be first Win64 #if defined( _WIN64 ) # define FC_PLATFORM FC_PLATFORM_WINDOWS -#elif defined( __WIN32__ ) || defined( WIN32 ) || defined( _WIN32 ) -# define FC_PLATFORM FC_PLATFORM_WINDOWS #elif defined( __APPLE_CC__ ) # define FC_PLATFORM FC_PLATFORM_APPLE #elif defined( __INTEL_COMPILER ) diff --git a/src/common/Debugging/WheatyExceptionReport.cpp b/src/common/Debugging/WheatyExceptionReport.cpp index a3d1a7e1..ba6ef082 100644 --- a/src/common/Debugging/WheatyExceptionReport.cpp +++ b/src/common/Debugging/WheatyExceptionReport.cpp @@ -9,9 +9,9 @@ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif -#pragma warning(disable:4996) -#pragma warning(disable:4312) -#pragma warning(disable:4311) +#pragma warning(disable : 4996) +#pragma warning(disable : 4312) +#pragma warning(disable : 4311) #include #include #include @@ -36,23 +36,17 @@ inline LPTSTR ErrorMessage(DWORD dw) { LPVOID lpMsgBuf; - DWORD formatResult = FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - dw, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR) &lpMsgBuf, - 0, NULL); + DWORD formatResult = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); if (formatResult != 0) + { return (LPTSTR)lpMsgBuf; + } else { LPTSTR msgBuf = (LPTSTR)LocalAlloc(LPTR, 30); sprintf(msgBuf, "Unknown error: %u", dw); return msgBuf; } - } //============================== Global Variables ============================= @@ -74,13 +68,12 @@ bool WheatyExceptionReport::alreadyCrashed; std::mutex WheatyExceptionReport::alreadyCrashedLock; WheatyExceptionReport::pRtlGetVersion WheatyExceptionReport::RtlGetVersion; - // Declare global instance of class WheatyExceptionReport g_WheatyExceptionReport; //============================== Class Methods ============================= -WheatyExceptionReport::WheatyExceptionReport() // Constructor +WheatyExceptionReport::WheatyExceptionReport() // Constructor { // Install the unhandled exception filter function m_previousFilter = SetUnhandledExceptionFilter(WheatyUnhandledExceptionFilter); @@ -113,8 +106,7 @@ WheatyExceptionReport::~WheatyExceptionReport() //=========================================================== // Entry point where control comes on an unhandled exception //=========================================================== -LONG WINAPI WheatyExceptionReport::WheatyUnhandledExceptionFilter( -PEXCEPTION_POINTERS pExceptionInfo) +LONG WINAPI WheatyExceptionReport::WheatyUnhandledExceptionFilter(PEXCEPTION_POINTERS pExceptionInfo) { std::unique_lock guard(alreadyCrashedLock); // Handle only 1 exception in the whole process lifetime @@ -144,27 +136,13 @@ PEXCEPTION_POINTERS pExceptionInfo) SYSTEMTIME systime; GetLocalTime(&systime); - sprintf(m_szDumpFileName, "%s\\%s_%s_[%u-%u_%u-%u-%u].dmp", - crash_folder_path, GitRevision::GetHash(), pos, systime.wDay, systime.wMonth, systime.wHour, systime.wMinute, systime.wSecond); - - sprintf(m_szLogFileName, "%s\\%s_%s_[%u-%u_%u-%u-%u].txt", - crash_folder_path, GitRevision::GetHash(), pos, systime.wDay, systime.wMonth, systime.wHour, systime.wMinute, systime.wSecond); - - m_hDumpFile = CreateFile(m_szDumpFileName, - GENERIC_WRITE, - 0, - 0, - OPEN_ALWAYS, - FILE_FLAG_WRITE_THROUGH, - 0); - - m_hReportFile = CreateFile(m_szLogFileName, - GENERIC_WRITE, - 0, - 0, - OPEN_ALWAYS, - FILE_FLAG_WRITE_THROUGH, - 0); + sprintf(m_szDumpFileName, "%s\\%s_%s_[%u-%u_%u-%u-%u].dmp", crash_folder_path, GitRevision::GetHash(), pos, systime.wDay, systime.wMonth, systime.wHour, systime.wMinute, systime.wSecond); + + sprintf(m_szLogFileName, "%s\\%s_%s_[%u-%u_%u-%u-%u].txt", crash_folder_path, GitRevision::GetHash(), pos, systime.wDay, systime.wMonth, systime.wHour, systime.wMinute, systime.wSecond); + + m_hDumpFile = CreateFile(m_szDumpFileName, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, 0); + + m_hReportFile = CreateFile(m_szLogFileName, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, 0); if (m_hDumpFile) { @@ -186,8 +164,7 @@ PEXCEPTION_POINTERS pExceptionInfo) additionalStreamInfo.UserStreamCount = 1; } - MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), - m_hDumpFile, MiniDumpWithIndirectlyReferencedMemory, &info, &additionalStreamInfo, 0); + MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), m_hDumpFile, MiniDumpWithIndirectlyReferencedMemory, &info, &additionalStreamInfo, 0); CloseHandle(m_hDumpFile); } @@ -205,7 +182,7 @@ PEXCEPTION_POINTERS pExceptionInfo) if (m_previousFilter) return m_previousFilter(pExceptionInfo); else - return EXCEPTION_EXECUTE_HANDLER/*EXCEPTION_CONTINUE_SEARCH*/; + return EXCEPTION_EXECUTE_HANDLER /*EXCEPTION_CONTINUE_SEARCH*/; } void __cdecl WheatyExceptionReport::WheatyCrtHandler(wchar_t const* /*expression*/, wchar_t const* /*function*/, wchar_t const* /*file*/, unsigned int /*line*/, uintptr_t /*pReserved*/) @@ -220,14 +197,12 @@ BOOL WheatyExceptionReport::_GetProcessorName(TCHAR* sProcessorName, DWORD maxco HKEY hKey; LONG lRet; - lRet = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), - 0, KEY_QUERY_VALUE, &hKey); + lRet = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), 0, KEY_QUERY_VALUE, &hKey); if (lRet != ERROR_SUCCESS) return FALSE; TCHAR szTmp[2048]; DWORD cntBytes = sizeof(szTmp); - lRet = ::RegQueryValueEx(hKey, _T("ProcessorNameString"), NULL, NULL, - (LPBYTE)szTmp, &cntBytes); + lRet = ::RegQueryValueEx(hKey, _T("ProcessorNameString"), NULL, NULL, (LPBYTE)szTmp, &cntBytes); if (lRet != ERROR_SUCCESS) return FALSE; ::RegCloseKey(hKey); @@ -240,8 +215,7 @@ BOOL WheatyExceptionReport::_GetProcessorName(TCHAR* sProcessorName, DWORD maxco return TRUE; } -template -void ToTchar(wchar_t const* src, TCHAR (&dst)[size]) +template void ToTchar(wchar_t const* src, TCHAR (&dst)[size]) { if constexpr (std::is_same_v) ::wcstombs_s(nullptr, dst, src, size); @@ -258,7 +232,7 @@ BOOL WheatyExceptionReport::_GetWindowsVersion(TCHAR* szVersion, DWORD cntMax) // Try calling GetVersionEx using the OSVERSIONINFOEX structure. // If that fails, try using the OSVERSIONINFO structure. - RTL_OSVERSIONINFOEXW osvi = { }; + RTL_OSVERSIONINFOEXW osvi = {}; osvi.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW); NTSTATUS bVersionEx = RtlGetVersion((PRTL_OSVERSIONINFOW)&osvi); if (bVersionEx < 0) @@ -274,154 +248,149 @@ BOOL WheatyExceptionReport::_GetWindowsVersion(TCHAR* szVersion, DWORD cntMax) TCHAR wszTmp[128]; switch (osvi.dwPlatformId) { - // Windows NT product family. - case VER_PLATFORM_WIN32_NT: + // Windows NT product family. + case VER_PLATFORM_WIN32_NT: + { +#if WINVER < 0x0500 + BYTE suiteMask = osvi.wReserved[0]; + BYTE productType = osvi.wReserved[1]; +#else + WORD suiteMask = osvi.wSuiteMask; + BYTE productType = osvi.wProductType; +#endif // WINVER < 0x0500 + + // Test for the specific product family. + if (osvi.dwMajorVersion == 10) + { + if (productType == VER_NT_WORKSTATION) + _tcsncat(szVersion, _T("Windows 10 "), cntMax); + else + _tcsncat(szVersion, _T("Windows Server 2016 "), cntMax); + } + else if (osvi.dwMajorVersion == 6) { - #if WINVER < 0x0500 - BYTE suiteMask = osvi.wReserved[0]; - BYTE productType = osvi.wReserved[1]; - #else - WORD suiteMask = osvi.wSuiteMask; - BYTE productType = osvi.wProductType; - #endif // WINVER < 0x0500 - - // Test for the specific product family. - if (osvi.dwMajorVersion == 10) + if (productType == VER_NT_WORKSTATION) { - if (productType == VER_NT_WORKSTATION) - _tcsncat(szVersion, _T("Windows 10 "), cntMax); + if (osvi.dwMinorVersion == 3) + _tcsncat(szVersion, _T("Windows 8.1 "), cntMax); + else if (osvi.dwMinorVersion == 2) + _tcsncat(szVersion, _T("Windows 8 "), cntMax); + else if (osvi.dwMinorVersion == 1) + _tcsncat(szVersion, _T("Windows 7 "), cntMax); else - _tcsncat(szVersion, _T("Windows Server 2016 "), cntMax); + _tcsncat(szVersion, _T("Windows Vista "), cntMax); } - else if (osvi.dwMajorVersion == 6) + else if (osvi.dwMinorVersion == 3) + _tcsncat(szVersion, _T("Windows Server 2012 R2 "), cntMax); + else if (osvi.dwMinorVersion == 2) + _tcsncat(szVersion, _T("Windows Server 2012 "), cntMax); + else if (osvi.dwMinorVersion == 1) + _tcsncat(szVersion, _T("Windows Server 2008 R2 "), cntMax); + else + _tcsncat(szVersion, _T("Windows Server 2008 "), cntMax); + } + else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) + _tcsncat(szVersion, _T("Microsoft Windows Server 2003 "), cntMax); + else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) + _tcsncat(szVersion, _T("Microsoft Windows XP "), cntMax); + else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) + _tcsncat(szVersion, _T("Microsoft Windows 2000 "), cntMax); + else if (osvi.dwMajorVersion <= 4) + _tcsncat(szVersion, _T("Microsoft Windows NT "), cntMax); + + // Test for specific product on Windows NT 4.0 SP6 and later. + if (bVersionEx >= 0) + { + // Test for the workstation type. + if (productType == VER_NT_WORKSTATION) { - if (productType == VER_NT_WORKSTATION) - { - if (osvi.dwMinorVersion == 3) - _tcsncat(szVersion, _T("Windows 8.1 "), cntMax); - else if (osvi.dwMinorVersion == 2) - _tcsncat(szVersion, _T("Windows 8 "), cntMax); - else if (osvi.dwMinorVersion == 1) - _tcsncat(szVersion, _T("Windows 7 "), cntMax); - else - _tcsncat(szVersion, _T("Windows Vista "), cntMax); - } - else if (osvi.dwMinorVersion == 3) - _tcsncat(szVersion, _T("Windows Server 2012 R2 "), cntMax); - else if (osvi.dwMinorVersion == 2) - _tcsncat(szVersion, _T("Windows Server 2012 "), cntMax); - else if (osvi.dwMinorVersion == 1) - _tcsncat(szVersion, _T("Windows Server 2008 R2 "), cntMax); + if (osvi.dwMajorVersion == 4) + _tcsncat(szVersion, _T("Workstation 4.0 "), cntMax); + else if (suiteMask & VER_SUITE_PERSONAL) + _tcsncat(szVersion, _T("Home Edition "), cntMax); + else if (suiteMask & VER_SUITE_EMBEDDEDNT) + _tcsncat(szVersion, _T("Embedded "), cntMax); else - _tcsncat(szVersion, _T("Windows Server 2008 "), cntMax); + _tcsncat(szVersion, _T("Professional "), cntMax); } - else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) - _tcsncat(szVersion, _T("Microsoft Windows Server 2003 "), cntMax); - else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) - _tcsncat(szVersion, _T("Microsoft Windows XP "), cntMax); - else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) - _tcsncat(szVersion, _T("Microsoft Windows 2000 "), cntMax); - else if (osvi.dwMajorVersion <= 4) - _tcsncat(szVersion, _T("Microsoft Windows NT "), cntMax); - - // Test for specific product on Windows NT 4.0 SP6 and later. - if (bVersionEx >= 0) + // Test for the server type. + else if (productType == VER_NT_SERVER) { - // Test for the workstation type. - if (productType == VER_NT_WORKSTATION) + if (osvi.dwMajorVersion == 6 || osvi.dwMajorVersion == 10) { - if (osvi.dwMajorVersion == 4) - _tcsncat(szVersion, _T("Workstation 4.0 "), cntMax); - else if (suiteMask & VER_SUITE_PERSONAL) - _tcsncat(szVersion, _T("Home Edition "), cntMax); - else if (suiteMask & VER_SUITE_EMBEDDEDNT) - _tcsncat(szVersion, _T("Embedded "), cntMax); + if (suiteMask & VER_SUITE_SMALLBUSINESS_RESTRICTED) + _tcsncat(szVersion, _T("Essentials "), cntMax); + else if (suiteMask & VER_SUITE_DATACENTER) + _tcsncat(szVersion, _T("Datacenter "), cntMax); + else if (suiteMask & VER_SUITE_ENTERPRISE) + _tcsncat(szVersion, _T("Enterprise "), cntMax); else - _tcsncat(szVersion, _T("Professional "), cntMax); + _tcsncat(szVersion, _T("Standard "), cntMax); } - // Test for the server type. - else if (productType == VER_NT_SERVER) + else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { - if (osvi.dwMajorVersion == 6 || osvi.dwMajorVersion == 10) - { - if (suiteMask & VER_SUITE_SMALLBUSINESS_RESTRICTED) - _tcsncat(szVersion, _T("Essentials "), cntMax); - else if (suiteMask & VER_SUITE_DATACENTER) - _tcsncat(szVersion, _T("Datacenter "), cntMax); - else if (suiteMask & VER_SUITE_ENTERPRISE) - _tcsncat(szVersion, _T("Enterprise "), cntMax); - else - _tcsncat(szVersion, _T("Standard "), cntMax); - } - else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) - { - if (suiteMask & VER_SUITE_DATACENTER) - _tcsncat(szVersion, _T("Datacenter Edition "), cntMax); - else if (suiteMask & VER_SUITE_ENTERPRISE) - _tcsncat(szVersion, _T("Enterprise Edition "), cntMax); - else if (suiteMask == VER_SUITE_BLADE) - _tcsncat(szVersion, _T("Web Edition "), cntMax); - else - _tcsncat(szVersion, _T("Standard Edition "), cntMax); - } - else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) - { - if (suiteMask & VER_SUITE_DATACENTER) - _tcsncat(szVersion, _T("Datacenter Server "), cntMax); - else if (suiteMask & VER_SUITE_ENTERPRISE) - _tcsncat(szVersion, _T("Advanced Server "), cntMax); - else - _tcsncat(szVersion, _T("Server "), cntMax); - } - else // Windows NT 4.0 - { - if (suiteMask & VER_SUITE_ENTERPRISE) - _tcsncat(szVersion, _T("Server 4.0, Enterprise Edition "), cntMax); - else - _tcsncat(szVersion, _T("Server 4.0 "), cntMax); - } + if (suiteMask & VER_SUITE_DATACENTER) + _tcsncat(szVersion, _T("Datacenter Edition "), cntMax); + else if (suiteMask & VER_SUITE_ENTERPRISE) + _tcsncat(szVersion, _T("Enterprise Edition "), cntMax); + else if (suiteMask == VER_SUITE_BLADE) + _tcsncat(szVersion, _T("Web Edition "), cntMax); + else + _tcsncat(szVersion, _T("Standard Edition "), cntMax); } - } - - // Display service pack (if any) and build number. - if (osvi.dwMajorVersion == 4 && _tcsicmp(szCSDVersion, _T("Service Pack 6")) == 0) - { - HKEY hKey; - LONG lRet; - - // Test for SP6 versus SP6a. - lRet = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009"), 0, KEY_QUERY_VALUE, &hKey); - if (lRet == ERROR_SUCCESS) + else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { - _stprintf(wszTmp, _T("Service Pack 6a (Version %d.%d, Build %d)"), - osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber & 0xFFFF); - _tcsncat(szVersion, wszTmp, cntMax); + if (suiteMask & VER_SUITE_DATACENTER) + _tcsncat(szVersion, _T("Datacenter Server "), cntMax); + else if (suiteMask & VER_SUITE_ENTERPRISE) + _tcsncat(szVersion, _T("Advanced Server "), cntMax); + else + _tcsncat(szVersion, _T("Server "), cntMax); } - else // Windows NT 4.0 prior to SP6a + else // Windows NT 4.0 { - _stprintf(wszTmp, _T("%s (Version %d.%d, Build %d)"), - szCSDVersion, osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber & 0xFFFF); - _tcsncat(szVersion, wszTmp, cntMax); + if (suiteMask & VER_SUITE_ENTERPRISE) + _tcsncat(szVersion, _T("Server 4.0, Enterprise Edition "), cntMax); + else + _tcsncat(szVersion, _T("Server 4.0 "), cntMax); } - ::RegCloseKey(hKey); } - else // Windows NT 3.51 and earlier or Windows 2000 and later + } + + // Display service pack (if any) and build number. + if (osvi.dwMajorVersion == 4 && _tcsicmp(szCSDVersion, _T("Service Pack 6")) == 0) + { + HKEY hKey; + LONG lRet; + + // Test for SP6 versus SP6a. + lRet = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009"), 0, KEY_QUERY_VALUE, &hKey); + if (lRet == ERROR_SUCCESS) { - if (!_tcslen(szCSDVersion)) - _stprintf(wszTmp, _T("(Version %d.%d, Build %d)"), - osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber & 0xFFFF); - else - _stprintf(wszTmp, _T("%s (Version %d.%d, Build %d)"), - szCSDVersion, osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber & 0xFFFF); + _stprintf(wszTmp, _T("Service Pack 6a (Version %d.%d, Build %d)"), osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber & 0xFFFF); _tcsncat(szVersion, wszTmp, cntMax); } - break; + else // Windows NT 4.0 prior to SP6a + { + _stprintf(wszTmp, _T("%s (Version %d.%d, Build %d)"), szCSDVersion, osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber & 0xFFFF); + _tcsncat(szVersion, wszTmp, cntMax); + } + ::RegCloseKey(hKey); } - default: - _stprintf(wszTmp, _T("%s (Version %d.%d, Build %d)"), - szCSDVersion, osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber & 0xFFFF); + else // Windows NT 3.51 and earlier or Windows 2000 and later + { + if (!_tcslen(szCSDVersion)) + _stprintf(wszTmp, _T("(Version %d.%d, Build %d)"), osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber & 0xFFFF); + else + _stprintf(wszTmp, _T("%s (Version %d.%d, Build %d)"), szCSDVersion, osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber & 0xFFFF); _tcsncat(szVersion, wszTmp, cntMax); - break; + } + break; + } + default: + _stprintf(wszTmp, _T("%s (Version %d.%d, Build %d)"), szCSDVersion, osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber & 0xFFFF); + _tcsncat(szVersion, wszTmp, cntMax); + break; } return TRUE; @@ -435,15 +404,11 @@ BOOL WheatyExceptionReport::_GetWindowsVersionFromWMI(TCHAR* szVersion, DWORD cn if (FAILED(hres)) return FALSE; - std::shared_ptr com(nullptr, [](void*) - { - CoUninitialize(); - }); + std::shared_ptr com(nullptr, [](void*) { CoUninitialize(); }); // Step 2: -------------------------------------------------- // Set general COM security levels -------------------------- - hres = CoInitializeSecurity( - nullptr, + hres = CoInitializeSecurity(nullptr, -1, // COM authentication nullptr, // Authentication services nullptr, // Reserved @@ -462,17 +427,16 @@ BOOL WheatyExceptionReport::_GetWindowsVersionFromWMI(TCHAR* szVersion, DWORD cn std::shared_ptr loc = []() -> std::shared_ptr { IWbemLocator* tmp = nullptr; - HRESULT hres = CoCreateInstance( - CLSID_WbemLocator, - nullptr, - CLSCTX_INPROC_SERVER, - IID_IWbemLocator, - reinterpret_cast(&tmp)); + HRESULT hres = CoCreateInstance(CLSID_WbemLocator, nullptr, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast(&tmp)); if (FAILED(hres)) return nullptr; - return { tmp, [](IWbemLocator* ptr) { if (ptr) ptr->Release(); } }; + return {tmp, [](IWbemLocator* ptr) + { + if (ptr) + ptr->Release(); + }}; }(); if (!loc) @@ -482,24 +446,27 @@ BOOL WheatyExceptionReport::_GetWindowsVersionFromWMI(TCHAR* szVersion, DWORD cn // Connect to the root\cimv2 namespace with // the current user and obtain pointer pSvc // to make IWbemServices calls. - std::shared_ptr svc = [loc]() ->std::shared_ptr + std::shared_ptr svc = [loc]() -> std::shared_ptr { IWbemServices* tmp = nullptr; - HRESULT hres = loc->ConnectServer( - bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace - nullptr, // User name. NULL = current user - nullptr, // User password. NULL = current - nullptr, // Locale. NULL indicates current - 0, // Security flags. - nullptr, // Authority (for example, Kerberos) - nullptr, // Context object - &tmp // pointer to IWbemServices proxy + HRESULT hres = loc->ConnectServer(bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace + nullptr, // User name. NULL = current user + nullptr, // User password. NULL = current + nullptr, // Locale. NULL indicates current + 0, // Security flags. + nullptr, // Authority (for example, Kerberos) + nullptr, // Context object + &tmp // pointer to IWbemServices proxy ); if (FAILED(hres)) return nullptr; - return { tmp, [](IWbemServices* ptr) { if (ptr) ptr->Release(); } }; + return {tmp, [](IWbemServices* ptr) + { + if (ptr) + ptr->Release(); + }}; }(); if (!svc) @@ -507,15 +474,14 @@ BOOL WheatyExceptionReport::_GetWindowsVersionFromWMI(TCHAR* szVersion, DWORD cn // Step 5: -------------------------------------------------- // Set security levels on the proxy ------------------------- - hres = CoSetProxyBlanket( - svc.get(), // Indicates the proxy to set - RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx - RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx - nullptr, // Server principal name - RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx - RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx - nullptr, // client identity - EOAC_NONE // proxy capabilities + hres = CoSetProxyBlanket(svc.get(), // Indicates the proxy to set + RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx + RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx + nullptr, // Server principal name + RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx + RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx + nullptr, // client identity + EOAC_NONE // proxy capabilities ); if (FAILED(hres)) @@ -528,17 +494,16 @@ BOOL WheatyExceptionReport::_GetWindowsVersionFromWMI(TCHAR* szVersion, DWORD cn std::shared_ptr queryResult = [svc]() -> std::shared_ptr { IEnumWbemClassObject* tmp = nullptr; - HRESULT hres = svc->ExecQuery( - bstr_t("WQL"), - bstr_t("SELECT Caption, CSDVersion FROM Win32_OperatingSystem"), - WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, - nullptr, - &tmp); + HRESULT hres = svc->ExecQuery(bstr_t("WQL"), bstr_t("SELECT Caption, CSDVersion FROM Win32_OperatingSystem"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, nullptr, &tmp); if (FAILED(hres)) return nullptr; - return { tmp, [](IEnumWbemClassObject* ptr) { if (ptr) ptr->Release(); } }; + return {tmp, [](IEnumWbemClassObject* ptr) + { + if (ptr) + ptr->Release(); + }}; }(); BOOL result = FALSE; @@ -558,7 +523,7 @@ BOOL WheatyExceptionReport::_GetWindowsVersionFromWMI(TCHAR* szVersion, DWORD cn VARIANT field; VariantInit(&field); fields->Get(L"Caption", 0, &field, nullptr, nullptr); - TCHAR buf[256] = { }; + TCHAR buf[256] = {}; ToTchar(field.bstrVal, buf); _tcsncat(szVersion, buf, cntMax); VariantClear(&field); @@ -589,16 +554,16 @@ void WheatyExceptionReport::PrintSystemInfo() ::GetSystemInfo(&SystemInfo); MEMORYSTATUS MemoryStatus; - MemoryStatus.dwLength = sizeof (MEMORYSTATUS); + MemoryStatus.dwLength = sizeof(MEMORYSTATUS); ::GlobalMemoryStatus(&MemoryStatus); TCHAR sString[1024]; Log(_T("//=====================================================\r\n")); if (_GetProcessorName(sString, countof(sString))) - Log(_T("*** Hardware ***\r\nProcessor: %s\r\nNumber Of Processors: %d\r\nPhysical Memory: %d KB (Available: %d KB)\r\nCommit Charge Limit: %d KB\r\n"), - sString, SystemInfo.dwNumberOfProcessors, MemoryStatus.dwTotalPhys/0x400, MemoryStatus.dwAvailPhys/0x400, MemoryStatus.dwTotalPageFile/0x400); + Log(_T("*** Hardware ***\r\nProcessor: %s\r\nNumber Of Processors: %d\r\nPhysical Memory: %d KB (Available: %d KB)\r\nCommit Charge Limit: %d KB\r\n"), sString, + SystemInfo.dwNumberOfProcessors, MemoryStatus.dwTotalPhys / 0x400, MemoryStatus.dwAvailPhys / 0x400, MemoryStatus.dwTotalPageFile / 0x400); else - Log(_T("*** Hardware ***\r\nProcessor: \r\nNumber Of Processors: %d\r\nPhysical Memory: %d KB (Available: %d KB)\r\nCommit Charge Limit: %d KB\r\n"), - SystemInfo.dwNumberOfProcessors, MemoryStatus.dwTotalPhys/0x400, MemoryStatus.dwAvailPhys/0x400, MemoryStatus.dwTotalPageFile/0x400); + Log(_T("*** Hardware ***\r\nProcessor: \r\nNumber Of Processors: %d\r\nPhysical Memory: %d KB (Available: %d KB)\r\nCommit Charge Limit: %d KB\r\n"), SystemInfo.dwNumberOfProcessors, + MemoryStatus.dwTotalPhys / 0x400, MemoryStatus.dwAvailPhys / 0x400, MemoryStatus.dwTotalPageFile / 0x400); if (_GetWindowsVersion(sString, countof(sString))) Log(_T("\r\n*** Operation System ***\r\n%s\r\n"), sString); @@ -609,56 +574,55 @@ void WheatyExceptionReport::PrintSystemInfo() //=========================================================================== void WheatyExceptionReport::printTracesForAllThreads(bool bWriteVariables) { - THREADENTRY32 te32; + THREADENTRY32 te32; - DWORD dwOwnerPID = GetCurrentProcessId(); - m_hProcess = GetCurrentProcess(); - // Take a snapshot of all running threads - HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - if (hThreadSnap == INVALID_HANDLE_VALUE) - return; + DWORD dwOwnerPID = GetCurrentProcessId(); + m_hProcess = GetCurrentProcess(); + // Take a snapshot of all running threads + HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if (hThreadSnap == INVALID_HANDLE_VALUE) + return; - // Fill in the size of the structure before using it. - te32.dwSize = sizeof(THREADENTRY32); + // Fill in the size of the structure before using it. + te32.dwSize = sizeof(THREADENTRY32); - // Retrieve information about the first thread, - // and exit if unsuccessful - if (!Thread32First(hThreadSnap, &te32)) - { - CloseHandle(hThreadSnap); // Must clean up the - // snapshot object! - return; - } - - // Now walk the thread list of the system, - // and display information about each thread - // associated with the specified process - do - { - if (te32.th32OwnerProcessID == dwOwnerPID) + // Retrieve information about the first thread, + // and exit if unsuccessful + if (!Thread32First(hThreadSnap, &te32)) { - CONTEXT context; - context.ContextFlags = 0xffffffff; - HANDLE threadHandle = OpenThread(THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, false, te32.th32ThreadID); - if (threadHandle) + CloseHandle(hThreadSnap); // Must clean up the + // snapshot object! + return; + } + + // Now walk the thread list of the system, + // and display information about each thread + // associated with the specified process + do + { + if (te32.th32OwnerProcessID == dwOwnerPID) { - if (GetThreadContext(threadHandle, &context)) - WriteStackDetails(&context, bWriteVariables, threadHandle); - CloseHandle(threadHandle); + CONTEXT context; + context.ContextFlags = 0xffffffff; + HANDLE threadHandle = OpenThread(THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, false, te32.th32ThreadID); + if (threadHandle) + { + if (GetThreadContext(threadHandle, &context)) + WriteStackDetails(&context, bWriteVariables, threadHandle); + CloseHandle(threadHandle); + } } - } - } while (Thread32Next(hThreadSnap, &te32)); + } while (Thread32Next(hThreadSnap, &te32)); -// Don't forget to clean up the snapshot object. - CloseHandle(hThreadSnap); + // Don't forget to clean up the snapshot object. + CloseHandle(hThreadSnap); } //=========================================================================== // Open the report file, and write the desired information to it. Called by // WheatyUnhandledExceptionFilter //=========================================================================== -void WheatyExceptionReport::GenerateExceptionReport( -PEXCEPTION_POINTERS pExceptionInfo) +void WheatyExceptionReport::GenerateExceptionReport(PEXCEPTION_POINTERS pExceptionInfo) { __try { @@ -673,9 +637,7 @@ PEXCEPTION_POINTERS pExceptionInfo) PrintSystemInfo(); // First print information about the type of fault Log(_T("\r\n//=====================================================\r\n")); - Log(_T("Exception code: %08X %s\r\n"), - pExceptionRecord->ExceptionCode, - GetExceptionString(pExceptionRecord->ExceptionCode)); + Log(_T("Exception code: %08X %s\r\n"), pExceptionRecord->ExceptionCode, GetExceptionString(pExceptionRecord->ExceptionCode)); if (pExceptionRecord->ExceptionCode == EXCEPTION_ASSERTION_FAILURE && pExceptionRecord->NumberParameters >= 2) { pExceptionRecord->ExceptionAddress = reinterpret_cast(pExceptionRecord->ExceptionInformation[1]); @@ -686,51 +648,37 @@ PEXCEPTION_POINTERS pExceptionInfo) TCHAR szFaultingModule[MAX_PATH]; DWORD section; DWORD_PTR offset; - GetLogicalAddress(pExceptionRecord->ExceptionAddress, - szFaultingModule, - sizeof(szFaultingModule), - section, offset); + GetLogicalAddress(pExceptionRecord->ExceptionAddress, szFaultingModule, sizeof(szFaultingModule), section, offset); #ifdef _M_IX86 - Log(_T("Fault address: %08X %02X:%08X %s\r\n"), - pExceptionRecord->ExceptionAddress, - section, offset, szFaultingModule); + Log(_T("Fault address: %08X %02X:%08X %s\r\n"), pExceptionRecord->ExceptionAddress, section, offset, szFaultingModule); #endif #ifdef _M_X64 - Log(_T("Fault address: %016I64X %02X:%016I64X %s\r\n"), - pExceptionRecord->ExceptionAddress, - section, offset, szFaultingModule); + Log(_T("Fault address: %016I64X %02X:%016I64X %s\r\n"), pExceptionRecord->ExceptionAddress, section, offset, szFaultingModule); #endif PCONTEXT pCtx = pExceptionInfo->ContextRecord; // Show the registers -#ifdef _M_IX86 // X86 Only! +#ifdef _M_IX86 // X86 Only! Log(_T("\r\nRegisters:\r\n")); - Log(_T("EAX:%08X\r\nEBX:%08X\r\nECX:%08X\r\nEDX:%08X\r\nESI:%08X\r\nEDI:%08X\r\n") - , pCtx->Eax, pCtx->Ebx, pCtx->Ecx, pCtx->Edx, - pCtx->Esi, pCtx->Edi); + Log(_T("EAX:%08X\r\nEBX:%08X\r\nECX:%08X\r\nEDX:%08X\r\nESI:%08X\r\nEDI:%08X\r\n"), pCtx->Eax, pCtx->Ebx, pCtx->Ecx, pCtx->Edx, pCtx->Esi, pCtx->Edi); Log(_T("CS:EIP:%04X:%08X\r\n"), pCtx->SegCs, pCtx->Eip); - Log(_T("SS:ESP:%04X:%08X EBP:%08X\r\n"), - pCtx->SegSs, pCtx->Esp, pCtx->Ebp); - Log(_T("DS:%04X ES:%04X FS:%04X GS:%04X\r\n"), - pCtx->SegDs, pCtx->SegEs, pCtx->SegFs, pCtx->SegGs); + Log(_T("SS:ESP:%04X:%08X EBP:%08X\r\n"), pCtx->SegSs, pCtx->Esp, pCtx->Ebp); + Log(_T("DS:%04X ES:%04X FS:%04X GS:%04X\r\n"), pCtx->SegDs, pCtx->SegEs, pCtx->SegFs, pCtx->SegGs); Log(_T("Flags:%08X\r\n"), pCtx->EFlags); #endif #ifdef _M_X64 Log(_T("\r\nRegisters:\r\n")); Log(_T("RAX:%016I64X\r\nRBX:%016I64X\r\nRCX:%016I64X\r\nRDX:%016I64X\r\nRSI:%016I64X\r\nRDI:%016I64X\r\n") - _T("R8: %016I64X\r\nR9: %016I64X\r\nR10:%016I64X\r\nR11:%016I64X\r\nR12:%016I64X\r\nR13:%016I64X\r\nR14:%016I64X\r\nR15:%016I64X\r\n") - , pCtx->Rax, pCtx->Rbx, pCtx->Rcx, pCtx->Rdx, - pCtx->Rsi, pCtx->Rdi, pCtx->R9, pCtx->R10, pCtx->R11, pCtx->R12, pCtx->R13, pCtx->R14, pCtx->R15); + _T("R8: %016I64X\r\nR9: %016I64X\r\nR10:%016I64X\r\nR11:%016I64X\r\nR12:%016I64X\r\nR13:%016I64X\r\nR14:%016I64X\r\nR15:%016I64X\r\n"), + pCtx->Rax, pCtx->Rbx, pCtx->Rcx, pCtx->Rdx, pCtx->Rsi, pCtx->Rdi, pCtx->R9, pCtx->R10, pCtx->R11, pCtx->R12, pCtx->R13, pCtx->R14, pCtx->R15); Log(_T("CS:RIP:%04X:%016I64X\r\n"), pCtx->SegCs, pCtx->Rip); - Log(_T("SS:RSP:%04X:%016X RBP:%08X\r\n"), - pCtx->SegSs, pCtx->Rsp, pCtx->Rbp); - Log(_T("DS:%04X ES:%04X FS:%04X GS:%04X\r\n"), - pCtx->SegDs, pCtx->SegEs, pCtx->SegFs, pCtx->SegGs); + Log(_T("SS:RSP:%04X:%016X RBP:%08X\r\n"), pCtx->SegSs, pCtx->Rsp, pCtx->Rbp); + Log(_T("DS:%04X ES:%04X FS:%04X GS:%04X\r\n"), pCtx->SegDs, pCtx->SegEs, pCtx->SegFs, pCtx->SegGs); Log(_T("Flags:%08X\r\n"), pCtx->EFlags); #endif @@ -739,8 +687,7 @@ PEXCEPTION_POINTERS pExceptionInfo) // Initialize DbgHelp if (!SymInitialize(GetCurrentProcess(), 0, TRUE)) { - Log(_T("\n\rCRITICAL ERROR.\n\r Couldn't initialize the symbol handler for process.\n\rError [%s].\n\r\n\r"), - ErrorMessage(GetLastError())); + Log(_T("\n\rCRITICAL ERROR.\n\r Couldn't initialize the symbol handler for process.\n\rError [%s].\n\r\n\r"), ErrorMessage(GetLastError())); } CONTEXT trashableContext = *pCtx; @@ -773,42 +720,42 @@ PEXCEPTION_POINTERS pExceptionInfo) //====================================================================== LPTSTR WheatyExceptionReport::GetExceptionString(DWORD dwCode) { - #define EXCEPTION(x) case EXCEPTION_##x: return _T(#x); +#define EXCEPTION(x) \ + case EXCEPTION_##x: \ + return _T(#x); switch (dwCode) { EXCEPTION(ACCESS_VIOLATION) - EXCEPTION(DATATYPE_MISALIGNMENT) - EXCEPTION(BREAKPOINT) - EXCEPTION(SINGLE_STEP) - EXCEPTION(ARRAY_BOUNDS_EXCEEDED) - EXCEPTION(FLT_DENORMAL_OPERAND) - EXCEPTION(FLT_DIVIDE_BY_ZERO) - EXCEPTION(FLT_INEXACT_RESULT) - EXCEPTION(FLT_INVALID_OPERATION) - EXCEPTION(FLT_OVERFLOW) - EXCEPTION(FLT_STACK_CHECK) - EXCEPTION(FLT_UNDERFLOW) - EXCEPTION(INT_DIVIDE_BY_ZERO) - EXCEPTION(INT_OVERFLOW) - EXCEPTION(PRIV_INSTRUCTION) - EXCEPTION(IN_PAGE_ERROR) - EXCEPTION(ILLEGAL_INSTRUCTION) - EXCEPTION(NONCONTINUABLE_EXCEPTION) - EXCEPTION(STACK_OVERFLOW) - EXCEPTION(INVALID_DISPOSITION) - EXCEPTION(GUARD_PAGE) - EXCEPTION(INVALID_HANDLE) + EXCEPTION(DATATYPE_MISALIGNMENT) + EXCEPTION(BREAKPOINT) + EXCEPTION(SINGLE_STEP) + EXCEPTION(ARRAY_BOUNDS_EXCEEDED) + EXCEPTION(FLT_DENORMAL_OPERAND) + EXCEPTION(FLT_DIVIDE_BY_ZERO) + EXCEPTION(FLT_INEXACT_RESULT) + EXCEPTION(FLT_INVALID_OPERATION) + EXCEPTION(FLT_OVERFLOW) + EXCEPTION(FLT_STACK_CHECK) + EXCEPTION(FLT_UNDERFLOW) + EXCEPTION(INT_DIVIDE_BY_ZERO) + EXCEPTION(INT_OVERFLOW) + EXCEPTION(PRIV_INSTRUCTION) + EXCEPTION(IN_PAGE_ERROR) + EXCEPTION(ILLEGAL_INSTRUCTION) + EXCEPTION(NONCONTINUABLE_EXCEPTION) + EXCEPTION(STACK_OVERFLOW) + EXCEPTION(INVALID_DISPOSITION) + EXCEPTION(GUARD_PAGE) + EXCEPTION(INVALID_HANDLE) } // If not one of the "known" exceptions, try to get the string // from NTDLL.DLL's message table. - static TCHAR szBuffer[512] = { 0 }; + static TCHAR szBuffer[512] = {0}; - FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE, - GetModuleHandle(_T("NTDLL.DLL")), - dwCode, 0, szBuffer, sizeof(szBuffer), 0); + FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE, GetModuleHandle(_T("NTDLL.DLL")), dwCode, 0, szBuffer, sizeof(szBuffer), 0); return szBuffer; } @@ -820,8 +767,7 @@ LPTSTR WheatyExceptionReport::GetExceptionString(DWORD dwCode) // Note: the szModule paramater buffer is an output buffer of length specified // by the len parameter (in characters!) //============================================================================= -BOOL WheatyExceptionReport::GetLogicalAddress( -PVOID addr, PTSTR szModule, DWORD len, DWORD& section, DWORD_PTR& offset) +BOOL WheatyExceptionReport::GetLogicalAddress(PVOID addr, PTSTR szModule, DWORD len, DWORD& section, DWORD_PTR& offset) { MEMORY_BASIC_INFORMATION mbi; @@ -844,17 +790,14 @@ PVOID addr, PTSTR szModule, DWORD len, DWORD& section, DWORD_PTR& offset) PIMAGE_SECTION_HEADER pSection = IMAGE_FIRST_SECTION(pNtHdr); - DWORD_PTR rva = (DWORD_PTR)addr - hMod; // RVA is offset from module load address + DWORD_PTR rva = (DWORD_PTR)addr - hMod; // RVA is offset from module load address // Iterate through the section table, looking for the one that encompasses // the linear address. - for (unsigned i = 0; - i < pNtHdr->FileHeader.NumberOfSections; - i++, pSection++) + for (unsigned i = 0; i < pNtHdr->FileHeader.NumberOfSections; i++, pSection++) { DWORD_PTR sectionStart = pSection->VirtualAddress; - DWORD_PTR sectionEnd = sectionStart - + DWORD_PTR(std::max(pSection->SizeOfRawData, pSection->Misc.VirtualSize)); + DWORD_PTR sectionEnd = sectionStart + DWORD_PTR(std::max(pSection->SizeOfRawData, pSection->Misc.VirtualSize)); // Is the address in this section??? if ((rva >= sectionStart) && (rva <= sectionEnd)) @@ -862,13 +805,13 @@ PVOID addr, PTSTR szModule, DWORD len, DWORD& section, DWORD_PTR& offset) // Yes, address is in the section. Calculate section and offset, // and store in the "section" & "offset" params, which were // passed by reference. - section = i+1; + section = i + 1; offset = rva - sectionStart; return TRUE; } } - return FALSE; // Should never get here! + return FALSE; // Should never get here! } // It contains SYMBOL_INFO structure plus additional @@ -878,16 +821,14 @@ struct CSymbolInfoPackage : public SYMBOL_INFO_PACKAGE CSymbolInfoPackage() { si.SizeOfStruct = sizeof(SYMBOL_INFO); - si.MaxNameLen = sizeof(name); + si.MaxNameLen = sizeof(name); } }; //============================================================ // Walks the stack, and writes the results to the report file //============================================================ -void WheatyExceptionReport::WriteStackDetails( -PCONTEXT pContext, -bool bWriteVariables, HANDLE pThreadHandle) // true if local/params should be output +void WheatyExceptionReport::WriteStackDetails(PCONTEXT pContext, bool bWriteVariables, HANDLE pThreadHandle) // true if local/params should be output { Log(_T("\r\nCall stack:\r\n")); @@ -899,44 +840,36 @@ bool bWriteVariables, HANDLE pThreadHandle) STACKFRAME64 sf; memset(&sf, 0, sizeof(sf)); - #ifdef _M_IX86 +#ifdef _M_IX86 // Initialize the STACKFRAME structure for the first call. This is only // necessary for Intel CPUs, and isn't mentioned in the documentation. - sf.AddrPC.Offset = pContext->Eip; - sf.AddrPC.Mode = AddrModeFlat; - sf.AddrStack.Offset = pContext->Esp; - sf.AddrStack.Mode = AddrModeFlat; - sf.AddrFrame.Offset = pContext->Ebp; - sf.AddrFrame.Mode = AddrModeFlat; + sf.AddrPC.Offset = pContext->Eip; + sf.AddrPC.Mode = AddrModeFlat; + sf.AddrStack.Offset = pContext->Esp; + sf.AddrStack.Mode = AddrModeFlat; + sf.AddrFrame.Offset = pContext->Ebp; + sf.AddrFrame.Mode = AddrModeFlat; dwMachineType = IMAGE_FILE_MACHINE_I386; - #endif +#endif #ifdef _M_X64 - sf.AddrPC.Offset = pContext->Rip; + sf.AddrPC.Offset = pContext->Rip; sf.AddrPC.Mode = AddrModeFlat; - sf.AddrStack.Offset = pContext->Rsp; - sf.AddrStack.Mode = AddrModeFlat; - sf.AddrFrame.Offset = pContext->Rbp; - sf.AddrFrame.Mode = AddrModeFlat; + sf.AddrStack.Offset = pContext->Rsp; + sf.AddrStack.Mode = AddrModeFlat; + sf.AddrFrame.Offset = pContext->Rbp; + sf.AddrFrame.Mode = AddrModeFlat; dwMachineType = IMAGE_FILE_MACHINE_AMD64; #endif for (;;) { // Get the next stack frame - if (! StackWalk64(dwMachineType, - m_hProcess, - pThreadHandle != NULL ? pThreadHandle : GetCurrentThread(), - &sf, - pContext, - 0, - SymFunctionTableAccess64, - SymGetModuleBase64, - 0)) + if (!StackWalk64(dwMachineType, m_hProcess, pThreadHandle != NULL ? pThreadHandle : GetCurrentThread(), &sf, pContext, 0, SymFunctionTableAccess64, SymGetModuleBase64, 0)) break; - if (0 == sf.AddrFrame.Offset) // Basic sanity check to make sure - break; // the frame is OK. Bail if not. + if (0 == sf.AddrFrame.Offset) // Basic sanity check to make sure + break; // the frame is OK. Bail if not. #ifdef _M_IX86 Log(_T("%08X %08X "), sf.AddrPC.Offset, sf.AddrFrame.Offset); #endif @@ -944,28 +877,25 @@ bool bWriteVariables, HANDLE pThreadHandle) Log(_T("%016I64X %016I64X "), sf.AddrPC.Offset, sf.AddrFrame.Offset); #endif - DWORD64 symDisplacement = 0; // Displacement of the input address, + DWORD64 symDisplacement = 0; // Displacement of the input address, // relative to the start of the symbol // Get the name of the function for this stack frame entry CSymbolInfoPackage sip; - if (SymFromAddr( - m_hProcess, // Process handle of the current process - sf.AddrPC.Offset, // Symbol address - &symDisplacement, // Address of the variable that will receive the displacement - &sip.si)) // Address of the SYMBOL_INFO structure (inside "sip" object) + if (SymFromAddr(m_hProcess, // Process handle of the current process + sf.AddrPC.Offset, // Symbol address + &symDisplacement, // Address of the variable that will receive the displacement + &sip.si)) // Address of the SYMBOL_INFO structure (inside "sip" object) { Log(_T("%hs+%I64X"), sip.si.Name, symDisplacement); - } - else // No symbol found. Print out the logical address instead. + else // No symbol found. Print out the logical address instead. { TCHAR szModule[MAX_PATH] = _T(""); DWORD section = 0; DWORD_PTR offset = 0; - GetLogicalAddress((PVOID)sf.AddrPC.Offset, - szModule, sizeof(szModule), section, offset); + GetLogicalAddress((PVOID)sf.AddrPC.Offset, szModule, sizeof(szModule), section, offset); #ifdef _M_IX86 Log(_T("%04X:%08X %s"), section, offset, szModule); #endif @@ -975,10 +905,9 @@ bool bWriteVariables, HANDLE pThreadHandle) } // Get the source line for this stack frame entry - IMAGEHLP_LINE64 lineInfo = { sizeof(IMAGEHLP_LINE64) }; + IMAGEHLP_LINE64 lineInfo = {sizeof(IMAGEHLP_LINE64)}; DWORD dwLineDisplacement; - if (SymGetLineFromAddr64(m_hProcess, sf.AddrPC.Offset, - &dwLineDisplacement, &lineInfo)) + if (SymGetLineFromAddr64(m_hProcess, sf.AddrPC.Offset, &dwLineDisplacement, &lineInfo)) { Log(_T(" %s line %u"), lineInfo.FileName, lineInfo.LineNumber); } @@ -999,24 +928,18 @@ bool bWriteVariables, HANDLE pThreadHandle) Log(_T("\r\n")); } } - } ////////////////////////////////////////////////////////////////////////////// // The function invoked by SymEnumSymbols ////////////////////////////////////////////////////////////////////////////// -BOOL CALLBACK -WheatyExceptionReport::EnumerateSymbolsCallback( -PSYMBOL_INFO pSymInfo, -ULONG /*SymbolSize*/, -PVOID UserContext) +BOOL CALLBACK WheatyExceptionReport::EnumerateSymbolsCallback(PSYMBOL_INFO pSymInfo, ULONG /*SymbolSize*/, PVOID UserContext) { __try { ClearSymbols(); FormatSymbolValue(pSymInfo, (STACKFRAME64*)UserContext); - } __except (EXCEPTION_EXECUTE_HANDLER) { @@ -1031,20 +954,18 @@ PVOID UserContext) // contents. If it's a user defined type, display the members and their // values. ////////////////////////////////////////////////////////////////////////////// -bool WheatyExceptionReport::FormatSymbolValue( -PSYMBOL_INFO pSym, -STACKFRAME64 * sf) +bool WheatyExceptionReport::FormatSymbolValue(PSYMBOL_INFO pSym, STACKFRAME64* sf) { // If it's a function, don't do anything. - if (pSym->Tag == SymTagFunction) // SymTagFunction from CVCONST.H from the DIA SDK + if (pSym->Tag == SymTagFunction) // SymTagFunction from CVCONST.H from the DIA SDK return false; - DWORD_PTR pVariable = 0; // Will point to the variable's data in memory + DWORD_PTR pVariable = 0; // Will point to the variable's data in memory if (pSym->Flags & IMAGEHLP_SYMBOL_INFO_REGRELATIVE) { // if (pSym->Register == 8) // EBP is the value 8 (in DBGHELP 5.1) - { // This may change!!! + { // This may change!!! #ifdef _M_IX86 pVariable = sf->AddrFrame.Offset; #elif _M_X64 @@ -1056,10 +977,10 @@ STACKFRAME64 * sf) // return false; } else if (pSym->Flags & IMAGEHLP_SYMBOL_INFO_REGISTER) - return false; // Don't try to report register variable + return false; // Don't try to report register variable else { - pVariable = (DWORD_PTR)pSym->Address; // It must be a global variable + pVariable = (DWORD_PTR)pSym->Address; // It must be a global variable } PushSymbolDetail(); @@ -1102,15 +1023,7 @@ STACKFRAME64 * sf) // at fundamental types. When he hit fundamental types, return // bHandled = false, so that FormatSymbolValue() will format them. ////////////////////////////////////////////////////////////////////////////// -void WheatyExceptionReport::DumpTypeIndex( -DWORD64 modBase, -DWORD dwTypeIndex, -DWORD_PTR offset, -bool & bHandled, -char const* Name, -char* /*suffix*/, -bool newSymbol, -bool logChildren) +void WheatyExceptionReport::DumpTypeIndex(DWORD64 modBase, DWORD dwTypeIndex, DWORD_PTR offset, bool& bHandled, char const* Name, char* /*suffix*/, bool newSymbol, bool logChildren) { bHandled = false; @@ -1123,9 +1036,8 @@ bool logChildren) // Get the name of the symbol. This will either be a Type name (if a UDT), // or the structure member name. - WCHAR * pwszTypeName; - if (SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_SYMNAME, - &pwszTypeName)) + WCHAR* pwszTypeName; + if (SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_SYMNAME, &pwszTypeName)) { // handle special cases if (wcscmp(pwszTypeName, L"std::basic_string,std::allocator >") == 0) @@ -1168,188 +1080,184 @@ bool logChildren) DWORD innerTypeID; switch (typeTag) { - case SymTagPointerType: - if (SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_TYPEID, &innerTypeID)) - { - if (Name != NULL && Name[0] != '\0') - symbolDetails.top().Name = Name; + case SymTagPointerType: + if (SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_TYPEID, &innerTypeID)) + { + if (Name != NULL && Name[0] != '\0') + symbolDetails.top().Name = Name; - BOOL isReference; - SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_IS_REFERENCE, &isReference); + BOOL isReference; + SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_IS_REFERENCE, &isReference); - char addressStr[40]; - memset(addressStr, 0, sizeof(addressStr)); + char addressStr[40]; + memset(addressStr, 0, sizeof(addressStr)); - if (isReference) - symbolDetails.top().Suffix += "&"; - else - symbolDetails.top().Suffix += "*"; + if (isReference) + symbolDetails.top().Suffix += "&"; + else + symbolDetails.top().Suffix += "*"; - // Try to dereference the pointer in a try/except block since it might be invalid - DWORD_PTR address = DereferenceUnsafePointer(offset); + // Try to dereference the pointer in a try/except block since it might be invalid + DWORD_PTR address = DereferenceUnsafePointer(offset); - char buffer[WER_SMALL_BUFFER_SIZE]; - FormatOutputValue(buffer, btVoid, sizeof(PVOID), (PVOID)offset, sizeof(buffer)); - symbolDetails.top().Value = buffer; + char buffer[WER_SMALL_BUFFER_SIZE]; + FormatOutputValue(buffer, btVoid, sizeof(PVOID), (PVOID)offset, sizeof(buffer)); + symbolDetails.top().Value = buffer; - if (symbolDetails.size() >= WER_MAX_NESTING_LEVEL) - logChildren = false; + if (symbolDetails.size() >= WER_MAX_NESTING_LEVEL) + logChildren = false; - // no need to log any children since the address is invalid anyway - if (address == NULL || address == DWORD_PTR(-1)) - logChildren = false; + // no need to log any children since the address is invalid anyway + if (address == NULL || address == DWORD_PTR(-1)) + logChildren = false; - DumpTypeIndex(modBase, innerTypeID, address, bHandled, Name, addressStr, false, logChildren); + DumpTypeIndex(modBase, innerTypeID, address, bHandled, Name, addressStr, false, logChildren); - if (!bHandled) - { - BasicType basicType = GetBasicType(dwTypeIndex, modBase); - if (symbolDetails.top().Type.empty()) - symbolDetails.top().Type = rgBaseType[basicType]; - - if (address == NULL) - symbolDetails.top().Value = "NULL"; - else if (address == DWORD_PTR(-1)) - symbolDetails.top().Value = ""; - else - { - // Get the size of the child member - ULONG64 length; - SymGetTypeInfo(m_hProcess, modBase, innerTypeID, TI_GET_LENGTH, &length); - char buffer2[50]; - FormatOutputValue(buffer2, basicType, length, (PVOID)address, sizeof(buffer2)); - symbolDetails.top().Value = buffer2; - } - bHandled = true; - return; - } - else if (address == NULL) + if (!bHandled) + { + BasicType basicType = GetBasicType(dwTypeIndex, modBase); + if (symbolDetails.top().Type.empty()) + symbolDetails.top().Type = rgBaseType[basicType]; + + if (address == NULL) symbolDetails.top().Value = "NULL"; else if (address == DWORD_PTR(-1)) - { symbolDetails.top().Value = ""; - bHandled = true; - return; + else + { + // Get the size of the child member + ULONG64 length; + SymGetTypeInfo(m_hProcess, modBase, innerTypeID, TI_GET_LENGTH, &length); + char buffer2[50]; + FormatOutputValue(buffer2, basicType, length, (PVOID)address, sizeof(buffer2)); + symbolDetails.top().Value = buffer2; } + bHandled = true; + return; } - break; - case SymTagData: - if (SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_TYPEID, &innerTypeID)) + else if (address == NULL) + symbolDetails.top().Value = "NULL"; + else if (address == DWORD_PTR(-1)) { - DWORD innerTypeTag; - if (!SymGetTypeInfo(m_hProcess, modBase, innerTypeID, TI_GET_SYMTAG, &innerTypeTag)) - break; - - switch (innerTypeTag) - { - case SymTagUDT: - if (symbolDetails.size() >= WER_MAX_NESTING_LEVEL) - logChildren = false; - DumpTypeIndex(modBase, innerTypeID, - offset, bHandled, symbolDetails.top().Name.c_str(), "", false, logChildren); - break; - case SymTagPointerType: - if (Name != NULL && Name[0] != '\0') - symbolDetails.top().Name = Name; - DumpTypeIndex(modBase, innerTypeID, - offset, bHandled, symbolDetails.top().Name.c_str(), "", false, logChildren); - break; - case SymTagArrayType: - DumpTypeIndex(modBase, innerTypeID, - offset, bHandled, symbolDetails.top().Name.c_str(), "", false, logChildren); - break; - default: - break; - } + symbolDetails.top().Value = ""; + bHandled = true; + return; } - break; - case SymTagArrayType: - if (SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_TYPEID, &innerTypeID)) + } + break; + case SymTagData: + if (SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_TYPEID, &innerTypeID)) + { + DWORD innerTypeTag; + if (!SymGetTypeInfo(m_hProcess, modBase, innerTypeID, TI_GET_SYMTAG, &innerTypeTag)) + break; + + switch (innerTypeTag) { - symbolDetails.top().HasChildren = true; + case SymTagUDT: + if (symbolDetails.size() >= WER_MAX_NESTING_LEVEL) + logChildren = false; + DumpTypeIndex(modBase, innerTypeID, offset, bHandled, symbolDetails.top().Name.c_str(), "", false, logChildren); + break; + case SymTagPointerType: + if (Name != NULL && Name[0] != '\0') + symbolDetails.top().Name = Name; + DumpTypeIndex(modBase, innerTypeID, offset, bHandled, symbolDetails.top().Name.c_str(), "", false, logChildren); + break; + case SymTagArrayType: + DumpTypeIndex(modBase, innerTypeID, offset, bHandled, symbolDetails.top().Name.c_str(), "", false, logChildren); + break; + default: + break; + } + } + break; + case SymTagArrayType: + if (SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_TYPEID, &innerTypeID)) + { + symbolDetails.top().HasChildren = true; - BasicType basicType = btNoType; - DumpTypeIndex(modBase, innerTypeID, - offset, bHandled, Name, "", false, false); + BasicType basicType = btNoType; + DumpTypeIndex(modBase, innerTypeID, offset, bHandled, Name, "", false, false); - // Set Value back to an empty string since the Array object itself has no value, only its elements have - std::string firstElementValue = symbolDetails.top().Value; - symbolDetails.top().Value.clear(); + // Set Value back to an empty string since the Array object itself has no value, only its elements have + std::string firstElementValue = symbolDetails.top().Value; + symbolDetails.top().Value.clear(); - DWORD elementsCount; - if (SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_COUNT, &elementsCount)) - symbolDetails.top().Suffix += "[" + std::to_string(elementsCount) + "]"; - else - symbolDetails.top().Suffix += "[]"; + DWORD elementsCount; + if (SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_COUNT, &elementsCount)) + symbolDetails.top().Suffix += "[" + std::to_string(elementsCount) + "]"; + else + symbolDetails.top().Suffix += "[]"; - if (!bHandled) - { - basicType = GetBasicType(dwTypeIndex, modBase); - if (symbolDetails.top().Type.empty()) - symbolDetails.top().Type = rgBaseType[basicType]; - bHandled = true; - } + if (!bHandled) + { + basicType = GetBasicType(dwTypeIndex, modBase); + if (symbolDetails.top().Type.empty()) + symbolDetails.top().Type = rgBaseType[basicType]; + bHandled = true; + } - // Get the size of the child member - ULONG64 length; - SymGetTypeInfo(m_hProcess, modBase, innerTypeID, TI_GET_LENGTH, &length); + // Get the size of the child member + ULONG64 length; + SymGetTypeInfo(m_hProcess, modBase, innerTypeID, TI_GET_LENGTH, &length); - char buffer[50]; - switch (basicType) + char buffer[50]; + switch (basicType) + { + case btChar: + case btStdString: + FormatOutputValue(buffer, basicType, length, (PVOID)offset, sizeof(buffer), elementsCount); + symbolDetails.top().Value = buffer; + break; + default: + for (DWORD index = 0; index < elementsCount && index < WER_MAX_ARRAY_ELEMENTS_COUNT; index++) { - case btChar: - case btStdString: - FormatOutputValue(buffer, basicType, length, (PVOID)offset, sizeof(buffer), elementsCount); - symbolDetails.top().Value = buffer; - break; - default: - for (DWORD index = 0; index < elementsCount && index < WER_MAX_ARRAY_ELEMENTS_COUNT; index++) + bool elementHandled = false; + PushSymbolDetail(); + if (index == 0) + { + if (firstElementValue.empty()) + { + FormatOutputValue(buffer, basicType, length, (PVOID)(offset + length * index), sizeof(buffer)); + firstElementValue = buffer; + } + symbolDetails.top().Value = firstElementValue; + } + else + { + DumpTypeIndex(modBase, innerTypeID, offset + length * index, elementHandled, "", "", false, false); + if (!elementHandled) { - bool elementHandled = false; - PushSymbolDetail(); - if (index == 0) - { - if (firstElementValue.empty()) - { - FormatOutputValue(buffer, basicType, length, (PVOID)(offset + length * index), sizeof(buffer)); - firstElementValue = buffer; - } - symbolDetails.top().Value = firstElementValue; - } - else - { - DumpTypeIndex(modBase, innerTypeID, offset + length * index, elementHandled, "", "", false, false); - if (!elementHandled) - { - FormatOutputValue(buffer, basicType, length, (PVOID)(offset + length * index), sizeof(buffer)); - symbolDetails.top().Value = buffer; - } - } - symbolDetails.top().Prefix.clear(); - symbolDetails.top().Type.clear(); - symbolDetails.top().Suffix = "[" + std::to_string(index) + "]"; - symbolDetails.top().Name.clear(); - PopSymbolDetail(); + FormatOutputValue(buffer, basicType, length, (PVOID)(offset + length * index), sizeof(buffer)); + symbolDetails.top().Value = buffer; } - break; + } + symbolDetails.top().Prefix.clear(); + symbolDetails.top().Type.clear(); + symbolDetails.top().Suffix = "[" + std::to_string(index) + "]"; + symbolDetails.top().Name.clear(); + PopSymbolDetail(); } - - return; + break; } - break; - case SymTagBaseType: - break; - case SymTagEnum: + return; - default: - break; + } + break; + case SymTagBaseType: + break; + case SymTagEnum: + return; + default: + break; } // Determine how many children this type has. DWORD dwChildrenCount = 0; SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_GET_CHILDRENCOUNT, &dwChildrenCount); - if (!dwChildrenCount) // If no children, we're done + if (!dwChildrenCount) // If no children, we're done return; // Prepare to get an array of "TypeIds", representing each of the children. @@ -1357,16 +1265,15 @@ bool logChildren) // TI_FINDCHILDREN_PARAMS struct has. Use derivation to accomplish this. struct FINDCHILDREN : TI_FINDCHILDREN_PARAMS { - ULONG MoreChildIds[1024*2]; - FINDCHILDREN(){Count = sizeof(MoreChildIds) / sizeof(MoreChildIds[0]);} + ULONG MoreChildIds[1024 * 2]; + FINDCHILDREN() { Count = sizeof(MoreChildIds) / sizeof(MoreChildIds[0]); } } children; children.Count = dwChildrenCount; - children.Start= 0; + children.Start = 0; // Get the array of TypeIds, one for each child type - if (!SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_FINDCHILDREN, - &children)) + if (!SymGetTypeInfo(m_hProcess, modBase, dwTypeIndex, TI_FINDCHILDREN, &children)) { return; } @@ -1377,21 +1284,15 @@ bool logChildren) DWORD symTag; SymGetTypeInfo(m_hProcess, modBase, children.ChildId[i], TI_GET_SYMTAG, &symTag); - if (symTag == SymTagFunction || - symTag == SymTagEnum || - symTag == SymTagTypedef || - symTag == SymTagVTable) + if (symTag == SymTagFunction || symTag == SymTagEnum || symTag == SymTagTypedef || symTag == SymTagVTable) continue; // Ignore static fields DWORD dataKind; SymGetTypeInfo(m_hProcess, modBase, children.ChildId[i], TI_GET_DATAKIND, &dataKind); - if (dataKind == DataIsStaticLocal || - dataKind == DataIsGlobal || - dataKind == DataIsStaticMember) + if (dataKind == DataIsStaticLocal || dataKind == DataIsGlobal || dataKind == DataIsStaticMember) continue; - symbolDetails.top().HasChildren = true; if (!logChildren) { @@ -1405,15 +1306,12 @@ bool logChildren) // Get the offset of the child member, relative to its parent DWORD dwMemberOffset; - SymGetTypeInfo(m_hProcess, modBase, children.ChildId[i], - TI_GET_OFFSET, &dwMemberOffset); + SymGetTypeInfo(m_hProcess, modBase, children.ChildId[i], TI_GET_OFFSET, &dwMemberOffset); // Calculate the address of the member DWORD_PTR dwFinalOffset = offset + dwMemberOffset; - DumpTypeIndex(modBase, - children.ChildId[i], - dwFinalOffset, bHandled2, ""/*Name */, "", true, true); + DumpTypeIndex(modBase, children.ChildId[i], dwFinalOffset, bHandled2, "" /*Name */, "", true, true); // If the child wasn't a UDT, format it appropriately if (!bHandled2) @@ -1424,8 +1322,7 @@ bool logChildren) // Get the real "TypeId" of the child. We need this for the // SymGetTypeInfo(TI_GET_TYPEID) call below. DWORD typeId; - SymGetTypeInfo(m_hProcess, modBase, children.ChildId[i], - TI_GET_TYPEID, &typeId); + SymGetTypeInfo(m_hProcess, modBase, children.ChildId[i], TI_GET_TYPEID, &typeId); // Get the size of the child member ULONG64 length; @@ -1443,72 +1340,65 @@ bool logChildren) return; } -void WheatyExceptionReport::FormatOutputValue(char * pszCurrBuffer, -BasicType basicType, -DWORD64 length, -PVOID pAddress, -size_t bufferSize, -size_t countOverride) +void WheatyExceptionReport::FormatOutputValue(char* pszCurrBuffer, BasicType basicType, DWORD64 length, PVOID pAddress, size_t bufferSize, size_t countOverride) { __try { switch (basicType) { - case btChar: + case btChar: + { + // Special case handling for char[] type + if (countOverride != 0) + length = countOverride; + else + length = strlen((char*)pAddress); + if (length > bufferSize - 6) + pszCurrBuffer += sprintf(pszCurrBuffer, "\"%.*s...\"", (DWORD)(bufferSize - 6), (char*)pAddress); + else + pszCurrBuffer += sprintf(pszCurrBuffer, "\"%.*s\"", (DWORD)length, (char*)pAddress); + break; + } + case btStdString: + { + std::string* value = static_cast(pAddress); + if (value->length() > bufferSize - 6) + pszCurrBuffer += sprintf(pszCurrBuffer, "\"%.*s...\"", (DWORD)(bufferSize - 6), value->c_str()); + else + pszCurrBuffer += sprintf(pszCurrBuffer, "\"%s\"", value->c_str()); + break; + } + default: + // Format appropriately (assuming it's a 1, 2, or 4 bytes (!!!) + if (length == 1) + pszCurrBuffer += sprintf(pszCurrBuffer, "0x%X", *(PBYTE)pAddress); + else if (length == 2) + pszCurrBuffer += sprintf(pszCurrBuffer, "0x%X", *(PWORD)pAddress); + else if (length == 4) { - // Special case handling for char[] type - if (countOverride != 0) - length = countOverride; - else - length = strlen((char*)pAddress); - if (length > bufferSize - 6) - pszCurrBuffer += sprintf(pszCurrBuffer, "\"%.*s...\"", (DWORD)(bufferSize - 6), (char*)pAddress); + if (basicType == btFloat) + pszCurrBuffer += sprintf(pszCurrBuffer, "%f", *(PFLOAT)pAddress); else - pszCurrBuffer += sprintf(pszCurrBuffer, "\"%.*s\"", (DWORD)length, (char*)pAddress); - break; + pszCurrBuffer += sprintf(pszCurrBuffer, "0x%X", *(PDWORD)pAddress); } - case btStdString: + else if (length == 8) { - std::string* value = static_cast(pAddress); - if (value->length() > bufferSize - 6) - pszCurrBuffer += sprintf(pszCurrBuffer, "\"%.*s...\"", (DWORD)(bufferSize - 6), value->c_str()); - else - pszCurrBuffer += sprintf(pszCurrBuffer, "\"%s\"", value->c_str()); - break; - } - default: - // Format appropriately (assuming it's a 1, 2, or 4 bytes (!!!) - if (length == 1) - pszCurrBuffer += sprintf(pszCurrBuffer, "0x%X", *(PBYTE)pAddress); - else if (length == 2) - pszCurrBuffer += sprintf(pszCurrBuffer, "0x%X", *(PWORD)pAddress); - else if (length == 4) + if (basicType == btFloat) { - if (basicType == btFloat) - pszCurrBuffer += sprintf(pszCurrBuffer, "%f", *(PFLOAT)pAddress); - else - pszCurrBuffer += sprintf(pszCurrBuffer, "0x%X", *(PDWORD)pAddress); - } - else if (length == 8) - { - if (basicType == btFloat) - { - pszCurrBuffer += sprintf(pszCurrBuffer, "%f", - *(double *)pAddress); - } - else - pszCurrBuffer += sprintf(pszCurrBuffer, "0x%I64X", - *(DWORD64*)pAddress); + pszCurrBuffer += sprintf(pszCurrBuffer, "%f", *(double*)pAddress); } else - { - #if _WIN64 - pszCurrBuffer += sprintf(pszCurrBuffer, "0x%I64X", (DWORD64)pAddress); - #else - pszCurrBuffer += sprintf(pszCurrBuffer, "0x%X", (DWORD)pAddress); - #endif - } - break; + pszCurrBuffer += sprintf(pszCurrBuffer, "0x%I64X", *(DWORD64*)pAddress); + } + else + { +#if _WIN64 + pszCurrBuffer += sprintf(pszCurrBuffer, "0x%I64X", (DWORD64)pAddress); +#else + pszCurrBuffer += sprintf(pszCurrBuffer, "0x%X", (DWORD)pAddress); +#endif + } + break; } } __except (EXCEPTION_EXECUTE_HANDLER) @@ -1521,12 +1411,10 @@ size_t countOverride) } } -BasicType -WheatyExceptionReport::GetBasicType(DWORD typeIndex, DWORD64 modBase) +BasicType WheatyExceptionReport::GetBasicType(DWORD typeIndex, DWORD64 modBase) { BasicType basicType; - if (SymGetTypeInfo(m_hProcess, modBase, typeIndex, - TI_GET_BASETYPE, &basicType)) + if (SymGetTypeInfo(m_hProcess, modBase, typeIndex, TI_GET_BASETYPE, &basicType)) { return basicType; } @@ -1536,8 +1424,7 @@ WheatyExceptionReport::GetBasicType(DWORD typeIndex, DWORD64 modBase) DWORD typeId; if (SymGetTypeInfo(m_hProcess, modBase, typeIndex, TI_GET_TYPEID, &typeId)) { - if (SymGetTypeInfo(m_hProcess, modBase, typeId, TI_GET_BASETYPE, - &basicType)) + if (SymGetTypeInfo(m_hProcess, modBase, typeId, TI_GET_BASETYPE, &basicType)) { return basicType; } @@ -1562,7 +1449,7 @@ DWORD_PTR WheatyExceptionReport::DereferenceUnsafePointer(DWORD_PTR address) // Helper function that writes to the report file, and allows the user to use // printf style formating //============================================================================ -int __cdecl WheatyExceptionReport::Log(const TCHAR * format, ...) +int __cdecl WheatyExceptionReport::Log(const TCHAR* format, ...) { int retValue; va_list argptr; @@ -1581,7 +1468,7 @@ int __cdecl WheatyExceptionReport::Log(const TCHAR * format, ...) return retValue; } -int __cdecl WheatyExceptionReport::StackLog(const TCHAR * format, va_list argptr) +int __cdecl WheatyExceptionReport::StackLog(const TCHAR* format, va_list argptr) { int retValue; DWORD cbWritten; @@ -1593,7 +1480,7 @@ int __cdecl WheatyExceptionReport::StackLog(const TCHAR * format, va_list argptr return retValue; } -int __cdecl WheatyExceptionReport::HeapLog(const TCHAR * format, va_list argptr) +int __cdecl WheatyExceptionReport::HeapLog(const TCHAR* format, va_list argptr) { int retValue = 0; DWORD cbWritten; @@ -1608,10 +1495,7 @@ int __cdecl WheatyExceptionReport::HeapLog(const TCHAR * format, va_list argptr) return retValue; } -bool WheatyExceptionReport::StoreSymbol(DWORD type, DWORD_PTR offset) -{ - return symbols.insert(SymbolPair(type, offset)).second; -} +bool WheatyExceptionReport::StoreSymbol(DWORD type, DWORD_PTR offset) { return symbols.insert(SymbolPair(type, offset)).second; } void WheatyExceptionReport::ClearSymbols() { @@ -1651,4 +1535,4 @@ void WheatyExceptionReport::PrintSymbolDetail() return; } -#endif // _WIN32 +#endif // FC_PLATFORM_WINDOWS diff --git a/src/common/Logging/Log.h b/src/common/Logging/Log.h index 3a2566f2..7e321fb7 100644 --- a/src/common/Logging/Log.h +++ b/src/common/Logging/Log.h @@ -144,7 +144,7 @@ class FC_COMMON_API Log #ifdef PERFORMANCE_PROFILING #define LOG_MESSAGE_BODY(filterType__, level__, ...) ((void)0) -#elif FC_PLATFORM != FC_PLATFORM_WINDOWS +#elif FC_PLATFORM == FC_PLATFORM_UNIX || FC_PLATFORM == FC_PLATFORM_APPLE void check_args(char const*, ...) ATTR_PRINTF(1, 2); void check_args(std::string const&, ...); diff --git a/src/common/Metric/Metric.h b/src/common/Metric/Metric.h index 6c44d723..44ed53c6 100644 --- a/src/common/Metric/Metric.h +++ b/src/common/Metric/Metric.h @@ -124,7 +124,7 @@ class FC_COMMON_API Metric #ifdef PERFORMANCE_PROFILING #define FC_METRIC_EVENT(category, title, description) ((void)0) #define FC_METRIC_VALUE(category, value) ((void)0) -#elif FC_PLATFORM != FC_PLATFORM_WINDOWS +#elif FC_PLATFORM == FC_PLATFORM_UNIX #define FC_METRIC_EVENT(category, title, description) \ do { \ if (sMetric->IsEnabled()) \ diff --git a/src/common/Platform/ServiceWin32.cpp b/src/common/Platform/ServiceWin32.cpp index d20dd960..5de717a2 100644 --- a/src/common/Platform/ServiceWin32.cpp +++ b/src/common/Platform/ServiceWin32.cpp @@ -15,7 +15,7 @@ * with this program. If not, see . */ -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS #include "Common.h" #include "Log.h" @@ -259,4 +259,4 @@ bool WinServiceRun() } return true; } -#endif +#endif // FC_PLATFORM_WINDOWS diff --git a/src/common/Platform/ServiceWin32.h b/src/common/Platform/ServiceWin32.h index a820341d..b0224080 100644 --- a/src/common/Platform/ServiceWin32.h +++ b/src/common/Platform/ServiceWin32.h @@ -15,7 +15,7 @@ * with this program. If not, see . */ -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS #ifndef _WIN32_SERVICE_ #define _WIN32_SERVICE_ @@ -24,4 +24,4 @@ bool WinServiceUninstall(); bool WinServiceRun(); #endif // _WIN32_SERVICE_ -#endif // _WIN32 +#endif // FC_PLATFORM_WINDOWS diff --git a/src/common/Threading/ProcessPriority.cpp b/src/common/Threading/ProcessPriority.cpp index 70c553e0..2711832f 100644 --- a/src/common/Threading/ProcessPriority.cpp +++ b/src/common/Threading/ProcessPriority.cpp @@ -18,9 +18,9 @@ #include "ProcessPriority.h" #include "Log.h" -#ifdef _WIN32 // Windows +#if FC_PLATFORM == FC_PLATFORM_WINDOWS // Windows #include -#elif defined(__linux__) +#elif FC_PLATFORM == FC_PLATFORM_UNIX #include #include #define PROCESS_HIGH_PRIORITY -15 // [-20, 19], default is 0 @@ -29,7 +29,7 @@ void SetProcessPriority(std::string const& logChannel, uint32 affinity, bool highPriority) { ///- Handle affinity for multiple processors and process priority -#ifdef _WIN32 // Windows +#if FC_PLATFORM == FC_PLATFORM_WINDOWS // Windows HANDLE hProcess = GetCurrentProcess(); if (affinity > 0) @@ -59,7 +59,7 @@ void SetProcessPriority(std::string const& logChannel, uint32 affinity, bool hig LOG_ERROR(logChannel, "Can't set process priority class."); } -#elif defined(__linux__) // Linux +#elif FC_PLATFORM == FC_PLATFORM_UNIX // Linux if (affinity > 0) { diff --git a/src/common/Utilities/Util.cpp b/src/common/Utilities/Util.cpp index 06d6b0bb..c1b3fe7d 100644 --- a/src/common/Utilities/Util.cpp +++ b/src/common/Utilities/Util.cpp @@ -102,7 +102,7 @@ void stripLineInvisibleChars(std::string& str) str.clear(); } -#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) +#if FC_PLATFORM == FC_PLATFORM_WINDOWS struct tm* localtime_r(time_t const* time, struct tm* result) { localtime_s(result, time); @@ -119,7 +119,7 @@ tm TimeBreakdown(time_t time) time_t LocalTimeToUTCTime(time_t time) { -#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) +#if FC_PLATFORM == FC_PLATFORM_WINDOWS return time + _timezone; #else return time + timezone; @@ -287,7 +287,7 @@ uint32 CreatePIDFile(std::string const& filename) uint32 GetPID() { -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS DWORD pid = GetCurrentProcessId(); #else pid_t pid = getpid(); diff --git a/src/server/authserver/Main.cpp b/src/server/authserver/Main.cpp index cb62640c..cc9fb562 100644 --- a/src/server/authserver/Main.cpp +++ b/src/server/authserver/Main.cpp @@ -38,13 +38,16 @@ #include "ProcessPriority.h" #include "RealmList.h" #include "Util.h" + +#include +#include + #include #include #include + #include #include -#include -#include using boost::asio::ip::tcp; using namespace boost::program_options; diff --git a/src/server/database/Database/MySQLConnection.cpp b/src/server/database/Database/MySQLConnection.cpp index 3ceb8ca1..ce162d8c 100644 --- a/src/server/database/Database/MySQLConnection.cpp +++ b/src/server/database/Database/MySQLConnection.cpp @@ -99,7 +99,7 @@ uint32 MySQLConnection::Open() mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8"); //mysql_options(mysqlInit, MYSQL_OPT_READ_TIMEOUT, (char const*)&timeout); - #ifdef _WIN32 + #if FC_PLATFORM == FC_PLATFORM_WINDOWS if (m_connectionInfo.host == ".") // named pipe use option (Windows) { unsigned int opt = MYSQL_PROTOCOL_PIPE; diff --git a/src/server/database/Database/MySQLWorkaround.h b/src/server/database/Database/MySQLWorkaround.h index 65c6cae9..ce2d8916 100644 --- a/src/server/database/Database/MySQLWorkaround.h +++ b/src/server/database/Database/MySQLWorkaround.h @@ -15,7 +15,7 @@ * with this program. If not, see . */ -#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 #include #endif #include diff --git a/src/server/database/Updater/DBUpdater.cpp b/src/server/database/Updater/DBUpdater.cpp index 5af73d45..45334974 100644 --- a/src/server/database/Updater/DBUpdater.cpp +++ b/src/server/database/Updater/DBUpdater.cpp @@ -412,7 +412,7 @@ void DBUpdater::ApplyFile( args.emplace_back("-p" + password); // Check if we want to connect through ip or socket (Unix only) -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS if (host == ".") args.emplace_back("--protocol=PIPE"); diff --git a/src/server/game/Scripting/ScriptReloadMgr.cpp b/src/server/game/Scripting/ScriptReloadMgr.cpp index b8b7e736..d741342f 100644 --- a/src/server/game/Scripting/ScriptReloadMgr.cpp +++ b/src/server/game/Scripting/ScriptReloadMgr.cpp @@ -1327,7 +1327,7 @@ class HotSwapScriptReloadMgr final auto current_path = fs::current_path(); - #if FC_PLATFORM != FC_PLATFORM_WINDOWS + #if FC_PLATFORM == FC_PLATFORM_UNIX // The worldserver location is ${CMAKE_INSTALL_PREFIX}/bin // on all other platforms then windows current_path = current_path.parent_path(); diff --git a/src/server/shared/Networking/AsyncAcceptor.h b/src/server/shared/Networking/AsyncAcceptor.h index 67e180f5..ba23966a 100644 --- a/src/server/shared/Networking/AsyncAcceptor.h +++ b/src/server/shared/Networking/AsyncAcceptor.h @@ -79,7 +79,7 @@ class AsyncAcceptor return false; } -#if FC_PLATFORM != FC_PLATFORM_WINDOWS +#if FC_PLATFORM == FC_PLATFORM_UNIX _acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true), errorCode); if (errorCode) { diff --git a/src/server/worldserver/CommandLine/CliRunnable.cpp b/src/server/worldserver/CommandLine/CliRunnable.cpp index ee5feb3b..817e1d96 100644 --- a/src/server/worldserver/CommandLine/CliRunnable.cpp +++ b/src/server/worldserver/CommandLine/CliRunnable.cpp @@ -29,164 +29,180 @@ #include "Log.h" #include "Util.h" -#if FC_PLATFORM != FC_PLATFORM_WINDOWS +#if FC_PLATFORM == FC_PLATFORM_UNIX || FC_PLATFORM == FC_PLATFORM_APPLE #include "Chat.h" #include #include -namespace Firelands::Impl::Readline { +namespace Firelands::Impl::Readline +{ -char *command_finder(char const *text, int state) { - static size_t idx, len; - char const *ret; - std::vector const &cmd = ChatHandler::getCommandTable(); + char* command_finder(char const* text, int state) + { + static size_t idx, len; + char const* ret; + std::vector const& cmd = ChatHandler::getCommandTable(); - if (!state) { - idx = 0; - len = strlen(text); - } - - while (idx < cmd.size()) { - ret = cmd[idx].Name; - if (!cmd[idx].AllowConsole) { - ++idx; - continue; - } + if (!state) + { + idx = 0; + len = strlen(text); + } - ++idx; - // printf("Checking %s \n", cmd[idx].Name); - if (strncmp(ret, text, len) == 0) - return strdup(ret); - } + while (idx < cmd.size()) + { + ret = cmd[idx].Name; + if (!cmd[idx].AllowConsole) + { + ++idx; + continue; + } + + ++idx; + // printf("Checking %s \n", cmd[idx].Name); + if (strncmp(ret, text, len) == 0) + return strdup(ret); + } - return ((char *)nullptr); -} + return ((char*)nullptr); + } -char **cli_completion(char const *text, int start, int /*end*/) { - char **matches = nullptr; + char** cli_completion(char const* text, int start, int /*end*/) + { + char** matches = nullptr; - if (start) - ::rl_bind_key('\t', rl_complete); - else - matches = ::rl_completion_matches((char *)text, &command_finder); - return matches; -} + if (start) + ::rl_bind_key('\t', rl_complete); + else + matches = ::rl_completion_matches((char*)text, &command_finder); + return matches; + } -int cli_hook_func() { - if (World::IsStopped()) - ::rl_done = 1; - return 0; -} + int cli_hook_func() + { + if (World::IsStopped()) + ::rl_done = 1; + return 0; + } } // namespace Firelands::Impl::Readline #endif -void utf8print(void * /*arg*/, char const *str) { +void utf8print(void* /*arg*/, char const* str) +{ #if FC_PLATFORM == FC_PLATFORM_WINDOWS - wchar_t wtemp_buf[6000]; - size_t wtemp_len = 6000 - 1; - if (!Utf8toWStr(str, strlen(str), wtemp_buf, wtemp_len)) - return; - - char temp_buf[6000]; - CharToOemBuffW(&wtemp_buf[0], &temp_buf[0], wtemp_len + 1); - printf(temp_buf); + wchar_t wtemp_buf[6000]; + size_t wtemp_len = 6000 - 1; + if (!Utf8toWStr(str, strlen(str), wtemp_buf, wtemp_len)) + return; + + char temp_buf[6000]; + CharToOemBuffW(&wtemp_buf[0], &temp_buf[0], wtemp_len + 1); + printf(temp_buf); #else - { - printf("%s", str); - fflush(stdout); - } + { + printf("%s", str); + fflush(stdout); + } #endif } -void commandFinished(void *, bool /*success*/) { - printf("FC> "); - fflush(stdout); +void commandFinished(void*, bool /*success*/) +{ + printf("FC> "); + fflush(stdout); } -#ifdef linux +#if FC_PLATFORM == FC_PLATFORM_UNIX // Non-blocking keypress detector, when return pressed, return 1, else always // return 0 -int kb_hit_return() { - struct timeval tv; - fd_set fds; - tv.tv_sec = 0; - tv.tv_usec = 0; - FD_ZERO(&fds); - FD_SET(STDIN_FILENO, &fds); - select(STDIN_FILENO + 1, &fds, nullptr, nullptr, &tv); - return FD_ISSET(STDIN_FILENO, &fds); +int kb_hit_return() +{ + struct timeval tv; + fd_set fds; + tv.tv_sec = 0; + tv.tv_usec = 0; + FD_ZERO(&fds); + FD_SET(STDIN_FILENO, &fds); + select(STDIN_FILENO + 1, &fds, nullptr, nullptr, &tv); + return FD_ISSET(STDIN_FILENO, &fds); } #endif /// %Thread start -void CliThread() { - ///- Display the list of available CLI functions then beep - // LOG_INFO("server.worldserver", ""); -#if FC_PLATFORM != FC_PLATFORM_WINDOWS - ::rl_attempted_completion_function = &Firelands::Impl::Readline::cli_completion; - ::rl_event_hook = &Firelands::Impl::Readline::cli_hook_func; +void CliThread() +{ + ///- Display the list of available CLI functions then beep + // LOG_INFO("server.worldserver", ""); +#if FC_PLATFORM == FC_PLATFORM_UNIX + ::rl_attempted_completion_function = &Firelands::Impl::Readline::cli_completion; + ::rl_event_hook = &Firelands::Impl::Readline::cli_hook_func; #endif - if (sConfigMgr->GetBoolDefault("BeepAtStart", true)) - printf("\a"); // \a = Alert + if (sConfigMgr->GetBoolDefault("BeepAtStart", true)) + printf("\a"); // \a = Alert - // print this here the first time - // later it will be printed after command queue updates - printf("FC>"); + // print this here the first time + // later it will be printed after command queue updates + printf("FC>"); - ///- As long as the World is running (no World::m_stopEvent), get the command - /// line and handle it - while (!World::IsStopped()) { - fflush(stdout); + ///- As long as the World is running (no World::m_stopEvent), get the command + /// line and handle it + while (!World::IsStopped()) + { + fflush(stdout); - char *command_str; // = fgets(commandbuf, sizeof(commandbuf), stdin); + char* command_str; // = fgets(commandbuf, sizeof(commandbuf), stdin); #if FC_PLATFORM == FC_PLATFORM_WINDOWS - char commandbuf[256]; - command_str = fgets(commandbuf, sizeof(commandbuf), stdin); + char commandbuf[256]; + command_str = fgets(commandbuf, sizeof(commandbuf), stdin); #else - command_str = readline("FC>"); - rl_bind_key('\t', rl_complete); + command_str = readline("FC>"); + rl_bind_key('\t', rl_complete); #endif - if (command_str != nullptr) { - for (int x = 0; command_str[x]; ++x) - if (command_str[x] == '\r' || command_str[x] == '\n') { - command_str[x] = 0; - break; - } - - if (!*command_str) { + if (command_str != nullptr) + { + for (int x = 0; command_str[x]; ++x) + if (command_str[x] == '\r' || command_str[x] == '\n') + { + command_str[x] = 0; + break; + } + + if (!*command_str) + { #if FC_PLATFORM == FC_PLATFORM_WINDOWS - printf("FC>"); + printf("FC>"); #else - free(command_str); + free(command_str); #endif - continue; - } + continue; + } - std::string command; - if (!consoleToUtf8(command_str, - command)) // convert from console encoding to utf8 - { + std::string command; + if (!consoleToUtf8(command_str, + command)) // convert from console encoding to utf8 + { #if FC_PLATFORM == FC_PLATFORM_WINDOWS - printf("FC>"); + printf("FC>"); #else - free(command_str); + free(command_str); #endif - continue; - } - - fflush(stdout); - sWorld->QueueCliCommand(new CliCommandHolder( - nullptr, command.c_str(), &utf8print, &commandFinished)); -#if FC_PLATFORM != FC_PLATFORM_WINDOWS - add_history(command.c_str()); - free(command_str); + continue; + } + + fflush(stdout); + sWorld->QueueCliCommand(new CliCommandHolder(nullptr, command.c_str(), &utf8print, &commandFinished)); +#if FC_PLATFORM == FC_PLATFORM_UNIX + add_history(command.c_str()); + free(command_str); #endif - } else if (feof(stdin)) { - World::StopNow(SHUTDOWN_EXIT_CODE); + } + else if (feof(stdin)) + { + World::StopNow(SHUTDOWN_EXIT_CODE); + } } - } } diff --git a/src/server/worldserver/FCSoap/FCSoap.cpp b/src/server/worldserver/FCSoap/FCSoap.cpp index f7de44a6..aafea8c2 100644 --- a/src/server/worldserver/FCSoap/FCSoap.cpp +++ b/src/server/worldserver/FCSoap/FCSoap.cpp @@ -25,112 +25,119 @@ #include "soapH.h" #include "soapStub.h" -void TCSoapThread(const std::string& host, uint16 port) { - struct soap soap; - soap_init(&soap); - soap_set_imode(&soap, SOAP_C_UTFSTRING); - soap_set_omode(&soap, SOAP_C_UTFSTRING); - -#if FC_PLATFORM != FC_PLATFORM_WINDOWS - soap.bind_flags = SO_REUSEADDR; +void TCSoapThread(const std::string& host, uint16 port) +{ + struct soap soap; + soap_init(&soap); + soap_set_imode(&soap, SOAP_C_UTFSTRING); + soap_set_omode(&soap, SOAP_C_UTFSTRING); + +#if FC_PLATFORM == FC_PLATFORM_UNIX + soap.bind_flags = SO_REUSEADDR; #endif - // check every 3 seconds if world ended - soap.accept_timeout = 3; - soap.recv_timeout = 5; - soap.send_timeout = 5; - if (!soap_valid_socket(soap_bind(&soap, host.c_str(), port, 100))) { - LOG_ERROR("network.soap", "Couldn't bind to %s:%d", host.c_str(), port); - exit(-1); - } - - LOG_INFO("network.soap", "Bound to http://%s:%d", host.c_str(), port); - - while (!World::IsStopped()) { - if (!soap_valid_socket(soap_accept(&soap))) - continue; // ran into an accept timeout - - LOG_DEBUG("network.soap", "Accepted connection from IP=%d.%d.%d.%d", - (int)(soap.ip >> 24) & 0xFF, (int)(soap.ip >> 16) & 0xFF, - (int)(soap.ip >> 8) & 0xFF, (int)soap.ip & 0xFF); - struct soap* thread_soap = soap_copy(&soap); // make a safe copy - process_message(thread_soap); - } - - soap_destroy(&soap); - soap_end(&soap); - soap_done(&soap); + // check every 3 seconds if world ended + soap.accept_timeout = 3; + soap.recv_timeout = 5; + soap.send_timeout = 5; + if (!soap_valid_socket(soap_bind(&soap, host.c_str(), port, 100))) + { + LOG_ERROR("network.soap", "Couldn't bind to %s:%d", host.c_str(), port); + exit(-1); + } + + LOG_INFO("network.soap", "Bound to http://%s:%d", host.c_str(), port); + + while (!World::IsStopped()) + { + if (!soap_valid_socket(soap_accept(&soap))) + continue; // ran into an accept timeout + + LOG_DEBUG("network.soap", "Accepted connection from IP=%d.%d.%d.%d", (int)(soap.ip >> 24) & 0xFF, (int)(soap.ip >> 16) & 0xFF, (int)(soap.ip >> 8) & 0xFF, (int)soap.ip & 0xFF); + struct soap* thread_soap = soap_copy(&soap); // make a safe copy + process_message(thread_soap); + } + + soap_destroy(&soap); + soap_end(&soap); + soap_done(&soap); } -void process_message(struct soap* soap_message) { - LOG_TRACE("network.soap", "SOAPWorkingThread::process_message"); +void process_message(struct soap* soap_message) +{ + LOG_TRACE("network.soap", "SOAPWorkingThread::process_message"); - soap_serve(soap_message); - soap_destroy(soap_message); // dealloc C++ data - soap_end(soap_message); // dealloc data and clean up - soap_free(soap_message); // detach soap struct and free up the memory + soap_serve(soap_message); + soap_destroy(soap_message); // dealloc C++ data + soap_end(soap_message); // dealloc data and clean up + soap_free(soap_message); // detach soap struct and free up the memory } /* Code used for generating stubs: int ns1__executeCommand(char* command, char** result); */ -int ns1__executeCommand(soap* soap, char* command, char** result) { - // security check - if (!soap->userid || !soap->passwd) { - LOG_INFO("network.soap", "Client didn't provide login information"); - return 401; - } - - uint32 accountId = AccountMgr::GetId(soap->userid); - if (!accountId) { - LOG_INFO("network.soap", "Client used invalid username '%s'", soap->userid); - return 401; - } - - if (!AccountMgr::CheckPassword(accountId, soap->passwd)) { - LOG_INFO("network.soap", "Invalid password for account '%s'", soap->userid); - return 401; - } - - if (AccountMgr::GetSecurity(accountId, realm.Id.Realm) < SEC_ADMINISTRATOR) { - LOG_INFO("network.soap", "%s's gmlevel is too low", soap->userid); - return 403; - } - - if (!command || !*command) - return soap_sender_fault(soap, "Command can not be empty", - "The supplied command was an empty string"); - - LOG_INFO("network.soap", "Received command '%s'", command); - SOAPCommand connection; - - // commands are executed in the world thread. We have to wait for them to be - // completed - { - // CliCommandHolder will be deleted from world, accessing after queueing is - // NOT safe - CliCommandHolder* cmd = - new CliCommandHolder(&connection, command, &SOAPCommand::print, - &SOAPCommand::commandFinished); - sWorld->QueueCliCommand(cmd); - } - - // Wait until the command has finished executing - connection.finishedPromise.get_future().wait(); - - // The command has finished executing already - char* printBuffer = soap_strdup(soap, connection.m_printBuffer.c_str()); - if (connection.hasCommandSucceeded()) { - *result = printBuffer; - return SOAP_OK; - } else - return soap_sender_fault(soap, printBuffer, printBuffer); +int ns1__executeCommand(soap* soap, char* command, char** result) +{ + // security check + if (!soap->userid || !soap->passwd) + { + LOG_INFO("network.soap", "Client didn't provide login information"); + return 401; + } + + uint32 accountId = AccountMgr::GetId(soap->userid); + if (!accountId) + { + LOG_INFO("network.soap", "Client used invalid username '%s'", soap->userid); + return 401; + } + + if (!AccountMgr::CheckPassword(accountId, soap->passwd)) + { + LOG_INFO("network.soap", "Invalid password for account '%s'", soap->userid); + return 401; + } + + if (AccountMgr::GetSecurity(accountId, realm.Id.Realm) < SEC_ADMINISTRATOR) + { + LOG_INFO("network.soap", "%s's gmlevel is too low", soap->userid); + return 403; + } + + if (!command || !*command) + return soap_sender_fault(soap, "Command can not be empty", "The supplied command was an empty string"); + + LOG_INFO("network.soap", "Received command '%s'", command); + SOAPCommand connection; + + // commands are executed in the world thread. We have to wait for them to be + // completed + { + // CliCommandHolder will be deleted from world, accessing after queueing is + // NOT safe + CliCommandHolder* cmd = new CliCommandHolder(&connection, command, &SOAPCommand::print, &SOAPCommand::commandFinished); + sWorld->QueueCliCommand(cmd); + } + + // Wait until the command has finished executing + connection.finishedPromise.get_future().wait(); + + // The command has finished executing already + char* printBuffer = soap_strdup(soap, connection.m_printBuffer.c_str()); + if (connection.hasCommandSucceeded()) + { + *result = printBuffer; + return SOAP_OK; + } + else + return soap_sender_fault(soap, printBuffer, printBuffer); } -void SOAPCommand::commandFinished(void* soapconnection, bool success) { - SOAPCommand* con = (SOAPCommand*)soapconnection; - con->setCommandSuccess(success); +void SOAPCommand::commandFinished(void* soapconnection, bool success) +{ + SOAPCommand* con = (SOAPCommand*)soapconnection; + con->setCommandSuccess(success); } //////////////////////////////////////////////////////////////////////////////// @@ -139,14 +146,8 @@ void SOAPCommand::commandFinished(void* soapconnection, bool success) { // //////////////////////////////////////////////////////////////////////////////// -struct Namespace namespaces[] = { - {"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/", nullptr, - nullptr}, // must be first - {"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/", nullptr, - nullptr}, // must be second - {"xsi", "http://www.w3.org/1999/XMLSchema-instance", - "http://www.w3.org/*/XMLSchema-instance", nullptr}, - {"xsd", "http://www.w3.org/1999/XMLSchema", "http://www.w3.org/*/XMLSchema", - nullptr}, - {"ns1", "urn:TC", nullptr, nullptr}, // "ns1" namespace prefix +struct Namespace namespaces[] = {{"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/", nullptr, nullptr}, // must be first + {"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/", nullptr, nullptr}, // must be second + {"xsi", "http://www.w3.org/1999/XMLSchema-instance", "http://www.w3.org/*/XMLSchema-instance", nullptr}, {"xsd", "http://www.w3.org/1999/XMLSchema", "http://www.w3.org/*/XMLSchema", nullptr}, + {"ns1", "urn:TC", nullptr, nullptr}, // "ns1" namespace prefix {nullptr, nullptr, nullptr, nullptr}}; diff --git a/src/server/worldserver/Main.cpp b/src/server/worldserver/Main.cpp index c46c4019..51e4d3b0 100644 --- a/src/server/worldserver/Main.cpp +++ b/src/server/worldserver/Main.cpp @@ -53,15 +53,18 @@ #include "World.h" #include "WorldSocket.h" #include "WorldSocketMgr.h" + +#include +#include + #include #include #include + #include #include -#include -#include -#ifdef _WIN32 // ugly as hell +#if FC_PLATFORM == FC_PLATFORM_WINDOWS // ugly as hell #pragma comment(lib, "iphlpapi.lib") #endif @@ -72,7 +75,7 @@ namespace fs = boost::filesystem; #define _FIRELANDS_CORE_CONFIG "worldserver.conf" #endif -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS #include "ServiceWin32.h" char serviceName[] = "worldserver"; char serviceLongName[] = "Firelands world service"; @@ -135,7 +138,7 @@ extern int main(int argc, char **argv) if (vm.count("help") || vm.count("version")) return 0; -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS if (configService.compare("install") == 0) return WinServiceInstall() == true ? 0 : 1; else if (configService.compare("uninstall") == 0) @@ -363,7 +366,7 @@ extern int main(int argc, char **argv) // Launch CliRunnable thread std::shared_ptr cliThread; -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS if (sConfigMgr->GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1) /* need disable console in service mode*/) #else if (sConfigMgr->GetBoolDefault("Console.Enable", true)) @@ -416,7 +419,7 @@ void ShutdownCLIThread(std::thread *cliThread) { if (cliThread != nullptr) { -#ifdef _WIN32 +#if FC_PLATFORM_WINDOWS // First try to cancel any I/O in the CLI thread if (!CancelSynchronousIo(cliThread->native_handle())) { @@ -496,7 +499,7 @@ void WorldUpdateLoop() sWorld->Update(diff); realPrevTime = realCurrTime; -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS if (m_ServiceStatus == 0) World::StopNow(SHUTDOWN_EXIT_CODE); @@ -686,7 +689,7 @@ variables_map GetConsoleArguments(int argc, char **argv, fs::path &configFile, s options_description all("Allowed options"); all.add_options()("help,h", "print usage message")("version,v", "print version build info")( "config,c", value(&configFile)->default_value(fs::absolute(_FIRELANDS_CORE_CONFIG)), "use as configuration file")("update-databases-only,u", "updates databases only"); -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS options_description win("Windows platform specific options"); win.add_options()("service,s", value(&configService)->default_value(""), "Windows service options: [install | uninstall]"); diff --git a/src/tools/map_extractor/System.cpp b/src/tools/map_extractor/System.cpp index 75e3bbce..c4c4d0b2 100644 --- a/src/tools/map_extractor/System.cpp +++ b/src/tools/map_extractor/System.cpp @@ -32,7 +32,7 @@ #undef PLATFORM_WINDOWS #endif -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS #include "direct.h" #else #include @@ -173,8 +173,8 @@ void CreateDir(std::string const& path) return; } -#ifdef _WIN32 - _mkdir(path.c_str()); +#if FC_PLATFORM == FC_PLATFORM_WINDOWS + mkdir(path.c_str()); #else mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); // 0777 #endif diff --git a/src/tools/mmaps_generator/PathCommon.h b/src/tools/mmaps_generator/PathCommon.h index cf7decd2..c05c2a6b 100644 --- a/src/tools/mmaps_generator/PathCommon.h +++ b/src/tools/mmaps_generator/PathCommon.h @@ -23,14 +23,11 @@ #include #include -#ifndef _WIN32 - #include - #include - #include -#endif - -#ifdef __linux__ - #include +#if FC_PLATFORM == FC_PLATFORM_UNIX +#include +#include +#include +#include #endif namespace VMAP @@ -80,7 +77,7 @@ namespace MMAP inline ListFilesResult getDirContents(std::vector &fileList, std::string dirpath = ".", std::string filter = "*") { - #ifdef WIN32 + #if FC_PLATFORM == FC_PLATFORM_WINDOWS HANDLE hFind; WIN32_FIND_DATA findFileInfo; std::string directory; diff --git a/src/tools/vmap4_extractor/mpqfile.h b/src/tools/vmap4_extractor/mpqfile.h index 71f0d384..5c39c2f7 100644 --- a/src/tools/vmap4_extractor/mpqfile.h +++ b/src/tools/vmap4_extractor/mpqfile.h @@ -14,7 +14,7 @@ #include "StormLib.h" #include "Define.h" -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS #include // mainly only HANDLE definition is required #endif diff --git a/src/tools/vmap4_extractor/vmapexport.cpp b/src/tools/vmap4_extractor/vmapexport.cpp index c83494da..70729965 100644 --- a/src/tools/vmap4_extractor/vmapexport.cpp +++ b/src/tools/vmap4_extractor/vmapexport.cpp @@ -24,9 +24,8 @@ #include "Banner.h" #include -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS #include -#define mkdir _mkdir #else #include #define ERROR_PATH_NOT_FOUND ERROR_FILE_NOT_FOUND @@ -444,7 +443,7 @@ void ParsMapFiles() void getGamePath() { -#ifdef _WIN32 +#if FC_PLATFORM == FC_PLATFORM_WINDOWS strcpy(input_path,"Data\\"); #else strcpy(input_path,"Data/");