了解 cpu 寄存器

Understanding cpu registers

我是汇编语言的初学者,并试图了解这些都是如何工作的。我的问题可能看起来很愚蠢,但无论如何,我不太清楚。

考虑以下简单程序:

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

这里我们更新寄存器中的值并通过系统调用将其打印出来。但我想知道如果 OS(我使用的是 Ubuntu 16.04)在同一个核心上安排一些进程会怎样。这意味着进程以自己的方式更新 CPU 寄存器。 OS linux 是怎么处理的呢?我的意思是每个进程都有自己一致的寄存器值并且不受其他进程的影响?

在同一核心上的进程之间切换时,OS 保存前一个进程的寄存器。这就是所谓的上下文切换(您可以搜索更多详细信息)。然后OS恢复下一个进程的寄存器。

当内核 运行ning 时,它会在某个地方(在内核内存中)保存当前任务的寄存器内容的备份(在许多处理器上,可能有一些机器指令或硬件机制来帮助那个)。

当内核 运行 是 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.

当该任务请求(例如通过某些系统调用)运行 时,内核首先备份寄存器内容。

阅读 Operating Systems : Three Easy Pieces(可免费下载的书籍)。

每个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都有自己的寄存器内容(但它们共享 一些状态 - 特别是虚拟地址 space、文件描述符等... - 与同一进程中的其他线程)。