Skip to content

Instantly share code, notes, and snippets.

@vmxdev
Created June 25, 2017 12:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vmxdev/27550410c624e5bdb88ade96cf3ff5cb to your computer and use it in GitHub Desktop.
Save vmxdev/27550410c624e5bdb88ade96cf3ff5cb to your computer and use it in GitHub Desktop.
Trace function calls using -finstrument-functions
#define _GNU_SOURCE
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
/* ========================================================================= */
static int indent_level = 0;
__attribute__ ((no_instrument_function)) static void
indent()
{
int i;
/* green TRACE word */
printf("\x1B[32m" "TRACE:" "\x1B[0m");
for (i=0; i<indent_level; i++) {
putc(' ', stdout);
}
}
__attribute__ ((no_instrument_function)) void
__cyg_profile_func_enter(void *this_fn, void *call_site)
{
char cmd[PATH_MAX];
FILE *p;
(void)call_site;
indent();
sprintf(cmd, "addr2line -pif -e %s %p", program_invocation_name,
this_fn);
p = popen(cmd, "r");
if (p) {
char res[PATH_MAX];
size_t len;
fgets(res, sizeof(res), p);
len = strlen(res);
if (len > 1) {
res[len - 1] = '\0';
}
pclose(p);
printf("function %s {\n", res);
} else {
printf("function UNKNOWN (addr %p) {\n", this_fn);
}
indent_level++;
}
__attribute__ ((no_instrument_function)) void
__cyg_profile_func_exit(void *this_fn, void *call_site)
{
(void)this_fn;
(void)call_site;
indent_level--;
indent();
printf("}\n");
}
/* ========================================================================= */
static void
world()
{
printf("Hello world!\n");
}
static void
hello()
{
world();
}
int
main()
{
hello();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment