Getting a backtrace of other thread

前端 未结 3 463
忘掉有多难
忘掉有多难 2020-11-29 07:34

In Linux, to get a backtrace you can use backtrace() library call, but it only returns backtrace of current thread. Is there any way to get a backtrace of some other thread,

相关标签:
3条回答
  • 2020-11-29 07:58

    Signal Handling with the help of backtrace can solve your purpose.

    I mean if you have a PID of the Thread, you can raise a signal for that thread. and in the handler you can use the backtrace. since the handler would be executing in that partucular thread, the backtrace there would be the output what you are needed.

    0 讨论(0)
  • 2020-11-29 07:59

    gdb provides these facilities for debugging multi-thread programs:

    • automatic notification of new threads
    • ‘thread thread-id’, a command to switch among threads
    • ‘info threads’, a command to inquire about existing threads
    • ‘thread apply [thread-id-list] [all] args’, a command to apply a command to a list of threads
    • thread-specific breakpoints
    • ‘set print thread-events’, which controls printing of messages on thread start and exit.
    • ‘set libthread-db-search-path path’, which lets the user specify which libthread_db to use if the default choice isn't compatible with the program.

    So just goto required thread in GDB by cmd: 'thread thread-id'. Then do 'bt' in that thread context to print the thread backtrace.

    0 讨论(0)
  • 2020-11-29 08:01

    I implemented that myself here.

    Initially, I wanted to implement something similar as suggested here, i.e. getting somehow the top frame pointer of the thread and unwinding it manually (the linked source is derived from Apples backtrace implementation, thus might be Apple-specific, but the idea is generic).

    However, to have that safe (and the source above is not and may even be broken anyway), you must suspend the thread while you access its stack. I searched around for different ways to suspend a thread and found this, this and this. Basically, there is no really good way. The common hack, also used by the Hotspot JAVA VM, is to use signals and sending a custom signal to your thread via pthread_kill.

    So, as I would need such signal-hack anyway, I can have it a bit simpler and just use backtrace inside the called signal handler which is executed in the target thread (as also suggested here by sandeep). This is basically what my implementation is doing.

    If you are also interested in printing the backtrace, i.e. get some useful debugging information (function name, source code filename, source code line number, ...), read here about an extended backtrace_symbols based on libbfd. Or just see the source here.

    0 讨论(0)
提交回复
热议问题