Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding cpu registers

I'm very beginner in assembly language and trying to understand how these all work. My question may seem very dumb but anyway, it's not quite clear to me.

Consider the following simple program:

section .text
    global _start

_start:

    mov eax, [text]
    mov [val], eax
    mov ecx, val
    mov eax, 4
    mov edx, 7
    mov ebx, 1
    int 0x80

    mov eax, 1
    int 0x80

segment .bss
    val resb 2

segment .data
    text db "Th"
    len equ $- text

Here we update values in registers and print it out with system call. But I'm wondering what if OS (I'm using Ubuntu 16.04) schedules some process on the same core. It means the process updates CPU registers in its own way. How does OS linux handle it? I mean each process has its own consistent registers value and not affected by some another process?

like image 948
St.Antario Avatar asked Oct 26 '25 13:10

St.Antario


2 Answers

When the kernel is running, it keeps somewhere (in kernel memory) a backup of the register contents of the current task (on many processors, there might be some machine instruction or hardware mechanism to help that).

When the kernel runs the scheduler and it choose to run some task, that register state is restored. Notice that Linux has preemptive scheduling. Read about context switching and interrupts and CPU modes. Try several times cat /proc/interrupts in a terminal. See proc(5) for more about /proc/. Read more about x86-64.

When that task asks (e.g. via some system call) to run, the kernel starts by backing up the register contents.

Read Operating Systems : Three Easy Pieces (freely downloadable book).

Each process has, from the point of view of user-space code, its register content, its set of file descriptors, its virtual address space etc... (and the kernel, including its scheduler, is managing all that). For multi-threaded processes, every thread has its register content (but they share some state - notably virtual address space, file descriptors, etc... - with other threads in the same process).

like image 199
Basile Starynkevitch Avatar answered Oct 28 '25 02:10

Basile Starynkevitch


Upon switching between processes on the same core, the OS saves the registers of the previous process. That is called context-switching (you may search for more details). Then the OS restores the registers of the next process.

like image 31
Serge Rogatch Avatar answered Oct 28 '25 02:10

Serge Rogatch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!