libunwind 简介示例与详细示例

1,简介示例

1.1,代码先行

获取并打印函数调用堆栈信息,仅实现与 glibc中backtrace系列相同的功能,这个示例多了获取寄存器的值,结合glibc 的 backtrace 将比较容易理解,

hello_libunwind.c

cpp 复制代码
#include<stdio.h>
#define UNW_LOCAL_ONLY
#include<libunwind.h>


void do_unwind()
{
	unw_cursor_t cursor;
	unw_context_t context;

	unw_getcontext(&context);
	unw_init_local(&cursor, &context);

	while(unw_step(&cursor)>0)
	{
		unw_word_t offset, ip, eax, ebx, ecx, edx;
		char func_sym[64];
		
		
		unw_get_reg(&cursor, UNW_REG_IP, &ip);
		unw_get_reg(&cursor, UNW_X86_64_RAX, &eax);
		unw_get_reg(&cursor, UNW_X86_64_RBX, &ebx);
		unw_get_reg(&cursor, UNW_X86_64_RCX, &ecx);
		unw_get_reg(&cursor, UNW_X86_64_RDX, &edx);



		func_sym[0] = '\0';
		(void) unw_get_proc_name(&cursor, func_sym, sizeof(func_sym), &offset);

		printf("%p : (%s+0x%x) [%p] ", ip, func_sym, offset, ip);
		printf("EAX=0X%08X EBX=0X%08X ECX=0X%08X EDX=0X%08X\n", eax, ebx, ecx, edx);
		printf("");
	}

}

void xxx()
{

}

void aaa()
{
	xxx();
	do_unwind();
}

void bbb()
{
	xxx();
	xxx();
	aaa();
}

void ccc()
{
	xxx();
	xxx();
	xxx();
	bbb();
}

int main()
{
	ccc();
	
	return 0;
}

1.2,编译运行

Makefile

cpp 复制代码
hello_libunwind: 

%: %.c
	gcc $< -o $@  -lunwind 

$ make

运行:

$ ./hello_libunwind

效果:

2, 异常处理时应用 libunwind

相关推荐
SoveTingღ24 分钟前
【问题解析】我的客户端与服务器交互无响应了?
服务器·c++·qt·tcp
温宇飞1 小时前
内存异常
c++
挖矿大亨3 小时前
C++中深拷贝与浅拷贝的原理
开发语言·c++·算法
Bruce_kaizy3 小时前
c++图论——生成树之Kruskal&Prim算法
c++·算法·图论
雾岛听蓝4 小时前
C++:模拟实现string类
开发语言·c++
XFF不秃头4 小时前
力扣刷题笔记-合并区间
c++·笔记·算法·leetcode
编程之路,妙趣横生5 小时前
STL(七) unordered_set 与 unordered_map 基本用法 + 模拟实现
c++
寂柒5 小时前
c++--
c++
wregjru5 小时前
【读书笔记】Effective C++ 条款3:尽可能使用const
开发语言·c++
历程里程碑6 小时前
滑动窗口秒解LeetCode字母异位词
java·c语言·开发语言·数据结构·c++·算法·leetcode