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

相关推荐
潼心1412o1 小时前
C++初阶(长期更新)第5讲:类和对象(中)
开发语言·c++
weixin_307779131 小时前
C++代码实现MATLAB中的normalize函数功能
开发语言·c++·算法·matlab
(Charon)1 小时前
【C++面试】手写String类:同时实现拷贝构造与移动构造
c++·算法
程序员老陆1 小时前
通过std::unique_ptr初始化std::shared_ptr
开发语言·c++
西西弗Sisyphus3 小时前
Qt6 实现 会动的界面像物理世界一样
c++·qt
UIU1144 小时前
头文件可以防什么错?运用头文件做声明
c++·学习·c#
by209994 小时前
list:迭代器与资源管理实现的综合叙述(下)
数据结构·c++·笔记·list
MayZork4 小时前
Qt 开发集成CMake + vcpkg
开发语言·c++·qt
书生执笔画浮沉5 小时前
Linux桌面端应用向鸿蒙PC迁移适配纪实
c++·qt·c·信创·海思·libc·ohos
(Charon)5 小时前
【C++面试】单例模式:懒汉式与饿汉式的实现、区别与线程安全
开发语言·c++·面试