欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

追踪C函数执行路径

程序员文章站 2022-04-21 17:50:58
...

利用gcc特性,追踪函数执行路径

#include <stdio.h>
#include <time.h>
 
static FILE *fp_trace;
 
void
__attribute__((__no_instrument_function__))
__attribute__ ((constructor))
trace_begin (void)
{
 fp_trace = fopen("tracefunc.out", "w");
}
 
void
__attribute__((__no_instrument_function__))
__attribute__ ((destructor))
trace_end (void)
{
 if(fp_trace != NULL) {
 fclose(fp_trace);
 }
}
 
void __attribute__((__no_instrument_function__))
__cyg_profile_func_enter (void *func,  void *caller)
{
 if(fp_trace != NULL) {
 fprintf(fp_trace, "e %p %p %lu\n", func, caller, time(NULL) );
 }
}
 
void __attribute__((__no_instrument_function__))
__cyg_profile_func_exit (void *func, void *caller)
{
 if(fp_trace != NULL) {
 fprintf(fp_trace, "x %p %p %lu\n", func, caller, time(NULL));
 }
}

输出的文件解析成行数执行路径:

#!/bin/bash
if test ! -f "$1"
then
 echo "Error: executable $1 does not exist."
 exit 1
fi
if test ! -f "$2"
then
 echo "Error: trace log $2 does not exist."
 exit 1
fi
EXECUTABLE="$1"
TRACELOG="$2"
ident=0
while read LINETYPE FADDR CADDR CTIME; do
# CDATE="$(date -Iseconds -d @${CTIME})"
 if test "${LINETYPE}" = "e"
 then
     FNAME="$(addr2line -f -e ${EXECUTABLE} ${FADDR}|head -1)"
     CLINE="$(addr2line -s -e ${EXECUTABLE} ${CADDR})"
     for (( c=1; c<=ident; c++)) ; do echo -n "+" ; done 
     printf "${FNAME}"
     echo
     ident=$((ident+2))
 fi
 if test "${LINETYPE}" = "x"
 then
     ident=$((ident-2))
 fi
done < "${TRACELOG}"

GCC的编译参数需要设置如下:

-g -O0 -finstrument-functions