Skip to content

Commit 3ae2151

Browse files
committed
MB-68141: Add cb::backtrace::current
Add a method which returns the current stacktrace as a string (to simplify the use in various cases) Change-Id: I47f9528328804a8f4ff888b6ccbf6ef6e5be6120 Reviewed-on: https://review.couchbase.org/c/platform/+/232397 Reviewed-by: Vesko Karaganev <vesko.karaganev@couchbase.com> Tested-by: Build Bot <build@couchbase.com>
1 parent 66ddbc6 commit 3ae2151

3 files changed

Lines changed: 43 additions & 0 deletions

File tree

include/platform/backtrace.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include <platform/exceptions.h>
1313
#include <cstdio>
1414
#include <functional>
15+
#include <string>
1516

1617
using write_cb_t = void (*)(void*, const char*);
1718

@@ -48,4 +49,11 @@ namespace cb::backtrace {
4849
* handler).
4950
*/
5051
void initialize();
52+
53+
/**
54+
* Get the current backtrace as a string.
55+
*
56+
* @return a string containing the backtrace
57+
*/
58+
[[nodiscard]] std::string current();
5159
}

src/backtrace.cc

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@
2121
#include <execinfo.h> // for backtrace()
2222
#endif
2323

24+
#if __cpp_lib_stacktrace
25+
#include <stacktrace>
26+
#endif
27+
2428
// Maximum number of frames that will be printed.
2529
#define MAX_FRAMES 50
2630

@@ -200,3 +204,24 @@ void cb::backtrace::initialize() {
200204
}
201205
#endif
202206
}
207+
208+
namespace cb::backtrace {
209+
210+
#if __cpp_lib_stacktrace
211+
[[nodiscard]] std::string current() {
212+
return std::to_string(std::stacktrace::current());
213+
}
214+
#else
215+
static void callback(void* ctx, const char* frame) {
216+
auto* result = reinterpret_cast<std::string*>(ctx);
217+
result->append(frame);
218+
result->append("\n");
219+
}
220+
221+
[[nodiscard]] std::string current() {
222+
std::string result;
223+
print_backtrace(callback, &result);
224+
return result;
225+
}
226+
#endif
227+
} // namespace cb::backtrace

tests/unit_tests/backtrace_test.cc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,13 @@ TEST(BackTraceTest, PrintBacktraceToBufferMB19580) {
104104
EXPECT_TRUE(ArrayFilledWith(char(0xee), redzone_1, redzone_sz));
105105
EXPECT_TRUE(ArrayFilledWith(char(0xee), redzone_2, redzone_sz));
106106
}
107+
108+
TEST(BackTraceTest, Current) {
109+
auto backtrace = cb::backtrace::current();
110+
#if defined(WIN32) || defined(__APPLE__)
111+
// Arg.. our cv don't give us full symbols on g++ builds...
112+
EXPECT_TRUE(backtrace.contains("BackTraceTest")) << backtrace;
113+
#else
114+
EXPECT_TRUE(backtrace.contains("platform_unit_test")) << backtrace;
115+
#endif
116+
}

0 commit comments

Comments
 (0)