Skip to content

Instantly share code, notes, and snippets.

@whexy
Last active July 24, 2024 23:29
Show Gist options
  • Select an option

  • Save whexy/257ec2e9e90dcfdfebdfee11a5c8731d to your computer and use it in GitHub Desktop.

Select an option

Save whexy/257ec2e9e90dcfdfebdfee11a5c8731d to your computer and use it in GitHub Desktop.
Generate Run-time Call Graph with LLVM SanCov
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sanitizer/coverage_interface.h>
static FILE* fp;
void __attribute__((constructor)) trace_begin(void)
{
fp = fopen("/tmp/callgraph.log", "w");
if (!fp) {
perror("fopen");
exit(EXIT_FAILURE);
}
}
void __attribute__((destructor)) trace_end(void)
{
if (fp) {
fclose(fp);
}
}
void __sanitizer_cov_trace_pc_guard_init(uint32_t* start, uint32_t* stop) {}
void __sanitizer_cov_trace_pc_guard(uint32_t* guard)
{
void* PC = __builtin_return_address(0);
char Callee[1024];
__sanitizer_symbolize_pc(PC, "%f", Callee, sizeof(Callee));
char Caller[1024];
PC = __builtin_return_address(1);
__sanitizer_symbolize_pc(PC, "%f", Caller, sizeof(Caller));
fprintf(fp, "%s -> %s\n", Caller, Callee);
}
@whexy
Copy link
Author

whexy commented Jul 24, 2024

Compile the runtime:

clang -c callgraph.c -o callgraph.o

Compile the target (example.c) with necessary LLVM instrumentations:

clang -g -fsanitize=address -fsanitize-coverage=func,trace-pc-guard -c example.c -o example.o

Link the target with the runtime, enable at least one sanitizer for symbolization:

clang -g -fsanitize=address callgraph.o example.o -o example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment