Skip to content

Instantly share code, notes, and snippets.

@andrewrk
Created April 11, 2019 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewrk/3368c902612aa4f4b744d386b8e9ca66 to your computer and use it in GitHub Desktop.
Save andrewrk/3368c902612aa4f4b744d386b8e9ca66 to your computer and use it in GitHub Desktop.
demo of using Zig's standard library from C code
const std = @import("std");
const builtin = @import("builtin");
export fn captureStackTrace(addresses: [*]usize, len: usize, first_addr: usize) void {
var trace = builtin.StackTrace{
.instruction_addresses = addresses[0..len],
.index = 0,
};
std.debug.captureStackTrace(if (first_addr == 0) null else first_addr, &trace);
}
export fn dumpStackTrace(addresses: [*]usize, len: usize) void {
var index: usize = 0;
while (index < len and addresses[index] != 0) {
index += 1;
}
var trace = builtin.StackTrace{
.instruction_addresses = addresses[0..len],
.index = index,
};
std.debug.dumpStackTrace(trace);
}
$ zig build-lib debug.zig --library c
$ zig build-exe --c-source test.c --object libdebug.a --library c
$ ./test
/home/andy/tmp/abc/debug.zig:9:32: 0x203329 in ??? (debug)
std.debug.captureStackTrace(if (first_addr == 0) null else first_addr, &trace);
^
/home/andy/tmp/abc/test.c:7:5: 0x203099 in ??? (test.c)
captureStackTrace(&addresses[0], STACK_N, 0);
^
/home/andy/tmp/abc/test.c:14:5: 0x203050 in ??? (test.c)
foo();
^
???:?:?: 0x7fcbf9879b5e in ??? (???)
#include "debug.h"
#define STACK_N 4
uintptr_t addresses[STACK_N];
static void foo(void) {
captureStackTrace(&addresses[0], STACK_N, 0);
}
static void bar(void) {}
int main(int argc, char **argv) {
bar();
foo();
dumpStackTrace(addresses, STACK_N);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment