mirror of
https://github.com/phil-opp/blog_os.git
synced 2025-12-16 14:27:49 +00:00
Compare commits
25 Commits
5681d3f0f7
...
2676d69c31
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2676d69c31 | ||
|
|
c31f3c2728 | ||
|
|
5799263124 | ||
|
|
ded60de8d0 | ||
|
|
171956adc8 | ||
|
|
e2a4464835 | ||
|
|
f0fe3929ab | ||
|
|
c728cf8225 | ||
|
|
f38c11ae8e | ||
|
|
a1b195ede0 | ||
|
|
cfd31a977d | ||
|
|
06dd5edb3f | ||
|
|
685f55dd31 | ||
|
|
0b6b053c54 | ||
|
|
e0464fbd44 | ||
|
|
5e88b86d1e | ||
|
|
e6b507e6d2 | ||
|
|
5baf50a5b4 | ||
|
|
5d63300512 | ||
|
|
739d9e1a3c | ||
|
|
8a1063df5f | ||
|
|
d2c6b281c8 | ||
|
|
3900ddeb2c | ||
|
|
a7f4647e73 | ||
|
|
a7cfc562e9 |
@@ -51,6 +51,9 @@ translation_contributors = "With contributions from"
|
||||
word_separator = "and"
|
||||
|
||||
# Chinese (simplified)
|
||||
[languages.zh-CN]
|
||||
title = "Writing an OS in Rust"
|
||||
description = "This blog series creates a small operating system in the Rust programming language. Each post is a small tutorial and includes all needed code."
|
||||
[languages.zh-CN.translations]
|
||||
lang_name = "Chinese (simplified)"
|
||||
toc = "目录"
|
||||
@@ -66,6 +69,9 @@ translation_contributors = "With contributions from"
|
||||
word_separator = "和"
|
||||
|
||||
# Chinese (traditional)
|
||||
[languages.zh-TW]
|
||||
title = "Writing an OS in Rust"
|
||||
description = "This blog series creates a small operating system in the Rust programming language. Each post is a small tutorial and includes all needed code."
|
||||
[languages.zh-TW.translations]
|
||||
lang_name = "Chinese (traditional)"
|
||||
toc = "目錄"
|
||||
@@ -81,6 +87,9 @@ translation_contributors = "With contributions from"
|
||||
word_separator = "和"
|
||||
|
||||
# Japanese
|
||||
[languages.ja]
|
||||
title = "Writing an OS in Rust"
|
||||
description = "This blog series creates a small operating system in the Rust programming language. Each post is a small tutorial and includes all needed code."
|
||||
[languages.ja.translations]
|
||||
lang_name = "Japanese"
|
||||
toc = "目次"
|
||||
@@ -96,6 +105,9 @@ translation_contributors = "With contributions from"
|
||||
word_separator = "及び"
|
||||
|
||||
# Persian
|
||||
[languages.fa]
|
||||
title = "Writing an OS in Rust"
|
||||
description = "This blog series creates a small operating system in the Rust programming language. Each post is a small tutorial and includes all needed code."
|
||||
[languages.fa.translations]
|
||||
lang_name = "Persian"
|
||||
toc = "فهرست مطالب"
|
||||
@@ -111,6 +123,9 @@ translation_contributors = "With contributions from"
|
||||
word_separator = "و"
|
||||
|
||||
# Russian
|
||||
[languages.ru]
|
||||
title = "Writing an OS in Rust"
|
||||
description = "This blog series creates a small operating system in the Rust programming language. Each post is a small tutorial and includes all needed code."
|
||||
[languages.ru.translations]
|
||||
lang_name = "Russian"
|
||||
toc = "Содержание"
|
||||
@@ -126,6 +141,9 @@ translation_contributors = "With contributions from"
|
||||
word_separator = "и"
|
||||
|
||||
# French
|
||||
[languages.fr]
|
||||
title = "Writing an OS in Rust"
|
||||
description = "This blog series creates a small operating system in the Rust programming language. Each post is a small tutorial and includes all needed code."
|
||||
[languages.fr.translations]
|
||||
lang_name = "French"
|
||||
toc = "Table des matières"
|
||||
@@ -141,6 +159,9 @@ translation_contributors = "With contributions from"
|
||||
word_separator = "et"
|
||||
|
||||
# Korean
|
||||
[languages.ko]
|
||||
title = "Writing an OS in Rust"
|
||||
description = "This blog series creates a small operating system in the Rust programming language. Each post is a small tutorial and includes all needed code."
|
||||
[languages.ko.translations]
|
||||
lang_name = "Korean"
|
||||
toc = "목차"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
+++
|
||||
title = "Un binaire Rust autonome"
|
||||
title = "Un binaire Rust autoporté"
|
||||
weight = 1
|
||||
path = "fr/freestanding-rust-binary"
|
||||
date = 2018-02-10
|
||||
@@ -29,7 +29,7 @@ Ce blog est développé sur [GitHub]. Si vous avez un problème ou une question,
|
||||
|
||||
## Introduction
|
||||
Pour écrire un noyau de système d'exploitation, nous avons besoin d'un code qui ne dépend pas de fonctionnalités de système d'exploitation. Cela signifie que nous ne pouvons pas utiliser les fils d'exécution, les fichiers, la mémoire sur le tas, le réseau, les nombres aléatoires, la sortie standard ou tout autre fonctionnalité nécessitant une abstraction du système d'exploitation ou un matériel spécifique. Cela a du sens, étant donné que nous essayons d'écrire notre propre OS et nos propres pilotes.
|
||||
Cela signifie que nous ne pouvons pas utiliser la majeure partie de la [bibliothèque standard de Rust]. Il y a néanmoins beaucoup de fonctionnalités de Rust que nous _pouvons_ utiliser. Par exemple, nous pouvons utiliser les [iterators], les [closures], le [pattern matching], l'[option] et le [result], le [string formatting], et bien-sûr l'[ownership system]. Ces fonctionnalités permettent l'écriture d'un noyau d'une façon expressive et haut-niveau sans se soucier des [comportements indéfinis] ou de la [sécurité de la mémoire].
|
||||
Cela signifie que nous ne pouvons pas utiliser la majeure partie de la [bibliothèque standard de Rust]. Il y a néanmoins beaucoup de fonctionnalités de Rust que nous _pouvons_ utiliser. Par exemple, nous pouvons utiliser les [iterators], les [closures], le [pattern matching], l'[option] et le [result], le [string formatting], et bien sûr l'[ownership system]. Ces fonctionnalités permettent l'écriture d'un noyau d'une façon expressive et haut-niveau sans se soucier des [comportements indéfinis] ou de la [sécurité de la mémoire].
|
||||
|
||||
[option]: https://doc.rust-lang.org/core/option/
|
||||
[result]:https://doc.rust-lang.org/core/result/
|
||||
@@ -47,18 +47,18 @@ Cet article décrit les étapes nécessaires pour créer un exécutable Rust aut
|
||||
|
||||
## Désactiver la Bibliothèque Standard
|
||||
|
||||
Par défaut, tous les crates Rust relient la [bibliothèque standard], qui dépend du système d'exploitation pour les fonctionnalités telles que les fils d'exécution, les fichiers ou le réseau. Elle dépend aussi de la bibliothèque standard de C `libc`, qui intéragit de près avec les services de l'OS. Comme notre plan est d'écrire un système d'exploitation, nous ne pouvons pas utiliser des bibliothèques dépendant de l'OS. Nous devons donc désactiver l'inclusion automatique de la bibliothèque standard en utilisant l'[attribut `no std`].
|
||||
Par défaut, toutes les crates Rust sont liées à la bibliothèque standard, qui repose sur les fonctionnalités du système d’exploitation telles que les fils d'exécution, les fichiers et la connectivité réseau. Elle est également liée à la bibliothèque standard C `libc`, qui interagit étroitement avec les services fournis par l'OS. Comme notre plan est d'écrire un système d'exploitation, nous ne pouvons pas utiliser des bibliothèques dépendant de l'OS. Nous devons donc désactiver l'inclusion automatique de la bibliothèque standard en utilisant l'[attribut `no std`].
|
||||
|
||||
[bibliothèque standard]: https://doc.rust-lang.org/std/
|
||||
[attribut `no std`]: https://doc.rust-lang.org/1.30.0/book/first-edition/using-rust-without-the-standard-library.html
|
||||
|
||||
Nous commencons par créer un nouveau projet d'application cargo. La manière la plus simple de faire est avec la ligne de commande :
|
||||
Nous commençons par créer un nouveau projet d'application cargo. La manière la plus simple de faire est avec la ligne de commande :
|
||||
|
||||
```
|
||||
cargo new blog_os --bin --edition 2018
|
||||
```
|
||||
|
||||
J'ai nommé le projet `blog_os`, mais vous pouvez bien-sûr choisir le nom qu'il vous convient. Le flag `--bin` indique que nous voulons créer un exécutable (contrairement à une bibliothèque) et le flag `--edition 2018` indique que nous voulons utiliser l'[édition 2018] de Rust pour notre crate. Quand nous lançons la commande, cargo crée la structure de répertoire suivante pour nous :
|
||||
J'ai nommé le projet `blog_os`, mais vous pouvez évidemment choisir le nom qu'il vous convient. Le flag `--bin` indique que nous voulons créer un exécutable (contrairement à une bibliothèque) et le flag `--edition 2018` indique que nous voulons utiliser l'[édition 2018] de Rust pour notre crate. Quand nous lançons la commande, cargo crée la structure de répertoire suivante pour nous :
|
||||
|
||||
[édition 2018]: https://doc.rust-lang.org/nightly/edition-guide/rust-2018/index.html
|
||||
|
||||
@@ -75,7 +75,7 @@ Le fichier `Cargo.toml` contient la configuration de la crate, par exemple le no
|
||||
|
||||
### L'Attribut `no_std`
|
||||
|
||||
Pour l'instant, notre crate relie la bilbiothèque standard implicitement. Désactivons cela en ajoutant l'[attribut `no std`] :
|
||||
Pour l'instant, notre crate relie la bibliothèque standard implicitement. Désactivons cela en ajoutant l'[attribut `no std`] :
|
||||
|
||||
```rust
|
||||
// main.rs
|
||||
|
||||
@@ -383,7 +383,7 @@ error: linking with `cc` failed: exit code: 1
|
||||
cargo rustc -- -C link-args="-e __start"
|
||||
```
|
||||
|
||||
`-e` 表示肉口點的函式名稱,然後由於 macOS 上所有的函式都會加上前綴 `_`,我們需要設置入口點為 `__start` 而不是 `_start`。
|
||||
`-e` 表示入口點的函式名稱,然後由於 macOS 上所有的函式都會加上前綴 `_`,我們需要設置入口點為 `__start` 而不是 `_start`。
|
||||
|
||||
接下來會出現另一個連結器錯誤:
|
||||
|
||||
|
||||
@@ -323,7 +323,7 @@ build-std-features = ["compiler-builtins-mem"]
|
||||
در پشت صحنه، این پرچم [ویژگی `mem`] از کریت `compiler_builtins` را فعال میکند. اثرش این است که صفت `[no_mangle]#` بر روی [پیادهسازی `memcpy` و بقیه موارد] از کریت اعمال میشود، که آنها در دسترس لینکر قرار میدهد. شایان ذکر است که این توابع در حال حاضر [بهینه نشدهاند]، بنابراین ممکن است عملکرد آنها در بهترین حالت نباشد، اما حداقل صحیح هستند. برای `x86_64` ، یک pull request باز برای [بهینه سازی این توابع با استفاده از دستورالعملهای خاص اسمبلی][memcpy rep movsb] وجود دارد.
|
||||
|
||||
[ویژگی `mem`]: https://github.com/rust-lang/compiler-builtins/blob/eff506cd49b637f1ab5931625a33cef7e91fbbf6/Cargo.toml#L51-L52
|
||||
[پیادهسازی `memcpy` و بقیه موارد]: (https://github.com/rust-lang/compiler-builtins/blob/eff506cd49b637f1ab5931625a33cef7e91fbbf6/src/mem.rs#L12-L69)
|
||||
[پیادهسازی `memcpy` و بقیه موارد]: https://github.com/rust-lang/compiler-builtins/blob/eff506cd49b637f1ab5931625a33cef7e91fbbf6/src/mem.rs#L12-L69
|
||||
[بهینه نشدهاند]: https://github.com/rust-lang/compiler-builtins/issues/339
|
||||
[memcpy rep movsb]: https://github.com/rust-lang/compiler-builtins/pull/365
|
||||
|
||||
|
||||
@@ -317,7 +317,7 @@ build-std-features = ["compiler-builtins-mem"]
|
||||
このとき、裏で`compiler_builtins`クレートの[`mem`機能][`mem` feature]が有効化されています。これにより、このクレートの[`memcpy`などの実装][`memcpy` etc. implementations]に`#[no_mangle]`アトリビュートが適用され、リンカがこれらを利用できるようになっています。
|
||||
|
||||
[`mem` feature]: https://github.com/rust-lang/compiler-builtins/blob/eff506cd49b637f1ab5931625a33cef7e91fbbf6/Cargo.toml#L51-L52
|
||||
[`memcpy` etc. implementations]: (https://github.com/rust-lang/compiler-builtins/blob/eff506cd49b637f1ab5931625a33cef7e91fbbf6/src/mem.rs#L12-L69)
|
||||
[`memcpy` etc. implementations]: https://github.com/rust-lang/compiler-builtins/blob/eff506cd49b637f1ab5931625a33cef7e91fbbf6/src/mem.rs#L12-L69
|
||||
|
||||
この変更をもって、私達のカーネルはコンパイラに必要とされているすべての関数の有効な実装を手に入れたので、コードがもっと複雑になっても変わらずコンパイルできるでしょう。
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ UEFI 표준으로 동작하는 최신 기기들도 가상 BIOS를 지원하기
|
||||
지난 포스트에서 우리는 `cargo`를 통해 freestanding 실행파일을 만들었었는데, 호스트 시스템의 운영체제에 따라 프로그램 실행 시작 지점의 이름 및 컴파일 인자들을 다르게 설정해야 했습니다. 이것은 `cargo`가 기본적으로 _호스트 시스템_ (여러 분이 실행 중인 컴퓨터 시스템) 을 목표로 빌드하기 때문이었습니다. 우리의 커널은 다른 운영체제 (예를 들어 Windows) 위에서 실행될 것이 아니기에, 호스트 시스템에 설정 값을 맞추는 대신에 우리가 명확히 정의한 _목표 시스템 (target system)_ 을 목표로 컴파일할 것입니다.
|
||||
|
||||
### Rust Nightly 설치하기 {#installing-rust-nightly}
|
||||
Rust는 _stable_, _beta_ 그리고 _nightly_ 이렇게 세 가지의 채널을 통해 배포됩니다. Rust Book에 [세 채널들 간의 차이에 대해 잘 정리한 챕터]((https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#choo-choo-release-channels-and-riding-the-trains))가 있습니다. 운영체제를 빌드하기 위해서는 _nightly_ 채널에서만 제공하는 실험적인 기능들을 이용해야 하기에 _nightly_ 버전의 Rust를 설치하셔야 합니다.
|
||||
Rust는 _stable_, _beta_ 그리고 _nightly_ 이렇게 세 가지의 채널을 통해 배포됩니다. Rust Book에 [세 채널들 간의 차이에 대해 잘 정리한 챕터](https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#choo-choo-release-channels-and-riding-the-trains)가 있습니다. 운영체제를 빌드하기 위해서는 _nightly_ 채널에서만 제공하는 실험적인 기능들을 이용해야 하기에 _nightly_ 버전의 Rust를 설치하셔야 합니다.
|
||||
|
||||
여러 버전의 Rust 언어 설치 파일들을 관리할 때 [rustup]을 사용하는 것을 강력 추천합니다. rustup을 통해 nightly, beta 그리고 stable 컴파일러들을 모두 설치하고 업데이트할 수 있습니다. `rustup override set nightly` 명령어를 통해 현재 디렉토리에서 항상 nightly 버전의 Rust를 사용하도록 설정할 수 있습니다.
|
||||
`rust-toolchain`이라는 파일을 프로젝트 루트 디렉토리에 만들고 이 파일에 `nightly`라는 텍스트를 적어 놓아도 같은 효과를 볼 수 있습니다. `rustc --version` 명령어를 통해 현재 nightly 버전이 설치되어 있는지 확인할 수 있습니다 (출력되는 버전 넘버가 `-nightly`라는 텍스트로 끝나야 합니다).
|
||||
|
||||
@@ -49,7 +49,7 @@ pub extern "C" fn _start() -> ! {
|
||||
|
||||
// trigger a page fault
|
||||
unsafe {
|
||||
*(0xdeadbeef as *mut u64) = 42;
|
||||
*(0xdeadbeef as *mut u8) = 42;
|
||||
};
|
||||
|
||||
// as before
|
||||
|
||||
@@ -45,7 +45,7 @@ pub extern "C" fn _start() -> ! {
|
||||
|
||||
// ページフォルトを起こす
|
||||
unsafe {
|
||||
*(0xdeadbeef as *mut u64) = 42;
|
||||
*(0xdeadbeef as *mut u8) = 42;
|
||||
};
|
||||
|
||||
// 前回同様
|
||||
|
||||
@@ -48,7 +48,7 @@ pub extern "C" fn _start() -> ! {
|
||||
|
||||
// 페이지 폴트 일으키기
|
||||
unsafe {
|
||||
*(0xdeadbeef as *mut u64) = 42;
|
||||
*(0xdeadbeef as *mut u8) = 42;
|
||||
};
|
||||
|
||||
// 이전과 동일
|
||||
|
||||
@@ -42,7 +42,7 @@ pub extern "C" fn _start() -> ! {
|
||||
|
||||
// trigger a page fault
|
||||
unsafe {
|
||||
*(0xdeadbeef as *mut u64) = 42;
|
||||
*(0xdeadbeef as *mut u8) = 42;
|
||||
};
|
||||
|
||||
// as before
|
||||
@@ -374,9 +374,9 @@ pub fn init() {
|
||||
}
|
||||
```
|
||||
|
||||
We reload the code segment register using [`set_cs`] and load the TSS using [`load_tss`]. The functions are marked as `unsafe`, so we need an `unsafe` block to invoke them. The reason is that it might be possible to break memory safety by loading invalid selectors.
|
||||
We reload the code segment register using [`CS::set_reg`] and load the TSS using [`load_tss`]. The functions are marked as `unsafe`, so we need an `unsafe` block to invoke them. The reason is that it might be possible to break memory safety by loading invalid selectors.
|
||||
|
||||
[`set_cs`]: https://docs.rs/x86_64/0.14.2/x86_64/instructions/segmentation/fn.set_cs.html
|
||||
[`CS::set_reg`]: https://docs.rs/x86_64/0.14.5/x86_64/instructions/segmentation/struct.CS.html#method.set_reg
|
||||
[`load_tss`]: https://docs.rs/x86_64/0.14.2/x86_64/instructions/tables/fn.load_tss.html
|
||||
|
||||
Now that we have loaded a valid TSS and interrupt stack table, we can set the stack index for our double fault handler in the IDT:
|
||||
|
||||
@@ -47,7 +47,7 @@ pub extern "C" fn _start() -> ! {
|
||||
|
||||
// trigger a page fault
|
||||
unsafe {
|
||||
*(0xdeadbeef as *mut u64) = 42;
|
||||
*(0xdeadbeef as *mut u8) = 42;
|
||||
};
|
||||
|
||||
// as before
|
||||
|
||||
@@ -322,7 +322,7 @@ pub extern "C" fn _start() -> ! {
|
||||
blog_os::init();
|
||||
|
||||
// new
|
||||
let ptr = 0xdeadbeaf as *mut u32;
|
||||
let ptr = 0xdeadbeaf as *mut u8;
|
||||
unsafe { *ptr = 42; }
|
||||
|
||||
// as before
|
||||
@@ -347,7 +347,7 @@ pub extern "C" fn _start() -> ! {
|
||||
```rust
|
||||
// Note: The actual address might be different for you. Use the address that
|
||||
// your page fault handler reports.
|
||||
let ptr = 0x2031b2 as *mut u32;
|
||||
let ptr = 0x2031b2 as *mut u8;
|
||||
|
||||
// read from a code page
|
||||
unsafe { let x = *ptr; }
|
||||
|
||||
@@ -329,7 +329,7 @@ pub extern "C" fn _start() -> ! {
|
||||
blog_os::init();
|
||||
|
||||
// ここを追加
|
||||
let ptr = 0xdeadbeaf as *mut u32;
|
||||
let ptr = 0xdeadbeaf as *mut u8;
|
||||
unsafe { *ptr = 42; }
|
||||
|
||||
// ここはこれまでと同じ
|
||||
@@ -354,7 +354,7 @@ pub extern "C" fn _start() -> ! {
|
||||
```rust
|
||||
// 注意:実際のアドレスは個々人で違うかもしれません。
|
||||
// あなたのページフォルトハンドラが報告した値を使ってください。
|
||||
let ptr = 0x2031b2 as *mut u32;
|
||||
let ptr = 0x2031b2 as *mut u8;
|
||||
|
||||
// コードページから読み込む
|
||||
unsafe { let x = *ptr; }
|
||||
|
||||
@@ -316,7 +316,7 @@ pub extern "C" fn _start() -> ! {
|
||||
blog_os::init();
|
||||
|
||||
// new
|
||||
let ptr = 0xdeadbeaf as *mut u32;
|
||||
let ptr = 0xdeadbeaf as *mut u8;
|
||||
unsafe { *ptr = 42; }
|
||||
|
||||
// as before
|
||||
@@ -341,7 +341,7 @@ We see that the current instruction pointer is `0x2031b2`, so we know that this
|
||||
```rust
|
||||
// Note: The actual address might be different for you. Use the address that
|
||||
// your page fault handler reports.
|
||||
let ptr = 0x2031b2 as *mut u32;
|
||||
let ptr = 0x2031b2 as *mut u8;
|
||||
|
||||
// read from a code page
|
||||
unsafe { let x = *ptr; }
|
||||
|
||||
@@ -325,7 +325,7 @@ pub extern "C" fn _start() -> ! {
|
||||
blog_os::init();
|
||||
|
||||
// new
|
||||
let ptr = 0xdeadbeaf as *mut u32;
|
||||
let ptr = 0xdeadbeaf as *mut u8;
|
||||
unsafe { *ptr = 42; }
|
||||
|
||||
// as before
|
||||
@@ -350,7 +350,7 @@ pub extern "C" fn _start() -> ! {
|
||||
```rust
|
||||
// Note: The actual address might be different for you. Use the address that
|
||||
// your page fault handler reports.
|
||||
let ptr = 0x2031b2 as *mut u32;
|
||||
let ptr = 0x2031b2 as *mut u8;
|
||||
|
||||
// read from a code page
|
||||
unsafe { let x = *ptr; }
|
||||
|
||||
@@ -214,7 +214,7 @@ Since we are compiling for a custom target, we can't use the precompiled version
|
||||
|
||||
[unstable]
|
||||
build-std = ["core", "compiler_builtins", "alloc"]
|
||||
````
|
||||
```
|
||||
|
||||
Now the compiler will recompile and include the `alloc` crate in our kernel.
|
||||
|
||||
@@ -223,18 +223,12 @@ The reason that the `alloc` crate is disabled by default in `#[no_std]` crates i
|
||||
```
|
||||
error: no global memory allocator found but one is required; link to std or add
|
||||
#[global_allocator] to a static item that implements the GlobalAlloc trait.
|
||||
|
||||
error: `#[alloc_error_handler]` function required, but not found
|
||||
```
|
||||
|
||||
The first error occurs because the `alloc` crate requires a heap allocator, which is an object that provides the `allocate` and `deallocate` functions. In Rust, heap allocators are described by the [`GlobalAlloc`] trait, which is mentioned in the error message. To set the heap allocator for the crate, the `#[global_allocator]` attribute must be applied to a `static` variable that implements the `GlobalAlloc` trait.
|
||||
|
||||
The second error occurs because calls to `allocate` can fail, most commonly when there is no more memory available. Our program must be able to react to this case, which is what the `#[alloc_error_handler]` function is for.
|
||||
The error occurs because the `alloc` crate requires a heap allocator, which is an object that provides the `allocate` and `deallocate` functions. In Rust, heap allocators are described by the [`GlobalAlloc`] trait, which is mentioned in the error message. To set the heap allocator for the crate, the `#[global_allocator]` attribute must be applied to a `static` variable that implements the `GlobalAlloc` trait.
|
||||
|
||||
[`GlobalAlloc`]: https://doc.rust-lang.org/alloc/alloc/trait.GlobalAlloc.html
|
||||
|
||||
We will describe these traits and attributes in detail in the following sections.
|
||||
|
||||
### The `GlobalAlloc` Trait
|
||||
|
||||
The [`GlobalAlloc`] trait defines the functions that a heap allocator must provide. The trait is special because it is almost never used directly by the programmer. Instead, the compiler will automatically insert the appropriate calls to the trait methods when using the allocation and collection types of `alloc`.
|
||||
@@ -329,32 +323,7 @@ static ALLOCATOR: Dummy = Dummy;
|
||||
|
||||
Since the `Dummy` allocator is a [zero-sized type], we don't need to specify any fields in the initialization expression.
|
||||
|
||||
When we now try to compile it, the first error should be gone. Let's fix the remaining second error:
|
||||
|
||||
```
|
||||
error: `#[alloc_error_handler]` function required, but not found
|
||||
```
|
||||
|
||||
### The `#[alloc_error_handler]` Attribute
|
||||
|
||||
As we learned when discussing the `GlobalAlloc` trait, the `alloc` function can signal an allocation error by returning a null pointer. The question is: how should the Rust runtime react to such an allocation failure? This is where the `#[alloc_error_handler]` attribute comes in. It specifies a function that is called when an allocation error occurs, similar to how our panic handler is called when a panic occurs.
|
||||
|
||||
Let's add such a function to fix the compilation error:
|
||||
|
||||
```rust
|
||||
// in src/lib.rs
|
||||
|
||||
#![feature(alloc_error_handler)] // at the top of the file
|
||||
|
||||
#[alloc_error_handler]
|
||||
fn alloc_error_handler(layout: alloc::alloc::Layout) -> ! {
|
||||
panic!("allocation error: {:?}", layout)
|
||||
}
|
||||
```
|
||||
|
||||
The `alloc_error_handler` function is still unstable, so we need a feature gate to enable it. The function receives a single argument: the `Layout` instance that was passed to `alloc` when the allocation failure occurred. There's nothing we can do to resolve the failure, so we just panic with a message that contains the `Layout` instance.
|
||||
|
||||
With this function, the compilation errors should be fixed. Now we can use the allocation and collection types of `alloc`. For example, we can use a [`Box`] to allocate a value on the heap:
|
||||
With this static, the compilation errors should be fixed. Now we can use the allocation and collection types of `alloc`. For example, we can use a [`Box`] to allocate a value on the heap:
|
||||
|
||||
[`Box`]: https://doc.rust-lang.org/alloc/boxed/struct.Box.html
|
||||
|
||||
@@ -380,11 +349,11 @@ fn kernel_main(boot_info: &'static BootInfo) -> ! {
|
||||
|
||||
Note that we need to specify the `extern crate alloc` statement in our `main.rs` too. This is required because the `lib.rs` and `main.rs` parts are treated as separate crates. However, we don't need to create another `#[global_allocator]` static because the global allocator applies to all crates in the project. In fact, specifying an additional allocator in another crate would be an error.
|
||||
|
||||
When we run the above code, we see that our `alloc_error_handler` function is called:
|
||||
When we run the above code, we see that a panic occurs:
|
||||
|
||||

|
||||
|
||||
The error handler is called because the `Box::new` function implicitly calls the `alloc` function of the global allocator. Our dummy allocator always returns a null pointer, so every allocation fails. To fix this, we need to create an allocator that actually returns usable memory.
|
||||
The panic occurs because the `Box::new` function implicitly calls the `alloc` function of the global allocator. Our dummy allocator always returns a null pointer, so every allocation fails. To fix this, we need to create an allocator that actually returns usable memory.
|
||||
|
||||
## Creating a Kernel Heap
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ translation_contributors = ["asami-kawasaki", "Foo-x"]
|
||||
[コールスタック]: https://ja.wikipedia.org/wiki/%E3%82%B3%E3%83%BC%E3%83%AB%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF
|
||||
[コンテキスト・スイッチ (context switch)]: https://ja.wikipedia.org/wiki/%E3%82%B3%E3%83%B3%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%82%B9%E3%82%A4%E3%83%83%E3%83%81
|
||||
|
||||
コールスタックは非常に大きくなる可能性があるため、OSは通常、各タスクのスイッチでコールスタックの内容をバックアップする代わりに、各タスクに個別のコールスタックを設定します。このような独立したスタックを持つタスクは、[_thread of execution_](略して**スレッド**)と呼ばれます。タスクごとに独立したスタックを使用することで、コンテキスト・スイッチの際に保存する必要があるのはレジスタの内容だけになります(プログラム・カウンタとスタック・ポインタを含む)。この方法を取ることで、コンテキスト・スイッチの性能上のオーバーヘッドが最小限になります。これは、コンテキスト・スイッチが1秒間に100回も行われることがあるため、非常に重要なことです。
|
||||
コールスタックは非常に大きくなる可能性があるため、OSは通常、各タスクのスイッチでコールスタックの内容をバックアップする代わりに、各タスクに個別のコールスタックを設定します。このような独立したスタックを持つタスクは、[略して**スレッド**][_thread of execution_]と呼ばれます。タスクごとに独立したスタックを使用することで、コンテキスト・スイッチの際に保存する必要があるのはレジスタの内容だけになります(プログラム・カウンタとスタック・ポインタを含む)。この方法を取ることで、コンテキスト・スイッチの性能上のオーバーヘッドが最小限になります。これは、コンテキスト・スイッチが1秒間に100回も行われることがあるため、非常に重要なことです。
|
||||
|
||||
[_thread of execution_]: https://ja.wikipedia.org/wiki/%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89_(%E3%82%B3%E3%83%B3%E3%83%94%E3%83%A5%E3%83%BC%E3%82%BF)
|
||||
|
||||
|
||||
@@ -1104,30 +1104,6 @@ We see that our guess that the whole screen would turn gray was right:
|
||||
|
||||
We finally see some output from our little kernel!
|
||||
|
||||
You can try experimenting with the pixel bytes if you like, for example by increasing the pixel value on each loop iteration:
|
||||
|
||||
```rust ,hl_lines=5-9
|
||||
// in src/kernel/main.rs
|
||||
|
||||
fn kernel_main(boot_info: &'static mut BootInfo) -> ! {
|
||||
if let Some(framebuffer) = boot_info.framebuffer.as_mut() {
|
||||
let mut value = 0x90;
|
||||
for byte in framebuffer.buffer_mut() {
|
||||
*byte = value;
|
||||
value = value.wrapping_add(7);
|
||||
}
|
||||
}
|
||||
loop {}
|
||||
}
|
||||
```
|
||||
|
||||
We use the [`wrapping_add`] method here because Rust panics on implicit integer overflow (at least in debug mode).
|
||||
The result looks as follows:
|
||||
|
||||
[`wrapping_add`]: https://doc.rust-lang.org/std/primitive.u8.html#method.wrapping_add
|
||||
|
||||

|
||||
|
||||
### Booting on Real Hardware
|
||||
|
||||
To boot on real hardware, write either the `uefi.img` or the `bios.img` disk image to an USB thumb drive.
|
||||
@@ -1178,5 +1154,6 @@ We used the `bootloader` and `bootloader_api` crates to convert our kernel to a
|
||||
Through advanced cargo features such as [workspaces](#creating-a-workspace), [build scripts](#using-the-diskimagebuilder), and [artifact dependencies](#adding-an-artifact-dependency), we created a nice build system that can bring us directly from source code to a running QEMU instance using a single command.
|
||||
|
||||
We also started to look into frame buffers and [screen output](#screen-output).
|
||||
In the next post, we will continue with this and learn how to draw shapes and render text.
|
||||
In the [next post], we will continue with this and learn how to draw shapes and render text.
|
||||
|
||||
[next post]: @/edition-3/posts/03-screen-output/index.md
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 5.0 KiB |
@@ -12,14 +12,187 @@ icon = '''<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bi
|
||||
</svg>'''
|
||||
+++
|
||||
|
||||
Dolores qui incidunt sit fugiat amet consequatur. Qui ab vel et molestias ex nemo corporis consequatur. Quia consequuntur itaque sequi quia autem. Maxime vel quis maxime at. Tenetur eveniet velit dolor quidem temporibus tenetur.
|
||||
In this post we focus on the [framebuffer], a special memory region that controls the screen output.
|
||||
Using an [external crate], we will create functions for writing individual pixels, lines, and various shapes.
|
||||
In the the second half of this post, we will explore text rendering and learn how to print the obligatory _["Hello, World!"]_.
|
||||
|
||||
[framebuffer]: https://en.wikipedia.org/wiki/Framebuffer
|
||||
[external crate]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html
|
||||
["Hello, World!"]: https://en.wikipedia.org/wiki/Hello_world
|
||||
|
||||
<!-- more -->
|
||||
|
||||
Molestiae quidem ipsa nihil laboriosam sapiente laudantium quia. Praesentium et repudiandae minima voluptas et. Repellendus voluptatem distinctio enim et alias distinctio recusandae quos. Dolores ex eum culpa quo sunt sint voluptate voluptates. Facere unde sequi quo ea vel nihil. Rem deleniti repellat rem molestias
|
||||
This blog is openly developed on [GitHub].
|
||||
If you have any problems or questions, please open an issue there.
|
||||
You can also leave comments [at the bottom].
|
||||
The complete source code for this post can be found in the [`post-3.3`][post branch] branch.
|
||||
|
||||
[GitHub]: https://github.com/phil-opp/blog_os
|
||||
[at the bottom]: #comments
|
||||
<!-- fix for zola anchor checker (target is in template): <a id="comments"> -->
|
||||
[post branch]: https://github.com/phil-opp/blog_os/tree/post-3.3
|
||||
|
||||
<!-- toc -->
|
||||
Molestiae quidem ipsa nihil laboriosam sapiente laudantium quia. Praesentium et repudiandae minima voluptas et. Repellendus voluptatem distinctio enim et alias distinctio recusandae quos. Dolores ex eum culpa quo sunt sint voluptate voluptates. Facere unde sequi quo ea vel nihil. Rem deleniti repellat rem molestias
|
||||
|
||||
## Bitmap Images
|
||||
|
||||
In the [previous post], we learned how to make our minimal kernel bootable.
|
||||
Using the [`BootInfo`] provided by the bootloader, we were able to access a special memory region called the _[framebuffer]_, which controls the screen output.
|
||||
We wrote some example code to display a gray background:
|
||||
|
||||
[previous post]: @/edition-3/posts/02-booting/index.md
|
||||
[`BootInfo`]: https://docs.rs/bootloader_api/latest/bootloader_api/info/struct.BootInfo.html
|
||||
|
||||
```rust
|
||||
// in src/kernel/main.rs
|
||||
|
||||
fn kernel_main(boot_info: &'static mut BootInfo) -> ! {
|
||||
if let Some(framebuffer) = boot_info.framebuffer.as_mut() {
|
||||
for byte in framebuffer.buffer_mut() {
|
||||
*byte = 0x90;
|
||||
}
|
||||
}
|
||||
loop {}
|
||||
}
|
||||
```
|
||||
|
||||
The reason that the above code affects the screen output is because the graphics card interprets the framebuffer memory as a [bitmap] image.
|
||||
A bitmap describes an image through a predefined number of bytes per pixel.
|
||||
The pixels are laid out line by line, typically starting at the top.
|
||||
|
||||
[bitmap]: https://en.wikipedia.org/wiki/Bitmap
|
||||
[RGB]: https://en.wikipedia.org/wiki/Rgb
|
||||
|
||||
For example, the pixels of an image with width 10 and height 3 would be typically stored in this order:
|
||||
|
||||
<table><tbody>
|
||||
<tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td></tr>
|
||||
<tr><td>10</td><td>11</td><td>12</td><td>13</td><td>14</td><td>15</td><td>16</td><td>17</td><td>18</td><td>19</td></tr>
|
||||
<tr><td>20</td><td>21</td><td>22</td><td>23</td><td>24</td><td>25</td><td>26</td><td>27</td><td>28</td><td>29</td></tr>
|
||||
</tbody></table>
|
||||
|
||||
So top left pixel is stored at offset 0 in the bitmap array.
|
||||
The pixel on its right is at offset `pixel_size`.
|
||||
The first pixel of the next line starts at offset `line_length * pixel_size`.
|
||||
|
||||
### Padding
|
||||
|
||||
Depending on the hardware and GPU firmware, it is often more efficient
|
||||
|
||||
### Color formats
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
draw shapes and pixels directly onto the framebuffer. That's fine and all, but how is one able to go from that to displaying text on the screen? Understanding this requires taking a deep dive into how characters are rendered behind the scenes.
|
||||
|
||||
When a key is pressed on the keyboard, it sends a character code to the CPU. It's the CPU's job at that point to then interpret the character code and match it with an image to draw on the screen. The image is then sent to either the GPU or the framebuffer (the latter in our case) to be drawn on the screen, and the user sees that image as a letter, number, CJK character, emoji, or whatever else he or she wanted to have displayed by pressing that key.
|
||||
|
||||
In most other programming languages, implementing this behind the scenes can be a daunting task. With Rust, however, we have a toolset at our disposal that can pave the way for setting up proper framebuffer logging using very little code of our own.
|
||||
|
||||
# The `log` crate
|
||||
|
||||
Rust developers used to writing user-mode code will recognize the `log` crate from a mile away:
|
||||
|
||||
```toml
|
||||
# in Cargo.toml
|
||||
[dependencies]
|
||||
log = { version = "0.4.17", default-features = false }
|
||||
```
|
||||
|
||||
This crate has both a set of macros for logging either to the console or to a log file for later reading and a trait — also called `Log` with a capital L — that can be implemented to provide a backend, called a `Logger` in Rust parlance. Loggers are provided by a myriad of crates for a wide variety of use cases, and some of them even run on bare metal. We already used one such extant logger in the UEFI booting module when we used the logger provided by the `uefi` crate to print text to the UEFI console. That won't work in the kernel, however, because UEFI boot services need to be active in order for the UEFI logger to be usable.
|
||||
|
||||
If you were paying attention to the post before that one, however, you may have noticed that the bootloader is itself able to log directly to the framebuffer as it did when we booted the barebones kernel for the first time, and unlike the UEFI console logger, this logger is usable long after UEFI boot services are exited. It's this logger, therefore, that provides the easiest means of implementation on our end.
|
||||
|
||||
## `bootloader-x86_64-common`
|
||||
|
||||
In version 0.11.x of the bootloader crate, each component is separate, unlike in 0.10.x where the bootloader was a huge monolith. This is fantastic as it means that a lot of the APIs that the bootloader uses behind the scenes are also free for kernels to use, including, of course, the logger. The set of APIs that the logger belongs to are in a crate called `bootloader-x86_64-common` which also contains some other useful abstractions related to things like memory management that will come in handy later:
|
||||
|
||||
```toml
|
||||
# in Cargo.toml
|
||||
[dependencies]
|
||||
bootloader-x86_64-common = "0.11.3"
|
||||
```
|
||||
|
||||
For now, however, only the logger will be used. If you are curious as to how this logger is written behind the scenes, however, don't worry; a sub-module of this chapter will include a tutorial on how to write a custom logger from scratch.
|
||||
|
||||
# Putting it all together
|
||||
|
||||
Before we use the bootloader's logger, we first need to initialize it. This requires creating a static instance, since it needs to live for as long as the kernel lives — which would mean for as long as the computer is powered on. Unfortunately, this is easier said than done, as Rust statics can be rather finicky — understandably so for security reasons. Luckily, there's a crate for this too.
|
||||
|
||||
## The `conquer_once` crate
|
||||
|
||||
Those used to using the standard library know that it provides a `OnceCell` which is exactly what it sounds like: you write to it only once, and then after that it's just there to use whenever. We're in a kernel and don't have access to the standard library, however, so is there a crate on crates.io that provides a replacement? Ah, yes there is:
|
||||
|
||||
```toml
|
||||
# in Cargo.toml
|
||||
[dependencies]
|
||||
conquer-once = { version = "0.4.0", default-features = false }
|
||||
```
|
||||
|
||||
Note that we need to add `default-features = false` to our `conquer-once` dependency —that's because the [`conquer-once` crate](https://crates.io/crates/conquer-once) tries to pull in the standard library by default, which in the kernel will result in compilation errors.
|
||||
|
||||
Now that we've added our two dependencies, it's time to use them:
|
||||
|
||||
```rust
|
||||
// in src/main.rs
|
||||
use conquer_once::spin::OnceCell;
|
||||
use bootloader_x86_64_common::logger::LockedLogger;
|
||||
// ...
|
||||
pub(crate) static LOGGER: OnceCell<LockedLogger> = OnceCell::uninit();
|
||||
```
|
||||
|
||||
By setting the logger up as a static `OnceCell` it becomes much easier to initialize. We use `pub(crate)` to ensure that the kernel can see it but nothing else can.
|
||||
|
||||
After this, it's time to actually initialize it. To do that, we use a function:
|
||||
|
||||
```rust
|
||||
// in src/main.rs
|
||||
use bootloader_api::info::FrameBufferInfo;
|
||||
// ...
|
||||
pub(crate) fn init_logger(buffer: &'static mut [u8], info: FrameBufferInfo) {
|
||||
let logger = LOGGER.get_or_init(move || LockedLogger::new(buffer, info, true, false));
|
||||
log::set_logger(logger).expect("Logger already set");
|
||||
log::set_max_level(log::LevelFilter::Trace);
|
||||
log::info!("Hello, Kernel Mode!");
|
||||
}
|
||||
```
|
||||
|
||||
This function takes two parameters: a byte slice representing a raw framebuffer and a `FrameBufferInfo` structure containing information about the first parameter. Getting those parameters, however, requires jumping through some hoops to satisfy the borrow checker:
|
||||
|
||||
```rust
|
||||
// in src/main.rs
|
||||
fn kernel_main(boot_info: &'static mut bootloader_api::BootInfo) -> ! {
|
||||
// ...
|
||||
// free the doubly wrapped framebuffer from the boot info struct
|
||||
let frame_buffer_optional = &mut boot_info.framebuffer;
|
||||
|
||||
// free the wrapped framebuffer from the FFI-safe abstraction provided by bootloader_api
|
||||
let frame_buffer_option = frame_buffer_optional.as_mut();
|
||||
|
||||
// unwrap the framebuffer
|
||||
let frame_buffer_struct = frame_buffer_option.unwrap();
|
||||
|
||||
// extract the framebuffer info and, to satisfy the borrow checker, clone it
|
||||
let frame_buffer_info = frame_buffer.info().clone();
|
||||
|
||||
// get the framebuffer's mutable raw byte slice
|
||||
let raw_frame_buffer = frame_buffer_struct.buffer_mut();
|
||||
|
||||
// finally, initialize the logger using the last two variables
|
||||
init_logger(raw_frame_buffer, frame_buffer_info);
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Any one of these steps, if skipped, will cause the borrow checker to throw a hissy fit due to the use of the `move ||` closure by the initializer function. With this, however, you're done, and you'll know the logger has been initialized when you see "Hello, Kernel Mode!" printed on the screen.
|
||||
|
||||
<!-- more -->
|
||||
<!-- toc -->
|
||||
|
||||
<!-- TODO: update relative link in 02-booting/uefi/index.md when this post is finished -->
|
||||
|
||||
@@ -10,9 +10,11 @@
|
||||
{% macro giscus(search_term, lang) %}
|
||||
{% if lang != "en" %}
|
||||
{% set category = "Post Comments (translated)" %}
|
||||
{% set category_id = "DIC_kwDOAlvePc4CPg4c" %}
|
||||
{% set category_path = "post-comments-translated" %}
|
||||
{% else %}
|
||||
{% set category = "Post Comments" %}
|
||||
{% set category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMzMDE4OTg1" %}
|
||||
{% set category_path = "post-comments" %}
|
||||
{% endif %}
|
||||
|
||||
@@ -33,7 +35,7 @@
|
||||
data-repo="phil-opp/blog_os"
|
||||
data-repo-id="MDEwOlJlcG9zaXRvcnkzOTU3NTEwMQ=="
|
||||
data-category="{{ category }}"
|
||||
data-category-id="MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMzMDE4OTg1"
|
||||
data-category-id="{{ category_id }}"
|
||||
{% if search_term is number %}
|
||||
data-mapping="number"
|
||||
{% else %}
|
||||
|
||||
Reference in New Issue
Block a user