C++ – How does GDB pause an execution

cdebugging

As you may know, we can use GDB and set breakpoints on our code to pause execution for debugging.

My questions is, how does GDB pause a process and let you view the content of registers using i r for example. Aren't those register being used by other OS processes constantly? how do they not get overwritten?

Is it only a snapshot of the content and not live data?

Best Answer

It varies slightly with the architecture, but the important points apply nearly universally:

  • Interrupt servicing causes the CPU state (including registers) to be saved to memory before running the ISR, and restored as the ISR exits.

  • If an interrupt service routine swaps the content of the memory location where those registers are saved, it can perform a context switch. Every thread has a memory region where its registers are saved when the thread isn't running.

  • The context switch is controlled by a thread scheduler which takes into account whether a thread is waiting for I/O, synchronization, what its priority is, signal delivery, etc. Often there's a suspend count which is factored in.

  • The debugger can increment the suspend count, which guarantees the thread isn't runnable. Then it can inspect (and change) the thread's saved copy of registers.

Related Topic