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

相关推荐
WL学习笔记6 小时前
C & C++ 内存管理
c++·c++内存管理
宛 禾8 小时前
Qt 控件入门:QLabel 从拖拽到对象树,一篇讲透
c++·qt·学习
hetao17338378 小时前
联盟场-提高组-R7 & ZYZSC-S-Round 11
c++·算法
程序喵大人8 小时前
【C++入门】编译链接模型 - 07 链接器怎样把符号对上号
开发语言·c++·编译器·编译链接·链接器
局部有解9 小时前
Hot100 - 三数之和
数据结构·c++·算法
longlongzihan9 小时前
C++ 常用数据结构速查:vector、stack、queue、list、树、图、哈希表等声明与核心操作
数据结构·c++·list
别动我齐刘海9 小时前
实时控制学习2
linux·c++·人工智能·学习·算法
hetao173383711 小时前
校内场-提高组 ZYZSC-S-Round 2
c++·算法
hetao173383711 小时前
2026-10-14 hetao1733837 的刷题记录
c++·算法
浅念-12 小时前
动态规划:线性DP——多状态DP与子数组专题笔记
c++·笔记·算法·leetcode·职场和发展·动态规划·力扣