Skip to content

Commit

Permalink
btrace: add win32 support (#767)
Browse files Browse the repository at this point in the history
  • Loading branch information
sreimers authored Apr 27, 2023
1 parent 024233b commit 36e19ed
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 2 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,7 @@ if(WIN32)
iphlpapi
wsock32
ws2_32
dbghelp
)
else()
list(APPEND LINKLIBS -lm)
Expand Down
12 changes: 12 additions & 0 deletions include/re_btrace.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@ static inline int btrace(struct btrace *bt)

return 0;
}
#elif defined(WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
static inline int btrace(struct btrace *bt)
{
if (!bt)
return EINVAL;

bt->len = CaptureStackBackTrace(0, BTRACE_SZ, bt->stack, NULL);

return 0;
}
#else
static inline int btrace(struct btrace *bt)
{
Expand Down
46 changes: 44 additions & 2 deletions src/btrace/btrace.c
Original file line number Diff line number Diff line change
@@ -1,21 +1,63 @@
/**
* @file btrace.c Backtrace API (Linux/Unix only)
* @file btrace.c Backtrace API
*
* Copyright (C) 2023 Sebastian Reimers
*/

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <dbghelp.h>
#endif
#include <stdlib.h>
#include <re_types.h>
#include <re_fmt.h>
#include <re_mem.h>
#include <re_btrace.h>

enum print_type { BTRACE_CSV, BTRACE_NEWLINE, BTRACE_JSON };

static int print_debug(struct re_printf *pf, struct btrace *bt,
enum print_type type)
{
#if !defined(HAVE_EXECINFO) || defined(RELEASE)
#if (!defined(HAVE_EXECINFO) && !defined(WIN32)) || defined(RELEASE)
(void)pf;
(void)bt;
(void)type;

return 0;
#elif defined(WIN32)
SYMBOL_INFO *symbol;
DWORD displacement = 0;
IMAGEHLP_LINE line;
HANDLE hProcess = GetCurrentProcess();
(void)type;

/* Initialize the symbol buffer. */
symbol = mem_zalloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), NULL);
if (!symbol)
return ENOMEM;

SymInitialize(hProcess, NULL, TRUE);

symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);

/* Initialize the line buffer. */
ZeroMemory(&line, sizeof(line));
line.SizeOfStruct = sizeof(line);

for (size_t i = 0; i < bt->len; i++) {
SymFromAddr(hProcess, (DWORD64)(bt->stack[i]), NULL, symbol);
SymGetLineFromAddr(hProcess, (DWORD64)(bt->stack[i]),
&displacement, &line);
re_hprintf(pf, "%zu: %s (%s:%lu)\n", i, symbol->Name,
line.FileName, line.LineNumber);
}

mem_deref(symbol);
SymCleanup(hProcess);

return 0;
#else
char **symbols;
Expand Down

0 comments on commit 36e19ed

Please sign in to comment.