在信号处理程序中获取文件、源代码行和变量名称

发布于 2025-01-12 06:29:04 字数 371 浏览 5 评论 0 原文

我为段错误安装了自定义信号处理程序,

void sa_sigHandler(int signo, siginfo_t *info, void *context) {
  ...
  void *variableAddr = info->si_addr;
  ucontext_t *uctx = (ucontext_t *)context;    
  unsigned long inst = uctx->uc_mcontext.gregs[REG_RIP];
  // how to get file, source line and object name here ?
  ...
}

我看到了一些类似的问题,但没有找到具体的代码来实现这一点。

I installed custom signal handler for segfaults

void sa_sigHandler(int signo, siginfo_t *info, void *context) {
  ...
  void *variableAddr = info->si_addr;
  ucontext_t *uctx = (ucontext_t *)context;    
  unsigned long inst = uctx->uc_mcontext.gregs[REG_RIP];
  // how to get file, source line and object name here ?
  ...
}

I saw a few similar questions but found no concrete code to achieve this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坐在坟头思考人生 2025-01-19 06:29:04

在信号处理程序中获取文件、源代码行和变量名称

正如 @zwol 评论的那样,这很难做到,最好使用现有的解决方案,例如 BreakpadApport

如果必须在运行时报告此情况,最好将应用程序包装在 GDB 脚本中;类似于 gdb -ex run -ex where -ex quit /path/to/a.out 。

如果您仍然坚持在 CC++ 中执行此操作,您可以从 libdwarf,但请注意,从信号处理程序中使用它会带来额外的复杂性(它不是异步信号安全的),因此您需要构建从程序计数器到源文件/行的映射信息提前,并且仅在崩溃时进行查找。

就我而言,我正在寻找发生段错误的(共享对象的)地址

导致SIGSEGV地址可直接用作uctx->uc_mcontext .gregs[REG_RIP] 并且您的代码已经将其作为 inst 获取,因此您不是在寻找它,而是在寻找其他东西。

如果其他内容是“上述地址的文件/行信息”,请参见上文。您还可以execv此命令来打印该信息(这可以以异步安全的方式完成):/usr/bin/addr2line -fe /path/to/binary $inst.

Get file, source line and variable name in signal handler

As @zwol commented, this is pretty hard to do, and you'll be better off using existing solutions, such as Breakpad or Apport.

If you must report this at runtime, you may be better off wrapping the application in a GDB script; something like gdb -ex run -ex where -ex quit /path/to/a.out.

If you still insist on doing this in C or C++, you could benefit from libdwarf, but note that using it from a signal handler presents additional complications (it is not async-signal safe), so you'll need to build a map from program counters to source file/line info ahead of time, and only do the lookups at crash time.

in my case, I am looking for the address(of shared object) on which segfault occurs

The address which caused SIGSEGV is directly available as uctx->uc_mcontext.gregs[REG_RIP] and your code already gets that as inst, so you are not looking for that, but for something else.

If that something else is "file / line info for the above address", see above. You could also execv this command to print that info (this can be done in async-safe manner): /usr/bin/addr2line -fe /path/to/binary $inst.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文