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

相关推荐
古月-一个C++方向的小白6 小时前
C++11之lambda表达式与包装器
开发语言·c++
tanyongxi668 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
斯是 陋室9 小时前
在CentOS7.9服务器上安装.NET 8.0 SDK
运维·服务器·开发语言·c++·c#·云计算·.net
tju新生代魔迷10 小时前
C++:list
开发语言·c++
HHRL-yx10 小时前
C++网络编程 5.TCP套接字(socket)通信进阶-基于多线程的TCP多客户端通信
网络·c++·tcp/ip
tomato0911 小时前
河南萌新联赛2025第(一)场:河南工业大学(补题)
c++·算法
每一天都要努力^13 小时前
C++拷贝构造
开发语言·c++
NoirSeeker15 小时前
在windows平台上基于OpenHarmony sdk编译三方库并暴露给ArkTS使用(详细)
c++·windows·arkts·鸿蒙·交叉编译
落羽的落羽15 小时前
【C++】(万字)一文看懂“类与对象”
c++
闻缺陷则喜何志丹16 小时前
【带权的并集查找】 P9235 [蓝桥杯 2023 省 A] 网络稳定性|省选-
数据结构·c++·蓝桥杯·洛谷·并集查找