从另一个线程打印堆栈跟踪
我知道我可以使用 backtrace() 或 [NSThread callStackSymbols] 获取当前线程的堆栈跟踪,但是如何获取不同线程的堆栈跟踪(假设它已被冻结)?
I know I can get the stack trace of the current thread using backtrace() or [NSThread callStackSymbols], but how would I get at the stack trace of a DIFFERENT thread (assuming it's been frozen)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:我原来的答案不会从任意线程打印。此后,我在崩溃处理程序项目中编写了正确的实现: https://github.com/kstenerud/KSCrash
具体来说,这些文件:
需要一些帮助来自:
您要做的是:
请注意,在执行此操作之前应该暂停线程,否则可能会得到不可预测的结果。
堆栈帧充满了包含两个指针的结构:
因此,在遍历帧以填写堆栈跟踪时需要考虑到这一点。堆栈也有可能损坏,导致指针错误,从而导致程序崩溃。您可以通过使用 vm_read_overwrite() 复制内存来解决这个问题,它首先询问内核是否有权访问内存,这样就不会崩溃。
一旦获得了堆栈跟踪,您就可以像平常一样调用 backtrace() (崩溃处理程序必须是异步安全的,因此它实现了自己的 backtrace 方法,但在正常情况下 backtrace() 就可以了)。
EDIT: My original answer will not print from an arbitrary thread. I've since written a proper implementation in my crash handler project: https://github.com/kstenerud/KSCrash
Specifically, these files:
With some help from:
What you do is:
Note that you should pause the thread before doing this or else you can get unpredictable results.
The stack frame is filled with structures containing two pointers:
So you need to take that into account when walking the frame to fill out your stack trace. There's also the possibility of a corrupted stack, leading to a bad pointer, which will crash your program. You can get around this by copying memory using vm_read_overwrite(), which first asks the kernel if it has access to the memory, so it doesn't crash.
Once you have the stack trace, you can just call backtrace() on it like normal (The crash handler has to be async-safe so it implements its own backtrace method, but in normal cases backtrace() is fine).
这是从另一个线程获取调用堆栈的一些更安全的方法: 实现 和一些背景信息。它使用信号处理并在目标线程中生成信号处理程序。它还具有比您的解决方案更具跨平台性的优点,即它应该可以在您拥有
和
的任何地方工作>。对于打印,您可以按照您自己的建议使用
backtrace_symbols
。但您可能对此处实现的扩展版本感兴趣。它使用 libbfd(来自 binutils;最新版本也主要适用于 MacOSX,请参阅此处了解可能不相关的小限制为您)读取调试信息并添加行号和其他信息(如果其他所有方法都失败,它也会回退到 dladdr;这就是 backtrace_symbols 正在做的事情) 。Here is some safer way to get the callstack from another thread: Implementation and some background information. It uses signal handling and spawns a signal handler in the target thread. It has also the advantage that it is more cross-platform than your solution, i.e. it should work anywhere where you have
<signal.h>
and<execinfo.h>
.For the printing, you can use
backtrace_symbols
as you do in your own suggestion. But you might be interested in an extended version of that as implemented here. It uses libbfd (from binutils; the recent version also mostly works on MacOSX, see here for a small limitation which might not be relevant for you) to read the debugging information and to add line-number and other information (it also falls back todladdr
if all else fails; that is whatbacktrace_symbols
is doing).