唉,当初怎么就选择用libdwarf做了 艹。做完发现它远没BFD好用。。。
只处理了标准C 在X86下有可能碰到的变量和其作用范围(就是函数和局部块的范围) 其他的 用不到 不关心
好多地方需要dwarf_dealloc的我都偷懒没管,这只是个例子 例子而已........
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "dwarf.h"
#include "libdwarf.h"
static const char *const dwarf_regnames_i386[] =
{
"eax", "ecx", "edx", "ebx",
"esp", "ebp", "esi", "edi",
"eip", "eflags", NULL,
"st0", "st1", "st2", "st3",
"st4", "st5", "st6", "st7",
NULL, NULL,
"xmm0", "xmm1", "xmm2", "xmm3",
"xmm4", "xmm5", "xmm6", "xmm7",
"mm0", "mm1", "mm2", "mm3",
"mm4", "mm5", "mm6", "mm7",
"fcw", "fsw", "mxcsr",
"es", "cs", "ss", "ds", "fs", "gs", NULL, NULL,
"tr", "ldtr"
};//从GDB源代码里copy过来的。。。
static void get_addr(Dwarf_Attribute attr, Dwarf_Addr *val) {
Dwarf_Error error = 0;
int res;
Dwarf_Addr uval = 0;
res = dwarf_formaddr(attr, &uval, &error);
if (res == DW_DLV_OK) {
*val = uval;
return;
}
return;
}
static void print_subprog(Dwarf_Debug dbg, Dwarf_Die die, int level) {
int res;
Dwarf_Error error = 0;
Dwarf_Addr lowpc = 0;
Dwarf_Addr highpc = 0;
Dwarf_Attribute t_attr;
res = dwarf_attr(die, DW_AT_inline, &t_attr, &error);
if (res == DW_DLV_OK) { // inline 函数 没 范围
printf("< %2d >", level);
printf("inline sub !\n");
return;
}
res = dwarf_attr(die, DW_AT_low_pc, &t_attr, &error);
if (res == DW_DLV_OK) // 获取DW_AT_low_pc
get_addr(t_attr, &lowpc);
res = dwarf_attr(die, DW_AT_high_pc, &t_attr, &error);
if (res == DW_DLV_OK) // 获取DW_AT_high_pc
get_addr(t_attr, &highpc);
if (lowpc) {
printf("< %2d >", level);
printf("low_pc : 0x%" DW_PR_DUx "\n", (Dwarf_Unsigned) lowpc);
}
if (highpc) {
printf("< %2d >", level);
printf("high_pc: 0x%" DW_PR_DUx "\n", (Dwarf_Unsigned) highpc);
}
}
static void get_location(Dwarf_Debug dbg, Dwarf_Attribute attr, int level) {
Dwarf_Error error = 0;
int res;
Dwa