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

相关推荐
hetao17338372 小时前
2026-10-08 hetao1733837 的刷题记录
c++·算法
Frank_refuel3 小时前
【C++】智能指针
开发语言·c++
一只旭宝4 小时前
数据结构与算法复习手册:从写过,到讲清楚
开发语言·数据结构·c++·算法
十五年专注C++开发4 小时前
std::filesystem::exists 在有的win10系统抛异常原因分析
c++·文件系统·filesystem
hetao17338375 小时前
2026-10-07 hetao1733837 的刷题记录
c++·算法
longlongzihan5 小时前
前缀积与后缀积 —— LeetCode 238. 除了自身以外数组的乘积
开发语言·c++·leetcode
All for pursuit.5 小时前
【动态规划-1】121.买卖股票的最佳时机
数据结构·c++·算法·leetcode·动态规划
水饺编程5 小时前
第1章,[Win32 章节]:API 及 内存管理模式
c语言·c++·windows·visual studio
weixin_307779135 小时前
C++代码实现MATLAB中的cvpartition函数功能
开发语言·c++·算法·matlab
(Charon)6 小时前
【C++面试】线程同步机制:互斥锁、条件变量、原子操作与读写锁
开发语言·c++·算法·面试