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)?
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).
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 to dladdr
if all else fails; that is what backtrace_symbols
is doing).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With