Chapter 09:User Process
===
:::info
作業系統的終極任務就是向 User Process 提供服務,所以本章的目標就是成功跳轉 User Process。本章的背景知識之前在 ==[Chapter 03-1:Privilege Level Switching](https://hackmd.io/@srhuang/BJO73NE5le)== 有詳細的範例實作,如果對於如何切換權限 (Ring0/Ring3) 還不熟悉的人可以先補充這部分的知識。
  1. Memory mgmt. for user process
  2. Load User Process
  3. Jump to User Process
:::
>[time=Sat, Nov 29, 2025 2:46 AM]
---
https://youtu.be/er73Fo5T-dQ
<iframe width="560" height="315" src="https://www.youtube.com/embed/er73Fo5T-dQ?si=Xgi1xiXKt3X7d9tl" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
# Memory mgmt. for user process
>[!Note] Support user virtual address bitmap
>
>[!Note] Overview of memory mgmt.
>
>[!Note] Overview of memory bitmap
>
## Source Code
https://github.com/srhuang/a-os/commit/c7be2124ddbfc485325e08ac81158bf0b131fb48
## Compile
```
make all
```
## Put on hard disk
```
sh gen.sh
```
## Checkpoint

# Load User Process

>[!Note] hard disk layout
>
>[!Note] ELF
>
>[!Note] Section & Segment
>Segment = loader 使用的單位(程式執行需要的 memory 區塊)
>Section = linker 使用的單位(編譯/連結時的邏輯區塊)
>Segment 是由多個 section 合併形成的。
>Section 不一定會出現在任何 segment 裡(很多純工具用的 section)。
>
## Source Code
https://github.com/srhuang/a-os/commit/dadee4c58be66de81054e4b215cb04ff0dbe0558
## Compile
```
make all
```
## Put on hard disk
==gen.sh==
```sh=
dd if=../code/out/mbr.bin of=./60mb.img bs=512 count=1 conv=notrunc
dd if=../code/out/loader.bin of=./60mb.img bs=512 count=4 seek=1 conv=notrunc
dd if=../code/out/kernel.bin of=./60mb.img bs=512 count=200 seek=5 conv=notrunc
dd if=../code/out/usr.bin of=./60mb.img bs=512 count=100 seek=205 conv=notrunc
```
```
sh gen.sh
```
## Checkpoint

```
ll out/usr.bin
```

```
readelf -h -l out/usr.bin
```

# Jump to User Process
>[!Note] TSS data structure
>
>[!Note] TSS Descriptor
>
>[!Note] User Process Stack
>
>[!Note] User Process Kernel Stack (Ring 0 --> Ring 3)
>
>[!Note] Interrupt Triggered Kernel Stack (Ring 3 --> Ring 0)
>
>[!Note] System Call Kernel Stack (Ring 3 --> Ring 0)
>
>[!Warning] mmap_min_addr
>The default value for mmap_min_addr varies by Linux distribution and kernel version, but it's commonly set to 65536 (64 KiB) for security to prevent NULL-pointer dereference exploits
>`cat /proc/sys/vm/mmap_min_addr`
>我們設定最低的 user space virtual address is `0x10000`
## Source Code
https://github.com/srhuang/a-os/commit/3f5c978caa14576bef935050a6221ed889b6e870
## Compile
```
make all
```
## Put on hard disk
```
sh gen.sh
```
## Checkpoint

```
vb 0x2b:0x80480a0
c
info gdt
info tab
```
