Created
June 25, 2017 12:23
-
-
Save vmxdev/27550410c624e5bdb88ade96cf3ff5cb to your computer and use it in GitHub Desktop.
Trace function calls using -finstrument-functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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