hackclub / putting-the-you-in-cpu

A technical explainer by @kognise of how your computer runs programs, from start to finish.
https://cpu.land
MIT License
4.71k stars 145 forks source link

Potentially unclear explanation of register usage in chapter 4 - Becoming an elf lord #57

Open oli-clive-griffin opened 6 months ago

oli-clive-griffin commented 6 months ago

The kernel is almost ready to return from the syscall (remember, we’re still in execve). It pushes the argc, argv, and environment variables to the stack for the program to read when it begins.

The registers are now cleared. Before handling a syscall, the kernel stores the current value of registers to the stack to be restored when switching back to user space. Before returning to user space, the kernel zeroes this part of the stack.

Finally, the syscall is over and the kernel returns to userland. It restores the registers, which are now zeroed, and jumps to the stored instruction pointer. That instruction pointer is now the starting point of the new program (or the ELF interpreter) and the current process has been replaced!

When I first read this I was confused as to the order of operations. After a few reads I thought maybe it went like this

  1. execve starts
  2. register values copied onto stack
  3. execve almost finishing up
  4. register values copied back into registers
  5. memory that held those values is zeroed

I was going to open a PR correcting this but then realised I wasn't sure if I was right. Is it actually that the memory is zeroed and then zeroes are copied back into the registers? that didn't seem right to me ("It restores the registers, which are now zeroed")

Anyway, would love to be corrected!

P.S. thanks so much for these blog posts, they're awesome