Sane C++ Libraries
C++ Platform Abstraction Libraries
Assert.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Foundation/Compiler.h" // SC_COMPILER_DEBUG_BREAK
5#include "../Foundation/LibC.h" // exit
6#include "../Foundation/Platform.h" // SC_CONFIGURATION_DEBUG
7
8namespace SC
9{
10struct SC_COMPILER_EXPORT Assert;
11}
14
17{
18 [[noreturn]] SC_COMPILER_FORCE_INLINE static void unreachable()
19 {
20#if SC_COMPILER_MSVC
21 __assume(false);
22#else
23 __builtin_unreachable();
24#endif
25 }
28 [[noreturn]] static void exit(int code);
29
35 static void print(const char* expression, const char* filename, const char* functionName, int lineNumber);
36
39 static void printAscii(const char* str);
40
43 [[nodiscard]] static bool printBacktrace();
44
48 [[nodiscard]] static bool printBacktrace(void** backtraceBuffer, size_t backtraceBufferSizeInBytes);
49
56 [[nodiscard]] static size_t captureBacktrace(size_t framesToSkip, void** backtraceBuffer,
57 size_t backtraceBufferSizeInBytes, uint32_t* hash);
58};
60
63
66#define SC_ASSERT_RELEASE(e) \
67 if (!(e)) \
68 SC_LANGUAGE_UNLIKELY \
69 { \
70 SC::Assert::print(#e, __FILE__, __func__, __LINE__); \
71 (void)SC::Assert::printBacktrace(); \
72 SC_COMPILER_DEBUG_BREAK; \
73 SC::Assert::exit(-1); \
74 } \
75 (void)0
76
79#if SC_CONFIGURATION_DEBUG
80#define SC_ASSERT_DEBUG(e) SC_ASSERT_RELEASE(e)
81#else
82#define SC_ASSERT_DEBUG(e) (void)0
83#endif
#define SC_COMPILER_EXPORT
Macro for symbol visibility in non-MSVC compilers.
Definition: Compiler.h:78
#define SC_COMPILER_FORCE_INLINE
Macro for forcing inline functions.
Definition: Compiler.h:46
unsigned int uint32_t
Platform independent (4) bytes unsigned int.
Definition: PrimitiveTypes.h:38
Functions and macros to assert, exit() or abort() and capture backtraces.
Definition: Assert.h:17
static void exit(int code)
Exits current process.
static bool printBacktrace()
Prints backtrace (call stack) of the caller to standard output.
static size_t captureBacktrace(size_t framesToSkip, void **backtraceBuffer, size_t backtraceBufferSizeInBytes, uint32_t *hash)
Captures backtrace of calling stack.
static bool printBacktrace(void **backtraceBuffer, size_t backtraceBufferSizeInBytes)
Prints backtrace (call stack) previously captured with captureBacktrace() of the caller to standard o...
static void printAscii(const char *str)
Prints an ASCII string to standard output.
static void print(const char *expression, const char *filename, const char *functionName, int lineNumber)
Prints an assertion to standard output.