Using gdb's Python to backtrace different OS threads, when gdb is not OS-aware
<p>I am still learning about debugging C using python within gdb (arm-none-eabi-gdb, in my case).  I am trying to use this facility to get thread information of a real-time OS running on ARM Cortex-M. Reading some OS structures, I can access <em>the</em> thread control blocks of the OS. I know the PC and the SP of each thread. How can I use gdb's Python to dump the threads' backtrace. Is there a generic API that can traverse the stack when given PC and SP?</p>

<p>I have read <a href="https://sourceware.org/gdb/current/onlinedocs/gdb/Unwinding-Frames-in-Python.html#Unwinding-Frames-in-Python" rel="nofollow">https://sourceware.org/gdb/current/onlinedocs/gdb/Unwinding-Frames-in-Python.html#Unwinding-Frames-in-Python</a> and I feel there might be a way to achieve that but I need some help.</p>

<p>Also, if possible, can I make gdb aware of the different threads of the OS? This link: 
<a href="https://sourceware.org/gdb/current/onlinedocs/gdb/Threads-In-Python.html#Threads-In-Python" rel="nofollow">https://sourceware.org/gdb/current/onlinedocs/gdb/Threads-In-Python.html#Threads-In-Python</a> touches on threads but relies on OS info. Can these be overload with what I know about the different OS threads from their respective control blocks?</p>

<p>Thanks!</p>

<p>After some more reading and trying to make use of old debugger knowledge that I have accumulated over the years, I managed to get this working. It lacks optimization but for now, I'm very please. This can be considered a poor-man's debugger making use of GDB's Python support to track the active threads in the system. It's generic, I assume, but the implementation targeted RTX (Keil's OS). It worked on Cortex-M0. It may need some tweaking to fit other operating systems or different cores.</p>

<p><strong>The main idea:</strong></p>

<ol>
<li>Use OS structures, to identify where the thread control block reside.</li>
<li>From the thread control block identify where is the different thread stacks are.</li>
<li>Read from the stack all the vital registers; SP, LR, and PC</li>
<li>Save the same registers for the current, running thread.</li>
<li>Loop over the different thread, change the vital registers to the ones matching the thread, then print the backtrace.</li>
<li>Enjoy a poor-man's OS-aware debugger.</li>
</ol>

<p>The script can be found here:</p>

<p><a href="https://gitlab.com/hesham/gdb-rtx-thread-backtrce/blob/master/rtx-threads-bt.py" rel="nofollow">https://gitlab.com/hesham/gdb-rtx-thread-backtrce/blob/master/rtx-threads-bt.py</a></p>

<p>It was a very good exercise to explore the power of GDB's Python extension!</p>

python c debugging operating-system gdb