Back in the old days of single tasking OSses, the only things that could get in the way of the execution of your program were interrupts. Now, interrupt handlers have the same problem you're talking about, your program is calculating something, user presses a key - interrupt - the interrupt service routine has to do some work but must not modify a single register in the process. That's the main reason, the stack was invented in the first place. A usual 80x86 DOS interrupt service routine would look like this:
push ax
push cx
push dx
push bx
push si
push di
push bp
// no need to push sp
[do actual work, caller registers avaiable on stack if needed]
pop bp
pop di
pop si
pop bx
pop dx
pop cx
pop ax
iret
This was even so common, that a new instruction pair pusha
and popa
(for push/pop all) was created to ease this task.
In today's CPUs with address space isolation between the operation systems and applications, the CPUs provide some task states system and allow the operation system to switch tasks (interrupts may still work similar to outlined above, but can also be handled via task switching). All modern OSses use this kine of task state systems, where the CPU saves all the registers of a process while it is not being actively executed. Like Jester already explained, gdb
just asks the OS for this values on the process to be debugged and then print them.
call stack
and theinstruction pointer
are manipulated. One way to use registers, and still know what they were, is to push them on he stack before you change them. Because you know how many bytes you pushed on the stack, you can even deduce what the stack pointer was before you started changing things. Many CPUs, however, have a fast instruction to copy all registers to/from a buffer. Mostly used to swap processes out so the CPU and registers can be shared, but a debugger does this also. – Jesse Chisholm