libunwind:记录程序崩溃堆栈

清泛原创
项目地址:https://github.com/libunwind/libunwind
源码编译安装:
git clone https://github.com/libunwind/libunwind
cd libunwind
./autogen.sh
./configure --prefix=/usr --enable-shared  #编译成.so,否则默认静态.la
make
make install
记录堆栈的代码如下:
static void log_backtrace(void) {
	char name[256];
	unw_cursor_t cursor;
	unw_context_t uc;
	unw_word_t ip, sp, offp;

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

	syslog(LOG_ERR, "--illegal memory access--");
	while(unw_step(&cursor) > 0) {
		name[0] = '\0';
		unw_get_proc_name(&cursor, name, 256, &offp);
		unw_get_reg(&cursor, UNW_REG_IP, &ip);
		unw_get_reg(&cursor, UNW_REG_SP, &sp);

		syslog(LOG_ERR, "Dump info: %s ip=%lx, sp=%lx\n", name, (long)ip, (long)sp);
	}
}

static void cri_sighandler(int sig) {
	log_backtrace();
	throw std::runtime_error("illegal memory access");
	//eixt(1);
}
链接时加上 -lunwind 即可。如果还是链接失败,尝试 -lunwind -lunwind-x86_64
打印效果参考如下:

--End--

libunwind

分享到:
评论加载中,请稍后...
创APP如搭积木 - 创意无限,梦想即时!
回到顶部