diff options
| author | Dan Engelbrecht <[email protected]> | 2024-04-04 14:32:40 +0200 |
|---|---|---|
| committer | GitHub Enterprise <[email protected]> | 2024-04-04 14:32:40 +0200 |
| commit | 12b7bf1c16f671c83840961c37a339141a7ffbb3 (patch) | |
| tree | 3c503e6e1cd4d53b87c1baebcf9286ca8b72db06 /src | |
| parent | hardening parsepackagemessage (#38) (diff) | |
| download | zen-12b7bf1c16f671c83840961c37a339141a7ffbb3.tar.xz zen-12b7bf1c16f671c83840961c37a339141a7ffbb3.zip | |
improved assert (#37)
- Improvement: Add file and line to ASSERT exceptions
- Improvement: Catch call stack when throwing assert exceptions and log/output call stack at important places to provide more context to caller
Diffstat (limited to 'src')
45 files changed, 591 insertions, 167 deletions
diff --git a/src/transports/winsock/winsock.cpp b/src/transports/winsock/winsock.cpp index 7ee2b5ed1..1c3ee909a 100644 --- a/src/transports/winsock/winsock.cpp +++ b/src/transports/winsock/winsock.cpp @@ -317,7 +317,7 @@ WinsockTransportPlugin::Initialize(TransportServer* ServerInterface) { Connection->HandleConnection(); } - catch (std::exception&) + catch (const std::exception&) { // ZEN_WARN("exception caught in connection loop: {}", Ex.what()); } diff --git a/src/zen/cmds/bench_cmd.cpp b/src/zen/cmds/bench_cmd.cpp index 5c955e980..86b82d838 100644 --- a/src/zen/cmds/bench_cmd.cpp +++ b/src/zen/cmds/bench_cmd.cpp @@ -48,11 +48,11 @@ BenchCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv) Ok = true; } - catch (zen::bench::util::elevation_required_exception&) + catch (const zen::bench::util::elevation_required_exception&) { ZEN_CONSOLE("purging standby lists requires elevation. Will try launch as elevated process"); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_CONSOLE("ERROR: {}", Ex.what()); } @@ -83,7 +83,7 @@ BenchCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv) } } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_CONSOLE("ERROR: {}", Ex.what()); } diff --git a/src/zen/cmds/copy_cmd.cpp b/src/zen/cmds/copy_cmd.cpp index 956d9c9d2..f39bfa71c 100644 --- a/src/zen/cmds/copy_cmd.cpp +++ b/src/zen/cmds/copy_cmd.cpp @@ -148,7 +148,7 @@ CopyCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv) throw std::logic_error("CopyFile failed in an unexpected way"); } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ++FailedFileCount; @@ -211,7 +211,7 @@ CopyCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv) throw std::logic_error("CopyFile failed in an unexpected way"); } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_CONSOLE_ERROR("Error: failed to copy '{}' to '{}': '{}'", FromPath, ToPath, Ex.what()); diff --git a/src/zen/cmds/serve_cmd.cpp b/src/zen/cmds/serve_cmd.cpp index c8117774b..ea9102b28 100644 --- a/src/zen/cmds/serve_cmd.cpp +++ b/src/zen/cmds/serve_cmd.cpp @@ -91,7 +91,7 @@ ServeCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv) ServerInstance->SetOwnerPid(zen::GetCurrentProcessId()); ServerInstance->SpawnServerAndWait(ServerPort); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_CONSOLE("failed to spawn server on port {}: '{}'", ServerPort, Ex.what()); diff --git a/src/zen/cmds/up_cmd.cpp b/src/zen/cmds/up_cmd.cpp index c5dd31f5e..14f954064 100644 --- a/src/zen/cmds/up_cmd.cpp +++ b/src/zen/cmds/up_cmd.cpp @@ -176,7 +176,7 @@ DownCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv) return 0; } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_DEBUG("Exception caught when requesting shutdown: {}", Ex.what()); } diff --git a/src/zen/zen.cpp b/src/zen/zen.cpp index 39f3f1f78..4881d44ae 100644 --- a/src/zen/zen.cpp +++ b/src/zen/zen.cpp @@ -72,7 +72,7 @@ ZenCmdBase::ParseOptions(int argc, char** argv) { Result = CmdOptions.parse(argc, argv); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { throw zen::OptionParseException(Ex.what()); } @@ -513,7 +513,7 @@ main(int argc, char** argv) { return CmdInfo.Cmd->Run(GlobalOptions, (int)CommandArgVec.size(), CommandArgVec.data()); } - catch (OptionParseException& Ex) + catch (const OptionParseException& Ex) { std::string help = VerbOptions.help(); @@ -526,7 +526,7 @@ main(int argc, char** argv) printf("Unknown command specified: '%s', exiting\n", SubCommand.c_str()); } - catch (OptionParseException& Ex) + catch (const OptionParseException& Ex) { std::string HelpMessage = Options.help(); @@ -534,13 +534,13 @@ main(int argc, char** argv) return 9; } - catch (std::system_error& Ex) + catch (const std::system_error& Ex) { printf("System Error: %s\n", Ex.what()); return Ex.code() ? Ex.code().value() : 10; } - catch (std::exception& Ex) + catch (const std::exception& Ex) { printf("Error: %s\n", Ex.what()); diff --git a/src/zencore/callstack.cpp b/src/zencore/callstack.cpp new file mode 100644 index 000000000..905ab3d9e --- /dev/null +++ b/src/zencore/callstack.cpp @@ -0,0 +1,221 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include <zencore/callstack.h> +#include <zencore/thread.h> + +#if ZEN_PLATFORM_WINDOWS +# include <zencore/windows.h> +# include <Dbghelp.h> +#endif + +#if ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC +# include <execinfo.h> +#endif + +#if ZEN_WITH_TESTS +# include <zencore/testing.h> +#endif + +#include <fmt/format.h> + +namespace zen { +#if ZEN_PLATFORM_WINDOWS + +class WinSymbolInit +{ +public: + WinSymbolInit() {} + ~WinSymbolInit() + { + m_CallstackLock.WithExclusiveLock([this]() { + if (m_Initialized) + { + SymCleanup(m_CurrentProcess); + } + }); + } + + bool GetSymbol(void* Frame, SYMBOL_INFO* OutSymbolInfo, DWORD64& OutDisplacement) + { + bool Result = false; + m_CallstackLock.WithExclusiveLock([&]() { + if (!m_Initialized) + { + m_CurrentProcess = GetCurrentProcess(); + if (SymInitialize(m_CurrentProcess, NULL, TRUE) == TRUE) + { + m_Initialized = true; + } + } + if (m_Initialized) + { + if (SymFromAddr(m_CurrentProcess, (DWORD64)Frame, &OutDisplacement, OutSymbolInfo) == TRUE) + { + Result = true; + } + } + }); + return Result; + } + +private: + HANDLE m_CurrentProcess = NULL; + BOOL m_Initialized = FALSE; + RwLock m_CallstackLock; +}; + +static WinSymbolInit WinSymbols; + +#endif + +CallstackFrames* +CreateCallstack(uint32_t FrameCount, void** Frames) noexcept +{ + if (FrameCount == 0) + { + return nullptr; + } + CallstackFrames* Callstack = (CallstackFrames*)malloc(sizeof(CallstackFrames) + sizeof(void*) * FrameCount); + if (Callstack != nullptr) + { + Callstack->FrameCount = FrameCount; + if (FrameCount == 0) + { + Callstack->Frames = nullptr; + } + else + { + Callstack->Frames = (void**)&Callstack[1]; + memcpy(Callstack->Frames, Frames, sizeof(void*) * FrameCount); + } + } + return Callstack; +} + +CallstackFrames* +CloneCallstack(const CallstackFrames* Callstack) noexcept +{ + if (Callstack == nullptr) + { + return nullptr; + } + return CreateCallstack(Callstack->FrameCount, Callstack->Frames); +} + +void +FreeCallstack(CallstackFrames* Callstack) noexcept +{ + if (Callstack != nullptr) + { + free(Callstack); + } +} + +uint32_t +GetCallstack(int FramesToSkip, int FramesToCapture, void* OutAddresses[]) +{ +#if ZEN_PLATFORM_WINDOWS + return (uint32_t)CaptureStackBackTrace(FramesToSkip, FramesToCapture, OutAddresses, 0); +#endif +#if ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC + void* Frames[FramesToSkip + FramesToCapture]; + int FrameCount = backtrace(Frames, FramesToSkip + FramesToCapture); + if (FrameCount > FramesToSkip) + { + for (int Index = FramesToSkip; Index < FrameCount; Index++) + { + OutAddresses[Index - FramesToSkip] = Frames[Index]; + } + return (uint32_t)(FrameCount - FramesToSkip); + } + else + { + return 0; + } +#endif +} + +std::vector<std::string> +GetFrameSymbols(uint32_t FrameCount, void** Frames) +{ + std::vector<std::string> FrameSymbols; + if (FrameCount > 0) + { + FrameSymbols.resize(FrameCount); +#if ZEN_PLATFORM_WINDOWS + char SymbolBuffer[sizeof(SYMBOL_INFO) + 1024]; + SYMBOL_INFO* SymbolInfo = (SYMBOL_INFO*)SymbolBuffer; + SymbolInfo->SizeOfStruct = sizeof(SYMBOL_INFO); + SymbolInfo->MaxNameLen = 1023; + DWORD64 Displacement = 0; + for (uint32_t FrameIndex = 0; FrameIndex < FrameCount; FrameIndex++) + { + if (WinSymbols.GetSymbol(Frames[FrameIndex], SymbolInfo, Displacement)) + { + FrameSymbols[FrameIndex] = fmt::format("{}+{:#x} [{:#x}]", SymbolInfo->Name, Displacement, (uintptr_t)Frames[FrameIndex]); + } + } +#endif +#if ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC + char** messages = backtrace_symbols(Frames, (int)FrameCount); + if (messages) + { + for (uint32_t FrameIndex = 0; FrameIndex < FrameCount; FrameIndex++) + { + FrameSymbols[FrameIndex] = messages[FrameIndex]; + } + free(messages); + } +#endif + } + return FrameSymbols; +} + +void +FormatCallstack(const CallstackFrames* Callstack, StringBuilderBase& SB) +{ + bool First = true; + for (const std::string& Symbol : GetFrameSymbols(Callstack)) + { + if (!First) + { + SB.Append("\n"); + } + else + { + First = false; + } + SB.Append(Symbol); + } +} + +std::string +CallstackToString(const CallstackFrames* Callstack) +{ + StringBuilder<2048> SB; + FormatCallstack(Callstack, SB); + return SB.ToString(); +} + +#if ZEN_WITH_TESTS + +TEST_CASE("Callstack.Basic") +{ + void* Addresses[4]; + uint32_t FrameCount = GetCallstack(1, 4, Addresses); + CHECK(FrameCount > 0); + std::vector<std::string> Symbols = GetFrameSymbols(FrameCount, Addresses); + for (const std::string& Symbol : Symbols) + { + CHECK(!Symbol.empty()); + } +} + +void +callstack_forcelink() +{ +} + +#endif + +} // namespace zen diff --git a/src/zencore/filesystem.cpp b/src/zencore/filesystem.cpp index 3e94b550f..ca2b3101f 100644 --- a/src/zencore/filesystem.cpp +++ b/src/zencore/filesystem.cpp @@ -730,7 +730,7 @@ CopyTree(std::filesystem::path FromPath, std::filesystem::path ToPath, const Cop throw std::runtime_error("CopyFile failed in an unexpected way"); } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ++FailedFileCount; diff --git a/src/zencore/include/zencore/callstack.h b/src/zencore/include/zencore/callstack.h new file mode 100644 index 000000000..02ba8b3c3 --- /dev/null +++ b/src/zencore/include/zencore/callstack.h @@ -0,0 +1,37 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include <zencore/zencore.h> + +#include <zencore/string.h> + +#include <string> +#include <vector> + +namespace zen { + +struct CallstackFrames +{ + uint32_t FrameCount; + void** Frames; +}; + +CallstackFrames* CreateCallstack(uint32_t FrameCount, void** Frames) noexcept; +CallstackFrames* CloneCallstack(const CallstackFrames* Callstack) noexcept; +void FreeCallstack(CallstackFrames* Callstack) noexcept; + +uint32_t GetCallstack(int FramesToSkip, int FramesToCapture, void* OutAddresses[]); +std::vector<std::string> GetFrameSymbols(uint32_t FrameCount, void** Frames); +inline std::vector<std::string> +GetFrameSymbols(const CallstackFrames* Callstack) +{ + return GetFrameSymbols(Callstack ? Callstack->FrameCount : 0, Callstack ? Callstack->Frames : nullptr); +} + +void FormatCallstack(const CallstackFrames* Callstack, StringBuilderBase& SB); +std::string CallstackToString(const CallstackFrames* Callstack); + +void callstack_forcelink(); // internal + +} // namespace zen diff --git a/src/zencore/include/zencore/scopeguard.h b/src/zencore/include/zencore/scopeguard.h index d04c8ed9c..3fd0564f6 100644 --- a/src/zencore/include/zencore/scopeguard.h +++ b/src/zencore/include/zencore/scopeguard.h @@ -21,7 +21,11 @@ public: { m_guardFunc(); } - catch (std::exception& Ex) + catch (const AssertException& Ex) + { + ZEN_ERROR("Assert exception in scope guard: {}", Ex.FullDescription()); + } + catch (const std::exception& Ex) { ZEN_ERROR("scope guard threw exception: '{}'", Ex.what()); } diff --git a/src/zencore/include/zencore/zencore.h b/src/zencore/include/zencore/zencore.h index 1a9060e29..cd1a34c7b 100644 --- a/src/zencore/include/zencore/zencore.h +++ b/src/zencore/include/zencore/zencore.h @@ -24,34 +24,63 @@ #endif namespace zen { + +struct CallstackFrames; + class AssertException : public std::logic_error { public: - inline explicit AssertException(const char* Msg) : std::logic_error(Msg) {} + using _Mybase = std::logic_error; + + virtual ~AssertException() noexcept; + + inline AssertException(const char* Msg, struct CallstackFrames* Callstack) noexcept : _Mybase(Msg), _Callstack(Callstack) {} + + AssertException(const AssertException& Rhs) noexcept; + + AssertException(AssertException&& Rhs) noexcept; + + AssertException& operator=(const AssertException& Rhs) noexcept; + + std::string FullDescription() const noexcept; + + struct CallstackFrames* _Callstack = nullptr; }; struct AssertImpl { + ZEN_FORCENOINLINE ZEN_DEBUG_SECTION AssertImpl() : PrevAssertImpl(CurrentAssertImpl) { CurrentAssertImpl = this; } + virtual ZEN_FORCENOINLINE ZEN_DEBUG_SECTION ~AssertImpl() { CurrentAssertImpl = PrevAssertImpl; } + static void ZEN_FORCENOINLINE ZEN_DEBUG_SECTION ExecAssert [[noreturn]] (const char* Filename, int LineNumber, const char* FunctionName, const char* Msg) { - CurrentAssertImpl->OnAssert(Filename, LineNumber, FunctionName, Msg); - throw AssertException{Msg}; + AssertImpl* AssertImpl = CurrentAssertImpl; + while (AssertImpl) + { + AssertImpl->OnAssert(Filename, LineNumber, FunctionName, Msg); + AssertImpl = AssertImpl->PrevAssertImpl; + } + ThrowAssertException(Filename, LineNumber, FunctionName, Msg); } -protected: virtual void ZEN_FORCENOINLINE ZEN_DEBUG_SECTION OnAssert(const char* Filename, int LineNumber, const char* FunctionName, const char* Msg) { - (void(Filename)); - (void(LineNumber)); - (void(FunctionName)); - (void(Msg)); + ZEN_UNUSED(Filename); + ZEN_UNUSED(LineNumber); + ZEN_UNUSED(FunctionName); + ZEN_UNUSED(Msg); } - static AssertImpl DefaultAssertImpl; + +protected: + static void ZEN_FORCENOINLINE ZEN_DEBUG_SECTION ThrowAssertException + [[noreturn]] (const char* Filename, int LineNumber, const char* FunctionName, const char* Msg); static AssertImpl* CurrentAssertImpl; + static AssertImpl DefaultAssertImpl; + AssertImpl* PrevAssertImpl = nullptr; }; } // namespace zen diff --git a/src/zencore/jobqueue.cpp b/src/zencore/jobqueue.cpp index 86c08cda9..d26d0dd1e 100644 --- a/src/zencore/jobqueue.cpp +++ b/src/zencore/jobqueue.cpp @@ -69,7 +69,7 @@ public: Stop(); } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("Failed shutting down jobqueue. Reason: '{}'", Ex.what()); } @@ -106,7 +106,7 @@ public: }); return {.Id = NewJobId}; } - catch (std::exception& Ex) + catch (const std::exception& Ex) { WorkerCounter.CountDown(); QueueLock.WithExclusiveLock([&]() { @@ -359,7 +359,18 @@ public: CompletedJobs.insert_or_assign(CurrentJob->Id.Id, std::move(CurrentJob)); }); } - catch (std::exception& Ex) + catch (const AssertException& Ex) + { + ZEN_DEBUG("Background job {}:'{}' asserted. Reason: {}", CurrentJob->Id.Id, CurrentJob->Name, Ex.FullDescription()); + QueueLock.WithExclusiveLock([&]() { + CurrentJob->State.AbortReason = Ex.FullDescription(); + CurrentJob->EndTick = JobClock::Now(); + CurrentJob->WorkerThreadId = 0; + RunningJobs.erase(CurrentJob->Id.Id); + AbortedJobs.insert_or_assign(CurrentJob->Id.Id, std::move(CurrentJob)); + }); + } + catch (const std::exception& Ex) { ZEN_DEBUG("Background job {}:'{}' aborted. Reason: '{}'", CurrentJob->Id.Id, CurrentJob->Name, Ex.what()); QueueLock.WithExclusiveLock([&]() { diff --git a/src/zencore/workthreadpool.cpp b/src/zencore/workthreadpool.cpp index 16b2310ff..f41c13bf6 100644 --- a/src/zencore/workthreadpool.cpp +++ b/src/zencore/workthreadpool.cpp @@ -186,7 +186,13 @@ WorkerThreadPool::Impl::WorkerThreadFunction(ThreadStartInfo Info) ZEN_TRACE_CPU_FLUSH("AsyncWork"); Work->Execute(); } - catch (std::exception& e) + catch (const AssertException& Ex) + { + Work->m_Exception = std::current_exception(); + + ZEN_WARN("Assert exception in worker thread: {}", Ex.FullDescription()); + } + catch (const std::exception& e) { Work->m_Exception = std::current_exception(); @@ -234,7 +240,13 @@ WorkerThreadPool::ScheduleWork(Ref<IWork> Work) ZEN_TRACE_CPU_FLUSH("SyncWork"); Work->Execute(); } - catch (std::exception& e) + catch (const AssertException& Ex) + { + Work->m_Exception = std::current_exception(); + + ZEN_WARN("Assert exception in worker thread: {}", Ex.FullDescription()); + } + catch (const std::exception& e) { Work->m_Exception = std::current_exception(); diff --git a/src/zencore/xmake.lua b/src/zencore/xmake.lua index e6102679d..5f2d95e16 100644 --- a/src/zencore/xmake.lua +++ b/src/zencore/xmake.lua @@ -53,6 +53,7 @@ target('zencore') if is_plat("windows") then add_syslinks("Advapi32") + add_syslinks("Dbghelp") add_syslinks("Shell32") add_syslinks("User32") add_syslinks("crypt32") diff --git a/src/zencore/zencore.cpp b/src/zencore/zencore.cpp index c97f5e5ca..c4fcc89de 100644 --- a/src/zencore/zencore.cpp +++ b/src/zencore/zencore.cpp @@ -6,12 +6,9 @@ # include <zencore/windows.h> #endif -#if ZEN_PLATFORM_LINUX -# include <pthread.h> -#endif - #include <zencore/assertfmt.h> #include <zencore/blake3.h> +#include <zencore/callstack.h> #include <zencore/compactbinary.h> #include <zencore/compactbinarybuilder.h> #include <zencore/compactbinarypackage.h> @@ -55,10 +52,59 @@ ExecAssertFmt(const char* Filename, int LineNumber, const char* FunctionName, st namespace zen { +AssertException::AssertException(const AssertException& Rhs) noexcept : _Mybase(Rhs), _Callstack(CloneCallstack(Rhs._Callstack)) +{ +} + +AssertException::AssertException(AssertException&& Rhs) noexcept : _Mybase(Rhs), _Callstack(Rhs._Callstack) +{ + Rhs._Callstack = nullptr; +} + +AssertException::~AssertException() noexcept +{ + FreeCallstack(_Callstack); +} + +AssertException& +AssertException::operator=(const AssertException& Rhs) noexcept +{ + _Mybase::operator=(Rhs); + + CallstackFrames* Callstack = CloneCallstack(Rhs._Callstack); + std::swap(_Callstack, Callstack); + FreeCallstack(Callstack); + return *this; +} + +std::string +AssertException::FullDescription() const noexcept +{ + if (_Callstack) + { + return fmt::format("'{}'\n{}", what(), CallstackToString(_Callstack)); + } + return what(); +} + +void +AssertImpl::ThrowAssertException(const char* Filename, int LineNumber, const char* FunctionName, const char* Msg) +{ + ZEN_UNUSED(FunctionName); + fmt::basic_memory_buffer<char, 2048> Message; + auto Appender = fmt::appender(Message); + fmt::format_to(Appender, "{}({}): {}", Filename, LineNumber, Msg); + Message.push_back('\0'); + + void* Frames[8]; + uint32_t FrameCount = GetCallstack(3, 8, Frames); + throw AssertException(Message.data(), CreateCallstack(FrameCount, Frames)); +} + void refcount_forcelink(); +AssertImpl* AssertImpl::CurrentAssertImpl = nullptr; AssertImpl AssertImpl::DefaultAssertImpl; -AssertImpl* AssertImpl::CurrentAssertImpl = &AssertImpl::DefaultAssertImpl; ////////////////////////////////////////////////////////////////////////// @@ -138,6 +184,7 @@ void zencore_forcelinktests() { zen::blake3_forcelink(); + zen::callstack_forcelink(); zen::compositebuffer_forcelink(); zen::compress_forcelink(); zen::crypto_forcelink(); @@ -174,24 +221,24 @@ TEST_SUITE_BEGIN("core.assert"); TEST_CASE("Assert.Default") { - bool A = true; - bool B = false; - CHECK_THROWS_WITH(ZEN_ASSERT(A == B), "A == B"); + bool A = true; + bool B = false; + std::string Expected = fmt::format("{}({}): {}", __FILE__, __LINE__ + 1, "A == B"); + CHECK_THROWS_WITH(ZEN_ASSERT(A == B), Expected.c_str()); } TEST_CASE("Assert.Format") { - bool A = true; - bool B = false; - CHECK_THROWS_WITH(ZEN_ASSERT_FORMAT(A == B, "{} == {}", A, B), "assert(A == B) failed: true == false"); + bool A = true; + bool B = false; + std::string Expected = fmt::format("{}({}): {}", __FILE__, __LINE__ + 1, "assert(A == B) failed: true == false"); + CHECK_THROWS_WITH(ZEN_ASSERT_FORMAT(A == B, "{} == {}", A, B), Expected.c_str()); } TEST_CASE("Assert.Custom") { struct MyAssertImpl : AssertImpl { - ZEN_FORCENOINLINE ZEN_DEBUG_SECTION MyAssertImpl() : PrevAssertImpl(CurrentAssertImpl) { CurrentAssertImpl = this; } - virtual ZEN_FORCENOINLINE ZEN_DEBUG_SECTION ~MyAssertImpl() { CurrentAssertImpl = PrevAssertImpl; } virtual void ZEN_FORCENOINLINE ZEN_DEBUG_SECTION OnAssert(const char* Filename, int LineNumber, const char* FunctionName, @@ -202,7 +249,7 @@ TEST_CASE("Assert.Custom") FuncName = FunctionName; Message = Msg; } - AssertImpl* PrevAssertImpl; + AssertImpl* PrevAssertImpl = nullptr; const char* AssertFileName = nullptr; int Line = -1; @@ -213,13 +260,47 @@ TEST_CASE("Assert.Custom") MyAssertImpl MyAssert; bool A = true; bool B = false; - CHECK_THROWS_WITH(ZEN_ASSERT(A == B), "A == B"); + CHECK_THROWS_WITH(ZEN_ASSERT(A == B), std::string(fmt::format("{}({}): {}", __FILE__, __LINE__, "A == B")).c_str()); CHECK(MyAssert.AssertFileName != nullptr); CHECK(MyAssert.Line != -1); CHECK(MyAssert.FuncName != nullptr); CHECK(strcmp(MyAssert.Message, "A == B") == 0); } +TEST_CASE("Assert.Callstack") +{ + try + { + ZEN_ASSERT(false); + } + catch (const AssertException& Assert) + { + ZEN_INFO("Assert failed: {}", Assert.what()); + CHECK(Assert._Callstack->FrameCount > 0); + CHECK(Assert._Callstack->Frames != nullptr); + ZEN_INFO("Callstack:\n{}", CallstackToString(Assert._Callstack)); + } + + WorkerThreadPool Pool(1); + auto Task = Pool.EnqueueTask(std::packaged_task<int()>{[] { + ZEN_ASSERT(false); + return 1; + }}); + + try + { + (void)Task.get(); + CHECK(false); + } + catch (const AssertException& Assert) + { + ZEN_INFO("Assert in future: {}", Assert.what()); + CHECK(Assert._Callstack->FrameCount > 0); + CHECK(Assert._Callstack->Frames != nullptr); + ZEN_INFO("Callstack:\n{}", CallstackToString(Assert._Callstack)); + } +} + TEST_SUITE_END(); #endif diff --git a/src/zenhttp/auth/authmgr.cpp b/src/zenhttp/auth/authmgr.cpp index 18568a21d..a520e8fd1 100644 --- a/src/zenhttp/auth/authmgr.cpp +++ b/src/zenhttp/auth/authmgr.cpp @@ -295,7 +295,7 @@ private: } } } - catch (std::exception& Err) + catch (const std::exception& Err) { ZEN_ERROR("(de)serialize state FAILED, reason '{}'", Err.what()); @@ -367,7 +367,7 @@ private: ZEN_WARN("save auth state FAILED, reason '{}'", Reason.value()); } } - catch (std::exception& Err) + catch (const std::exception& Err) { ZEN_WARN("serialize state FAILED, reason '{}'", Err.what()); } diff --git a/src/zenhttp/httpclient.cpp b/src/zenhttp/httpclient.cpp index 277b93a0f..262785a0a 100644 --- a/src/zenhttp/httpclient.cpp +++ b/src/zenhttp/httpclient.cpp @@ -379,7 +379,7 @@ public: m_FileHandle = nullptr; } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("Failed deleting temp file {}. Reason '{}'", m_FileHandle, Ex.what()); } diff --git a/src/zenhttp/servers/httpasio.cpp b/src/zenhttp/servers/httpasio.cpp index de71eb0a7..cddbe1ae2 100644 --- a/src/zenhttp/servers/httpasio.cpp +++ b/src/zenhttp/servers/httpasio.cpp @@ -476,7 +476,15 @@ HttpServerConnection::HandleRequest() { Service->HandleRequest(Request); } - catch (std::system_error& SystemError) + catch (const AssertException& AssertEx) + { + // Drop any partially formatted response + Request.m_Response.reset(); + + ZEN_ERROR("Caught assert exception while handling request: {}", AssertEx.FullDescription()); + Request.WriteResponse(HttpResponseCode::InternalServerError, HttpContentType::kText, AssertEx.FullDescription()); + } + catch (const std::system_error& SystemError) { // Drop any partially formatted response Request.m_Response.reset(); @@ -491,14 +499,14 @@ HttpServerConnection::HandleRequest() Request.WriteResponse(HttpResponseCode::InternalServerError, HttpContentType::kText, SystemError.what()); } } - catch (std::bad_alloc& BadAlloc) + catch (const std::bad_alloc& BadAlloc) { // Drop any partially formatted response Request.m_Response.reset(); Request.WriteResponse(HttpResponseCode::InsufficientStorage, HttpContentType::kText, BadAlloc.what()); } - catch (std::exception& ex) + catch (const std::exception& ex) { // Drop any partially formatted response Request.m_Response.reset(); @@ -958,7 +966,11 @@ HttpAsioServerImpl::Start(uint16_t Port, bool ForceLooopback, int ThreadCount) { m_IoService.run(); } - catch (std::exception& e) + catch (const AssertException& AssertEx) + { + ZEN_ERROR("Assert caught in asio event loop: {}", AssertEx.FullDescription()); + } + catch (const std::exception& e) { ZEN_ERROR("Exception caught in asio event loop: '{}'", e.what()); } @@ -1075,7 +1087,7 @@ HttpAsioServer::Close() { m_Impl->Stop(); } - catch (std::exception& ex) + catch (const std::exception& ex) { ZEN_WARN("Caught exception stopping http asio server: {}", ex.what()); } diff --git a/src/zenhttp/servers/httpparser.cpp b/src/zenhttp/servers/httpparser.cpp index 0a1c5686a..b848a5243 100644 --- a/src/zenhttp/servers/httpparser.cpp +++ b/src/zenhttp/servers/httpparser.cpp @@ -372,7 +372,12 @@ HttpRequestParser::OnMessageComplete() ResetState(); return 0; } - catch (std::system_error& SystemError) + catch (const AssertException& AssertEx) + { + ZEN_WARN("Assert caught when processing http request: {}", AssertEx.FullDescription()); + return 1; + } + catch (const std::system_error& SystemError) { if (IsOOM(SystemError.code())) { @@ -389,13 +394,13 @@ HttpRequestParser::OnMessageComplete() ResetState(); return 1; } - catch (std::bad_alloc& BadAlloc) + catch (const std::bad_alloc& BadAlloc) { ZEN_WARN("out of memory when processing http request: '{}'", BadAlloc.what()); ResetState(); return 1; } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("failed processing http request: '{}'", Ex.what()); ResetState(); diff --git a/src/zenhttp/servers/httpplugin.cpp b/src/zenhttp/servers/httpplugin.cpp index 4a2615133..09cd76f3e 100644 --- a/src/zenhttp/servers/httpplugin.cpp +++ b/src/zenhttp/servers/httpplugin.cpp @@ -386,7 +386,7 @@ HttpPluginConnectionHandler::HandleRequest() { Service->HandleRequest(Request); } - catch (std::system_error& SystemError) + catch (const std::system_error& SystemError) { // Drop any partially formatted response Request.m_Response.reset(); @@ -401,14 +401,14 @@ HttpPluginConnectionHandler::HandleRequest() Request.WriteResponse(HttpResponseCode::InternalServerError, HttpContentType::kText, SystemError.what()); } } - catch (std::bad_alloc& BadAlloc) + catch (const std::bad_alloc& BadAlloc) { // Drop any partially formatted response Request.m_Response.reset(); Request.WriteResponse(HttpResponseCode::InsufficientStorage, HttpContentType::kText, BadAlloc.what()); } - catch (std::exception& ex) + catch (const std::exception& ex) { // Drop any partially formatted response Request.m_Response.reset(); @@ -691,13 +691,13 @@ HttpPluginServerImpl::Initialize(int BasePort, std::filesystem::path DataDir) { Plugin->Initialize(this); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("exception caught during plugin initialization: {}", Ex.what()); } } } - catch (std::exception& ex) + catch (const std::exception& ex) { ZEN_WARN("Caught exception starting http plugin server: {}", ex.what()); } @@ -723,7 +723,7 @@ HttpPluginServerImpl::Close() { Plugin->Shutdown(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("exception caught during plugin shutdown: {}", Ex.what()); } @@ -733,7 +733,7 @@ HttpPluginServerImpl::Close() m_Plugins.clear(); } - catch (std::exception& ex) + catch (const std::exception& ex) { ZEN_WARN("Caught exception stopping http plugin server: {}", ex.what()); } diff --git a/src/zenhttp/servers/httpsys.cpp b/src/zenhttp/servers/httpsys.cpp index 4b812a127..2b97e3f25 100644 --- a/src/zenhttp/servers/httpsys.cpp +++ b/src/zenhttp/servers/httpsys.cpp @@ -873,7 +873,12 @@ HttpAsyncWorkRequest::AsyncWorkItem::Execute() new HttpMessageResponseRequest(Tx, 500, "Response generated but no request handler scheduled"sv)); } } - catch (std::exception& Ex) + catch (const AssertException& AssertEx) + { + return (void)Tx.IssueNextRequest( + new HttpMessageResponseRequest(Tx, 500, fmt::format("Assert thrown in async work: '{}", AssertEx.FullDescription()))); + } + catch (const std::exception& Ex) { return (void)Tx.IssueNextRequest( new HttpMessageResponseRequest(Tx, 500, fmt::format("Exception thrown in async work: {}", Ex.what()))); @@ -1485,7 +1490,11 @@ HttpSysTransaction::IssueNextRequest(HttpSysRequestHandler* NewCompletionHandler ZEN_WARN("IssueRequest() failed: {}", ErrorCode.message()); } - catch (std::exception& Ex) + catch (const AssertException& AssertEx) + { + ZEN_ERROR("Assert thrown in IssueNextRequest(): {}", AssertEx.FullDescription()); + } + catch (const std::exception& Ex) { ZEN_ERROR("exception caught in IssueNextRequest(): {}", Ex.what()); } @@ -1995,7 +2004,12 @@ InitialRequestHandler::HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesT // Unable to route return new HttpMessageResponseRequest(Transaction(), 404, "No suitable route found"sv); } - catch (std::system_error& SystemError) + catch (const AssertException& AssertEx) + { + ZEN_ERROR("Caught assert exception while handling request: {}", AssertEx.FullDescription()); + return new HttpMessageResponseRequest(Transaction(), (uint16_t)HttpResponseCode::InternalServerError, AssertEx.FullDescription()); + } + catch (const std::system_error& SystemError) { if (IsOOM(SystemError.code()) || IsOOD(SystemError.code())) { @@ -2005,11 +2019,11 @@ InitialRequestHandler::HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesT ZEN_ERROR("Caught system error exception while handling request: {}", SystemError.what()); return new HttpMessageResponseRequest(Transaction(), (uint16_t)HttpResponseCode::InternalServerError, SystemError.what()); } - catch (std::bad_alloc& BadAlloc) + catch (const std::bad_alloc& BadAlloc) { return new HttpMessageResponseRequest(Transaction(), (uint16_t)HttpResponseCode::InsufficientStorage, BadAlloc.what()); } - catch (std::exception& ex) + catch (const std::exception& ex) { ZEN_ERROR("Caught exception while handling request: '{}'", ex.what()); return new HttpMessageResponseRequest(Transaction(), (uint16_t)HttpResponseCode::InternalServerError, ex.what()); diff --git a/src/zenhttp/transports/asiotransport.cpp b/src/zenhttp/transports/asiotransport.cpp index a9a782821..96a15518c 100644 --- a/src/zenhttp/transports/asiotransport.cpp +++ b/src/zenhttp/transports/asiotransport.cpp @@ -426,7 +426,7 @@ AsioTransportPlugin::Initialize(TransportServer* ServerInterface) { m_IoService.run(); } - catch (std::exception& e) + catch (const std::exception& e) { ZEN_ERROR("exception caught in asio event loop: {}", e.what()); } diff --git a/src/zenhttp/transports/winsocktransport.cpp b/src/zenhttp/transports/winsocktransport.cpp index 7407c55dd..8c82760bb 100644 --- a/src/zenhttp/transports/winsocktransport.cpp +++ b/src/zenhttp/transports/winsocktransport.cpp @@ -309,7 +309,7 @@ SocketTransportPluginImpl::Initialize(TransportServer* ServerInterface) { Connection->HandleConnection(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("exception caught in connection loop: {}", Ex.what()); } diff --git a/src/zenserver/admin/admin.cpp b/src/zenserver/admin/admin.cpp index 8093a0735..75ff03912 100644 --- a/src/zenserver/admin/admin.cpp +++ b/src/zenserver/admin/admin.cpp @@ -603,7 +603,7 @@ HttpAdminService::HttpAdminService(GcScheduler& Scheduler, EmitStats("cas", Stats.CasStats); EmitStats("project", Stats.ProjectStats); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("exception in disk stats gathering for '{}': {}", m_ServerOptions.DataDir, Ex.what()); } @@ -622,7 +622,7 @@ HttpAdminService::HttpAdminService(GcScheduler& Scheduler, Obj.EndArray(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("exception in state gathering for '{}': {}", m_ServerOptions.SystemRootDir, Ex.what()); } diff --git a/src/zenserver/config.cpp b/src/zenserver/config.cpp index 00581d758..aa0eedb0e 100644 --- a/src/zenserver/config.cpp +++ b/src/zenserver/config.cpp @@ -128,7 +128,7 @@ ReadAllCentralManifests(const std::filesystem::path& SystemRoot) ZEN_WARN("failed to load manifest '{}': {}", File, ToString(ValidateError)); } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("failed to load manifest '{}': {}", File, Ex.what()); } @@ -1004,7 +1004,7 @@ ParseCliOptions(int argc, char* argv[], ZenServerOptions& ServerOptions) { Result = options.parse(argc, argv); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { throw zen::OptionParseException(Ex.what()); } @@ -1069,7 +1069,7 @@ ParseCliOptions(int argc, char* argv[], ZenServerOptions& ServerOptions) ValidateOptions(ServerOptions); } - catch (zen::OptionParseException& e) + catch (const zen::OptionParseException& e) { ZEN_CONSOLE_ERROR("Error parsing zenserver arguments: {}\n\n{}", e.what(), options.help()); diff --git a/src/zenserver/config/luaconfig.cpp b/src/zenserver/config/luaconfig.cpp index cdc808cf6..f742fa34a 100644 --- a/src/zenserver/config/luaconfig.cpp +++ b/src/zenserver/config/luaconfig.cpp @@ -280,7 +280,7 @@ Options::Parse(const std::filesystem::path& Path, const cxxopts::ParseResult& Cm config(); } - catch (std::exception& e) + catch (const std::exception& e) { throw std::runtime_error(fmt::format("failed to load config script ('{}'): {}", Path, e.what()).c_str()); } diff --git a/src/zenserver/diag/diagsvcs.cpp b/src/zenserver/diag/diagsvcs.cpp index 1a10782e9..f0aec98ab 100644 --- a/src/zenserver/diag/diagsvcs.cpp +++ b/src/zenserver/diag/diagsvcs.cpp @@ -36,7 +36,7 @@ ReadLogFile(const std::string& Path, StringBuilderBase& Out) return true; } - catch (std::exception&) + catch (const std::exception&) { Out.Reset(); return false; diff --git a/src/zenserver/main.cpp b/src/zenserver/main.cpp index 7a6d2dd22..6b31dc82e 100644 --- a/src/zenserver/main.cpp +++ b/src/zenserver/main.cpp @@ -247,7 +247,12 @@ ZenEntryPoint::Run() Server.Run(); } - catch (std::exception& e) + catch (const AssertException& AssertEx) + { + ZEN_CRITICAL("Caught assert exception in main for process {}: {}", zen::GetCurrentProcessId(), AssertEx.FullDescription()); + RequestApplicationExit(1); + } + catch (const std::exception& e) { ZEN_CRITICAL("Caught exception in main for process {}: {}", zen::GetCurrentProcessId(), e.what()); RequestApplicationExit(1); @@ -407,7 +412,12 @@ main(int argc, char* argv[]) return App.Run(); #endif } - catch (std::exception& Ex) + catch (const AssertException& AssertEx) + { + fprintf(stderr, "ERROR: Caught assert exception in main: '%s'", AssertEx.FullDescription().c_str()); + return 1; + } + catch (const std::exception& Ex) { fprintf(stderr, "ERROR: Caught exception in main: '%s'", Ex.what()); diff --git a/src/zenserver/projectstore/fileremoteprojectstore.cpp b/src/zenserver/projectstore/fileremoteprojectstore.cpp index 4248bbf2a..764bea355 100644 --- a/src/zenserver/projectstore/fileremoteprojectstore.cpp +++ b/src/zenserver/projectstore/fileremoteprojectstore.cpp @@ -79,7 +79,7 @@ public: } Result.RawHash = IoHash::HashBuffer(Payload); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { Result.ErrorCode = gsl::narrow<int32_t>(HttpResponseCode::InternalServerError); Result.Reason = fmt::format("Failed saving oplog container to '{}'. Reason: {}", ContainerPath, Ex.what()); @@ -108,7 +108,7 @@ public: Offset += Segment.GetSize(); } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { Result.ErrorCode = gsl::narrow<int32_t>(HttpResponseCode::InternalServerError); Result.Reason = fmt::format("Failed saving oplog attachment to '{}'. Reason: {}", ChunkPath, Ex.what()); diff --git a/src/zenserver/projectstore/projectstore.cpp b/src/zenserver/projectstore/projectstore.cpp index 0109533f6..84ed6f842 100644 --- a/src/zenserver/projectstore/projectstore.cpp +++ b/src/zenserver/projectstore/projectstore.cpp @@ -1679,7 +1679,7 @@ ProjectStore::Project::WriteAccessTimes() WriteFile(ProjectAccessTimesFilePath, Data.GetBuffer().AsIoBuffer()); } - catch (std::exception& Err) + catch (const std::exception& Err) { ZEN_WARN("writing access times FAILED, reason: '{}'", Err.what()); } @@ -1714,7 +1714,7 @@ ProjectStore::Project::NewOplog(std::string_view OplogId, const std::filesystem: Log->Write(); return Log; } - catch (std::exception&) + catch (const std::exception&) { // In case of failure we need to ensure there's no half constructed entry around // @@ -1760,7 +1760,7 @@ ProjectStore::Project::OpenOplog(std::string_view OplogId) return Log; } - catch (std::exception& ex) + catch (const std::exception& ex) { ZEN_WARN("failed to open oplog '{}' @ '{}': {}", OplogId, OplogBasePath, ex.what()); @@ -2371,7 +2371,7 @@ ProjectStore::OpenProject(std::string_view ProjectId) Prj->Read(); return Prj; } - catch (std::exception& e) + catch (const std::exception& e) { ZEN_WARN("failed to open {} @ {} ({})", ProjectId, BasePath, e.what()); m_Projects.erase(std::string{ProjectId}); @@ -4017,7 +4017,7 @@ ProjectStore::CreateReferenceCheckers(GcCtx& Ctx) } } } - catch (std::exception&) + catch (const std::exception&) { while (!Checkers.empty()) { diff --git a/src/zenserver/projectstore/remoteprojectstore.cpp b/src/zenserver/projectstore/remoteprojectstore.cpp index e11541534..8efb92e6b 100644 --- a/src/zenserver/projectstore/remoteprojectstore.cpp +++ b/src/zenserver/projectstore/remoteprojectstore.cpp @@ -835,7 +835,7 @@ BuildContainer(CidStore& ChunkStore, } } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { RemoteResult.SetError(gsl::narrow<int>(HttpResponseCode::NotFound), fmt::format("Failed to resolve attachment {}", RawHash), @@ -1216,7 +1216,7 @@ BuildContainer(CidStore& ChunkStore, return {}; } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { BlockCreateLatch.CountDown(); while (!BlockCreateLatch.Wait(1000)) @@ -1740,7 +1740,7 @@ SaveOplog(CidStore& ChunkStore, CreatedBlocks.insert({BlockHash, std::move(BlockBuffer)}); ZEN_DEBUG("Saved temp block to '{}', {}", AttachmentTempPath, NiceBytes(BlockBuffer.GetSize())); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { RemoteResult.SetError(gsl::narrow<int32_t>(HttpResponseCode::InternalServerError), Ex.what(), diff --git a/src/zenserver/sentryintegration.cpp b/src/zenserver/sentryintegration.cpp index 11bf78a75..a8d967985 100644 --- a/src/zenserver/sentryintegration.cpp +++ b/src/zenserver/sentryintegration.cpp @@ -31,13 +31,10 @@ namespace sentry { struct SentryAssertImpl : zen::AssertImpl { - ZEN_FORCENOINLINE ZEN_DEBUG_SECTION SentryAssertImpl(); - virtual ZEN_FORCENOINLINE ZEN_DEBUG_SECTION ~SentryAssertImpl(); virtual void ZEN_FORCENOINLINE ZEN_DEBUG_SECTION OnAssert(const char* Filename, int LineNumber, const char* FunctionName, const char* Msg) override; - AssertImpl* PrevAssertImpl; }; class sentry_sink final : public spdlog::sinks::base_sink<spdlog::details::null_mutex> @@ -85,7 +82,7 @@ sentry_sink::sink_it_(const spdlog::details::log_msg& msg) sentry_event_value_add_stacktrace(event, NULL, 0); sentry_capture_event(event); } - catch (std::exception&) + catch (const std::exception&) { // If our logging with Message formatting fails we do a non-allocating version and just post the msg.payload raw char TmpBuffer[256]; @@ -105,16 +102,6 @@ sentry_sink::flush_() { } -SentryAssertImpl::SentryAssertImpl() : PrevAssertImpl(CurrentAssertImpl) -{ - CurrentAssertImpl = this; -} - -SentryAssertImpl::~SentryAssertImpl() -{ - CurrentAssertImpl = PrevAssertImpl; -} - void SentryAssertImpl::OnAssert(const char* Filename, int LineNumber, const char* FunctionName, const char* Msg) { @@ -128,7 +115,7 @@ SentryAssertImpl::OnAssert(const char* Filename, int LineNumber, const char* Fun sentry_event_value_add_stacktrace(event, NULL, 0); sentry_capture_event(event); } - catch (std::exception&) + catch (const std::exception&) { // If our logging with Message formatting fails we do a non-allocating version and just post the Msg raw sentry_value_t event = sentry_value_new_message_event( diff --git a/src/zenserver/upstream/upstreamcache.cpp b/src/zenserver/upstream/upstreamcache.cpp index dac29c273..6d1d026cc 100644 --- a/src/zenserver/upstream/upstreamcache.cpp +++ b/src/zenserver/upstream/upstreamcache.cpp @@ -152,7 +152,7 @@ namespace detail { return m_Status.EndpointStatus(); } - catch (std::exception& Err) + catch (const std::exception& Err) { m_Status.Set(UpstreamEndpointState::kError, Err.what()); @@ -292,7 +292,7 @@ namespace detail { return {.Status = {.Error{.ErrorCode = Result.ErrorCode, .Reason = std::move(Result.Reason)}}}; } } - catch (std::exception& Err) + catch (const std::exception& Err) { m_Status.Set(UpstreamEndpointState::kError, Err.what()); @@ -388,7 +388,7 @@ namespace detail { return {.Status = {.Error{.ErrorCode = Result.ErrorCode, .Reason = std::move(Result.Reason)}}}; } } - catch (std::exception& Err) + catch (const std::exception& Err) { m_Status.Set(UpstreamEndpointState::kError, Err.what()); @@ -615,7 +615,7 @@ namespace detail { }); } } - catch (std::exception& Err) + catch (const std::exception& Err) { m_Status.Set(UpstreamEndpointState::kError, Err.what()); @@ -825,7 +825,7 @@ namespace detail { return m_Status.EndpointStatus(); } - catch (std::exception& Err) + catch (const std::exception& Err) { m_Status.Set(UpstreamEndpointState::kError, Err.what()); @@ -861,7 +861,7 @@ namespace detail { return {.Status = {.Error{.ErrorCode = Result.ErrorCode, .Reason = std::move(Result.Reason)}}}; } } - catch (std::exception& Err) + catch (const std::exception& Err) { m_Status.Set(UpstreamEndpointState::kError, Err.what()); @@ -984,7 +984,7 @@ namespace detail { return {.Status = {.Error{.ErrorCode = Result.ErrorCode, .Reason = std::move(Result.Reason)}}}; } } - catch (std::exception& Err) + catch (const std::exception& Err) { m_Status.Set(UpstreamEndpointState::kError, Err.what()); @@ -1405,7 +1405,7 @@ namespace detail { .ElapsedSeconds = TotalElapsedSeconds, .Success = Result.Success}; } - catch (std::exception& Err) + catch (const std::exception& Err) { m_Status.Set(UpstreamEndpointState::kError, Err.what()); @@ -1980,7 +1980,7 @@ private: { ProcessCacheRecord(std::move(CacheRecord)); } - catch (std::exception& Err) + catch (const std::exception& Err) { ZEN_ERROR("upload cache record '{}/{}/{}' FAILED, reason '{}'", CacheRecord.Namespace, @@ -2052,7 +2052,7 @@ private: } } } - catch (std::exception& Err) + catch (const std::exception& Err) { ZEN_ERROR("check endpoint(s) health FAILED, reason '{}'", Err.what()); } diff --git a/src/zenserver/vfs/vfsimpl.cpp b/src/zenserver/vfs/vfsimpl.cpp index 5ef89ee77..5c9f32c69 100644 --- a/src/zenserver/vfs/vfsimpl.cpp +++ b/src/zenserver/vfs/vfsimpl.cpp @@ -238,7 +238,7 @@ VfsService::Impl::VfsThread() m_VfsThreadRunning.Set(); m_VfsHost->Run(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("exception caught in VFS thread: {}", Ex.what()); diff --git a/src/zenserver/vfs/vfsservice.cpp b/src/zenserver/vfs/vfsservice.cpp index 04ba29ed2..d302a10ec 100644 --- a/src/zenserver/vfs/vfsservice.cpp +++ b/src/zenserver/vfs/vfsservice.cpp @@ -105,7 +105,7 @@ VfsService::VfsService() { m_Impl->Mount(Mountpath); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { return Req.ServerRequest().WriteResponse(HttpResponseCode::BadRequest, HttpContentType::kText, Ex.what()); } @@ -123,7 +123,7 @@ VfsService::VfsService() { m_Impl->Unmount(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { return Req.ServerRequest().WriteResponse(HttpResponseCode::BadRequest, HttpContentType::kText, Ex.what()); } diff --git a/src/zenserver/zenserver.cpp b/src/zenserver/zenserver.cpp index d1faeb8b6..e6e451952 100644 --- a/src/zenserver/zenserver.cpp +++ b/src/zenserver/zenserver.cpp @@ -761,7 +761,7 @@ ZenServer::Cleanup() m_Http = {}; m_JobQueue.reset(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("exception thrown during Cleanup() in {}: '{}'", ZEN_APP_NAME, Ex.what()); } @@ -831,7 +831,7 @@ ZenServer::CheckStateMarker() return; } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("state marker at {} could not be checked, reason: '{}'", StateMarkerPath, Ex.what()); RequestExit(1); diff --git a/src/zenstore/blockstore.cpp b/src/zenstore/blockstore.cpp index dfa852434..a576ff022 100644 --- a/src/zenstore/blockstore.cpp +++ b/src/zenstore/blockstore.cpp @@ -915,7 +915,7 @@ BlockStore::ReclaimSpace(const ReclaimSnapshotState& Snapshot, NewBlockFile = nullptr; } } - catch (std::system_error& SystemError) + catch (const std::system_error& SystemError) { if (IsOOM(SystemError.code())) { @@ -930,11 +930,11 @@ BlockStore::ReclaimSpace(const ReclaimSnapshotState& Snapshot, ZEN_ERROR("reclaiming space for '{}' failed with system error exception: '{}'", m_BlocksBasePath, SystemError.what()); } } - catch (std::bad_alloc& BadAlloc) + catch (const std::bad_alloc& BadAlloc) { ZEN_WARN("reclaiming space for '{}' ran out of memory: '{}'", m_BlocksBasePath, BadAlloc.what()); } - catch (std::exception& ex) + catch (const std::exception& ex) { ZEN_ERROR("reclaiming space for '{}' failed with: '{}'", m_BlocksBasePath, ex.what()); } diff --git a/src/zenstore/cache/cachedisklayer.cpp b/src/zenstore/cache/cachedisklayer.cpp index 3605f5582..f53ab6f8b 100644 --- a/src/zenstore/cache/cachedisklayer.cpp +++ b/src/zenstore/cache/cachedisklayer.cpp @@ -871,7 +871,7 @@ ZenCacheDiskLayer::CacheBucket::WriteIndexSnapshotLocked(const std::function<uin m_LogFlushPosition = LogCount; } } - catch (std::exception& Err) + catch (const std::exception& Err) { ZEN_WARN("snapshot FAILED, reason: '{}'", Err.what()); } @@ -1434,7 +1434,7 @@ ZenCacheDiskLayer::CacheBucket::Flush() SaveSnapshot(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("Failed to flush bucket in '{}'. Reason: '{}'", m_BucketDir, Ex.what()); } @@ -1540,7 +1540,7 @@ ZenCacheDiskLayer::CacheBucket::SaveSnapshot(const std::function<uint64_t()>& Cl std::filesystem::path ManifestPath = GetManifestPath(m_BucketDir, m_BucketName); WriteFile(ManifestPath, Buffer); } - catch (std::exception& Err) + catch (const std::exception& Err) { ZEN_WARN("writing manifest in '{}' FAILED, reason: '{}'", m_BucketDir, Err.what()); } @@ -1985,7 +1985,7 @@ ZenCacheDiskLayer::CacheBucket::CollectGarbage(GcContext& GcCtx) { SaveSnapshot([&]() { return GcCtx.ClaimGCReserve(); }); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("Failed to write index and manifest after GC in '{}'. Reason: '{}'", m_BucketDir, Ex.what()); } @@ -2921,7 +2921,7 @@ ZenCacheDiskLayer::CacheBucket::RemoveExpiredData(GcCtx& Ctx, GcStats& Stats) { SaveSnapshot([]() { return 0; }); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("Failed to write index and manifest after RemoveExpiredData in '{}'. Reason: '{}'", m_BucketDir, Ex.what()); } @@ -3034,7 +3034,7 @@ public: m_IndexLock.reset(); m_CacheBucket.m_IndexLock.WithExclusiveLock([&]() { m_CacheBucket.m_TrackedReferences.reset(); }); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("~DiskBucketReferenceChecker threw exception: '{}'", Ex.what()); } @@ -3367,7 +3367,7 @@ ZenCacheDiskLayer::~ZenCacheDiskLayer() // This can cause a deadlock, if GC is running we would block while holding ZenCacheDiskLayer::m_Lock m_DroppedBuckets.clear(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("~ZenCacheDiskLayer() failed. Reason: '{}'", Ex.what()); } @@ -3491,7 +3491,7 @@ ZenCacheDiskLayer::DiscoverBuckets() { IsOk = DeleteDirectories(BadBucketPath); } - catch (std::exception&) + catch (const std::exception&) { } @@ -3634,14 +3634,14 @@ ZenCacheDiskLayer::Flush() { Bucket->Flush(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("Failed flushing bucket. Reason: '{}'", Ex.what()); } }); } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("Failed to flush buckets at '{}'. Reason: '{}'", m_RootDir, Ex.what()); } @@ -3878,7 +3878,7 @@ ZenCacheDiskLayer::MemCacheTrim() } }); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("Failed scheduling ZenCacheDiskLayer::MemCacheTrim. Reason: '{}'", Ex.what()); m_IsMemCacheTrimming.store(false); diff --git a/src/zenstore/cache/structuredcachestore.cpp b/src/zenstore/cache/structuredcachestore.cpp index daa628f77..c4ee6f4d3 100644 --- a/src/zenstore/cache/structuredcachestore.cpp +++ b/src/zenstore/cache/structuredcachestore.cpp @@ -400,7 +400,7 @@ ZenCacheStore::LogWorker() ObjectSize, ToString(Item.Value.Value.GetContentType())) } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_LOG_INFO(LogCacheActivity, "{} [{}] {}/{}/{} failed: Reason: '{}'", @@ -436,7 +436,7 @@ ZenCacheStore::LogWorker() m_LogEvent.Wait(); m_LogEvent.Reset(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("Log writer failed: '{}'", Ex.what()); } diff --git a/src/zenstore/compactcas.cpp b/src/zenstore/compactcas.cpp index 17cf20e35..84905df15 100644 --- a/src/zenstore/compactcas.cpp +++ b/src/zenstore/compactcas.cpp @@ -338,7 +338,7 @@ CasContainerStrategy::ScrubStorage(ScrubContext& Ctx) m_BlockStore.IterateChunks(ChunkLocations, ValidateSmallChunk, ValidateLargeChunk); } - catch (ScrubDeadlineExpiredException&) + catch (const ScrubDeadlineExpiredException&) { ZEN_INFO("Scrubbing deadline expired, operation incomplete"); } @@ -934,7 +934,7 @@ CasContainerStrategy::MakeIndexSnapshot() EntryCount = Entries.size(); m_LogFlushPosition = IndexLogPosition; } - catch (std::exception& Err) + catch (const std::exception& Err) { ZEN_WARN("snapshot FAILED, reason: '{}'", Err.what()); diff --git a/src/zenstore/filecas.cpp b/src/zenstore/filecas.cpp index 6b4185ff4..0f3e2ab5a 100644 --- a/src/zenstore/filecas.cpp +++ b/src/zenstore/filecas.cpp @@ -1210,7 +1210,7 @@ FileCasStrategy::MakeIndexSnapshot() EntryCount = Entries.size(); m_LogFlushPosition = IndexLogPosition; } - catch (std::exception& Err) + catch (const std::exception& Err) { ZEN_WARN("snapshot FAILED, reason: '{}'", Err.what()); diff --git a/src/zenstore/gc.cpp b/src/zenstore/gc.cpp index 1a34019fb..d51144a5a 100644 --- a/src/zenstore/gc.cpp +++ b/src/zenstore/gc.cpp @@ -663,7 +663,7 @@ GcManager::CollectGarbage(const GcSettings& Settings) StoreCompactors.insert_or_assign(std::move(StoreCompactor), &Stats->second.CompactStoreStats); } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("GCV2: Failed removing expired data for {}. Reason: '{}'", Owner->GetGcName(Ctx), Ex.what()); } @@ -733,7 +733,7 @@ GcManager::CollectGarbage(const GcSettings& Settings) ReferencePruners.insert_or_assign(Index, std::move(ReferencePruner)); } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("GCV2: Failed creating reference pruners for {}. Reason: '{}'", ReferenceStore->GetGcName(Ctx), @@ -806,7 +806,7 @@ GcManager::CollectGarbage(const GcSettings& Settings) } } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("GCV2: Failed creating reference checkers for {}. Reason: '{}'", Referencer->GetGcName(Ctx), @@ -863,7 +863,7 @@ GcManager::CollectGarbage(const GcSettings& Settings) SCOPED_TIMER(Stats->second.PreCacheStateMS = std::chrono::milliseconds(Timer.GetElapsedTimeMs());); Checker->PreCache(Ctx); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("GCV2: Failed precaching for {}. Reason: '{}'", Checker->GetGcName(Ctx), Ex.what()); } @@ -919,7 +919,7 @@ GcManager::CollectGarbage(const GcSettings& Settings) SCOPED_TIMER(Stats->second.LockStateMS = std::chrono::milliseconds(Timer.GetElapsedTimeMs());); Checker->LockState(Ctx); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("GCV2: Failed locking state for {}. Reason: '{}'", Checker->GetGcName(Ctx), Ex.what()); } @@ -997,7 +997,7 @@ GcManager::CollectGarbage(const GcSettings& Settings) StoreCompactors.insert_or_assign(std::move(StoreCompactor), &Stats->CompactStoreStats); } } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("GCV2: Failed locking state for {}. Reason: '{}'", Pruner->GetGcName(Ctx), Ex.what()); } @@ -1563,7 +1563,7 @@ GcScheduler::AppendGCLog(GcClock::TimePoint StartTime, const GcSettings& Setting GcLogFile.Write(EntryBuffer, AppendPos); } } - catch (std::system_error& SystemError) + catch (const std::system_error& SystemError) { if (IsOOM(SystemError.code())) { @@ -1578,11 +1578,11 @@ GcScheduler::AppendGCLog(GcClock::TimePoint StartTime, const GcSettings& Setting ZEN_ERROR("writing gc result failed with system error exception: '{}'", SystemError.what()); } } - catch (std::bad_alloc& BadAlloc) + catch (const std::bad_alloc& BadAlloc) { ZEN_WARN("writing gc result ran out of memory: '{}'", BadAlloc.what()); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("writing gc result failed with: '{}'", Ex.what()); } @@ -1970,7 +1970,7 @@ GcScheduler::SchedulerThread() WaitTime = std::chrono::seconds(0); } - catch (std::system_error& SystemError) + catch (const std::system_error& SystemError) { if (IsOOM(SystemError.code())) { @@ -1988,14 +1988,14 @@ GcScheduler::SchedulerThread() m_LastLightweightGcTime = m_LastGcTime; WaitTime = m_Config.MonitorInterval; } - catch (std::bad_alloc& BadAlloc) + catch (const std::bad_alloc& BadAlloc) { ZEN_WARN("scheduling garbage collection ran out of memory: '{}'", BadAlloc.what()); m_LastGcTime = GcClock::Now(); m_LastLightweightGcTime = m_LastGcTime; WaitTime = m_Config.MonitorInterval; } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("scheduling garbage collection failed with: '{}'", Ex.what()); m_LastGcTime = GcClock::Now(); @@ -2028,7 +2028,7 @@ GcScheduler::ScrubStorage(bool DoDelete, bool SkipCid, std::chrono::seconds Time Ctx.SetShouldDelete(DoDelete); m_GcManager.ScrubStorage(Ctx); } - catch (ScrubDeadlineExpiredException&) + catch (const ScrubDeadlineExpiredException&) { ZEN_INFO("scrubbing deadline expired (top level), operation incomplete!"); } @@ -2189,7 +2189,7 @@ GcScheduler::CollectGarbage(const GcClock::TimePoint& CacheExpireTime, SchedulerState << "LastGcExpireTime"sv << static_cast<int64_t>(m_LastGcExpireTime.time_since_epoch().count()); SaveCompactBinaryObject(Path, SchedulerState.Save()); } - catch (std::system_error& SystemError) + catch (const std::system_error& SystemError) { if (IsOOM(SystemError.code())) { @@ -2204,11 +2204,11 @@ GcScheduler::CollectGarbage(const GcClock::TimePoint& CacheExpireTime, ZEN_ERROR("writing gc scheduler state failed with system error exception: '{}'", SystemError.what()); } } - catch (std::bad_alloc& BadAlloc) + catch (const std::bad_alloc& BadAlloc) { ZEN_WARN("writing gc scheduler state ran out of memory: '{}'", BadAlloc.what()); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("writing gc scheduler state failed with: '{}'", Ex.what()); } diff --git a/src/zenutil/cache/rpcrecording.cpp b/src/zenutil/cache/rpcrecording.cpp index 759af792d..9bef4d1a4 100644 --- a/src/zenutil/cache/rpcrecording.cpp +++ b/src/zenutil/cache/rpcrecording.cpp @@ -73,7 +73,7 @@ struct RecordedRequestsWriter WriteFile(m_BasePath / "rpc_recording_metadata.zcb", Metadata.GetBuffer().AsIoBuffer()); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("caught exception while generating metadata for RPC recording: {}", Ex.what()); } @@ -455,7 +455,7 @@ RecordedRequestsSegmentWriter::EndWrite() WriteFile(m_BasePath / "rpc_segment_info.zcb", Metadata.GetBuffer().AsIoBuffer()); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("caught exception while writing segment metadata for RPC recording: {}", Ex.what()); } @@ -562,7 +562,7 @@ RecordedRequestsSegmentWriter::WriteRequest(const RecordedRequestInfo& RequestIn m_RequestsByteCount.fetch_add(RequestBuffer.GetSize()); } } - catch (std::exception&) + catch (const std::exception&) { RwLock::ExclusiveLockScope _(m_Lock); m_Entries[RequestIndex].Length = 0; @@ -738,7 +738,7 @@ RecordedRequestsWriter::WriterThreadMain() RecordedRequestsSegmentWriter& Writer = EnsureCurrentSegment(); Writer.WriteRequest(Request.RequestInfo, Request.RequestBuffer); } - catch (std::exception&) + catch (const std::exception&) { // TODO: what's the right behaviour here? The most likely cause would // be some I/O error and we probably ought to just shut down recording @@ -867,7 +867,7 @@ RecordedRequestsWriter::WriteRecordingMetadata() WriteFile(m_BasePath / "rpc_recording_info.zcb", Metadata.GetBuffer().AsIoBuffer()); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("caught exception while writing metadata for RPC recording: {}", Ex.what()); } @@ -913,7 +913,7 @@ RecordedRequestsReader::BeginRead(const std::filesystem::path& BasePath, bool In return TotalRequestCount; } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_WARN("could not read metadata file: {}", Ex.what()); } @@ -950,7 +950,7 @@ RecordedRequestsReader::BeginRead(const std::filesystem::path& BasePath, bool In } } } - catch (std::exception&) + catch (const std::exception&) { } diff --git a/src/zenutil/include/zenutil/logging/rotatingfilesink.h b/src/zenutil/include/zenutil/logging/rotatingfilesink.h index e4a99fc30..ca4649ba8 100644 --- a/src/zenutil/include/zenutil/logging/rotatingfilesink.h +++ b/src/zenutil/include/zenutil/logging/rotatingfilesink.h @@ -60,7 +60,7 @@ public: RwLock::ExclusiveLockScope RotateLock(m_Lock); m_CurrentFile.Close(); } - catch (std::exception&) + catch (const std::exception&) { } } @@ -101,7 +101,7 @@ public: } } } - catch (std::exception&) + catch (const std::exception&) { // Silently eat errors } @@ -116,7 +116,7 @@ public: m_CurrentFile.Flush(); } } - catch (std::exception&) + catch (const std::exception&) { // Silently eat errors } @@ -129,7 +129,7 @@ public: RwLock::ExclusiveLockScope _(m_Lock); m_Formatter = spdlog::details::make_unique<spdlog::pattern_formatter>(pattern); } - catch (std::exception&) + catch (const std::exception&) { // Silently eat errors } @@ -141,7 +141,7 @@ public: RwLock::ExclusiveLockScope _(m_Lock); m_Formatter = std::move(sink_formatter); } - catch (std::exception&) + catch (const std::exception&) { // Silently eat errors } diff --git a/src/zenutil/openprocesscache.cpp b/src/zenutil/openprocesscache.cpp index 39e4aea90..fb654bde2 100644 --- a/src/zenutil/openprocesscache.cpp +++ b/src/zenutil/openprocesscache.cpp @@ -42,7 +42,7 @@ OpenProcessCache::~OpenProcessCache() } m_Sessions.clear(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("OpenProcessCache destructor failed with reason: `{}`", Ex.what()); } @@ -175,7 +175,7 @@ OpenProcessCache::GcWorker() { GCHandles(); } - catch (std::exception& Ex) + catch (const std::exception& Ex) { ZEN_ERROR("gc of open process cache failed with reason: `{}`", Ex.what()); } |