As I was learning about assembly, I used GDB the following way:
gdb ./a.out (a is a compiled C script that only prints hello world)
break main
run
info registers
Why can I see the registers used by my program when I am myself using the same CPU to print the registers? Shouldn't the use of GDB (or operating system) overwrite the registers and only show me the overwritten registers? The only answer I can think of is the fact that my CPU is dual-core and that one of the cores is being used and the other is kept for the program.
The operating system maintains the state of the registers for each execution thread. When you are examining registers in gdb, the debugger is actually asking the OS to read the register value from the saved state. Your program is not running at that point in time, it's the debugger which is.
Let's assume there are no other processes on your system. Here is a simplified view of what happens:
Note that this mechanism is part of the normal duties of a multitasking operating system, it's not specific to debugging. When the OS scheduler decides a different program should be executing, it saves the current state and loads another. This is called a context switch and it may happen many times per second, giving the illusion that programs execute simultaneously even if you only have a single cpu core.
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:
This was even so common, that a new instruction pair
pusha
andpopa
(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.