神泱 发表于 2025-6-8 12:45:50

[rCore学习笔记 019]在main中测试本章实现

写在前面

本随笔是非常菜的菜鸡写的。如有问题请及时提出。
可以联系:1160712160@qq.com
GitHhub:https://github.com/WindDevil (目前啥也没有
批处理操作系统的启动和运行流程

要想把本章实现的那些模块全部都串联在一起以实现运行一个批处理操作系统,回顾本章内容,思考批处理操作系统的运行流程.
可以看到本章完成的内容大概如图所示:

可以看到在内核层,最重要的就是实现了batch来加载程序和切换程序,以及trap用来处理用户层的请求.
因此,我们只需要在main.rs中添加这两个模块的初始化即可.
编写main.rs

主要是三部分:

[*]引入上述编写模块
[*]嵌入link_app.S
[*]引入batch,trap,syscall

[*]初始化模块
[*]开始运行用户态APP
需要添加的内容就这么多:
pub mod batch;
pub mod syscall;
pub mod trap;

global_asm!(include_str!("link_app.S"));
pub fn rust_main() -> ! {
        trap::init();
    batch::init();
    batch::run_next_app();
}最终实现的main.rs:
//! The main module and entrypoint
//!
//! Various facilities of the kernels are implemented as submodules. The most
//! important ones are:
//!
//! - [`trap`]: Handles all cases of switching from userspace to the kernel
//! - [`syscall`]: System call handling and implementation
//!
//! The operating system also starts in this module. Kernel code starts
//! executing from `entry.asm`, after which [`rust_main()`] is called to
//! initialize various pieces of functionality. (See its source code for
//! details.)
//!
//! We then call [`batch::run_next_app()`] and for the first time go to
//! userspace.

#!
#!
#!
#!
#!

use core::arch::global_asm;

use log::*;
#
mod console;
pub mod batch;
mod lang_items;
mod logging;
mod sbi;
mod sync;
pub mod syscall;
pub mod trap;

global_asm!(include_str!("entry.asm"));
global_asm!(include_str!("link_app.S"));

/// clear BSS segment
fn clear_bss() {
    extern "C" {
      fn sbss();
      fn ebss();
    }
    unsafe {
      core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize)
            .fill(0);
    }
}

/// the rust entry-point of os
#
pub fn rust_main() -> ! {
    extern "C" {
      fn stext(); // begin addr of text segment
      fn etext(); // end addr of text segment
      fn srodata(); // start addr of Read-Only data segment
      fn erodata(); // end addr of Read-Only data ssegment
      fn sdata(); // start addr of data segment
      fn edata(); // end addr of data segment
      fn sbss(); // start addr of BSS segment
      fn ebss(); // end addr of BSS segment
      fn boot_stack_lower_bound(); // stack lower bound
      fn boot_stack_top(); // stack top
    }
    clear_bss();
    logging::init();
    println!(" Hello, world!");
    trace!(
      " .text [{:#x}, {:#x})",
      stext as usize,
      etext as usize
    );
    debug!(
      " .rodata [{:#x}, {:#x})",
      srodata as usize, erodata as usize
    );
    info!(
      " .data [{:#x}, {:#x})",
      sdata as usize, edata as usize
    );
    warn!(
      " boot_stack top=bottom={:#x}, lower_bound={:#x}",
      boot_stack_top as usize, boot_stack_lower_bound as usize
    );
    error!(" .bss [{:#x}, {:#x})", sbss as usize, ebss as usize);
    trap::init();
    batch::init();
    batch::run_next_app();
}编译运行

使用第一章就编写好的Makefile文件实现一键编译运行:
cd os
make run第一次编译运行:
error: expected expression, found keyword `extern`
--> src/batch.rs:94:13
   |
94 |             extern "C"
   |             ^^^^^^ expected expression

error: cannot find macro `asm` in this scope
--> src/batch.rs:84:9
   |
84 |         asm!("fence.i")
   |         ^^^
   |
help: consider importing this macro
   |
1+ use core::arch::asm;
   |

error: cannot find macro `global_asm` in this scope
--> src/trap/mod.rs:3:1
|
3 | global_asm!(include_str!("trap.S"));
| ^^^^^^^^^^
|
help: consider importing one of these items
|
3 + use core::arch::global_asm;
|
3 + use crate::global_asm;
|

error: cannot find type `TrapContext` in this scope
--> src/batch.rs:34:36
   |
34 |   pub fn push_context(&self, cx: TrapContext) -> &'static mut TrapContext {
   |                                    ^^^^^^^^^^^ not found in this scope

error: cannot find type `TrapContext` in this scope
--> src/batch.rs:34:65
   |
34 |   pub fn push_context(&self, cx: TrapContext) -> &'static mut TrapContext {
   |                                                               ^^^^^^^^^^^ not found in this scope

error: cannot find type `TrapContext` in this scope
--> src/batch.rs:35:60
   |
35 |         let cx_ptr = (self.get_sp() - core::mem::size_of::<TrapContext>()) as *mut TrapContext;
   |                                                            ^^^^^^^^^^^ not found in this scope
   |
help: you might be missing a type parameter
   |
30 | impl<TrapContext> KernelStack {
   |   +++++++++++++

error: cannot find type `TrapContext` in this scope
--> src/batch.rs:35:84
   |
35 |         let cx_ptr = (self.get_sp() - core::mem::size_of::<TrapContext>()) as *mut TrapContext;
   |                                                                                    ^^^^^^^^^^^ not found in this scope

error: cannot find type `RefCell` in this scope
--> src/sync/up.rs:5:12
|
5 |   inner: RefCell<T>,
|            ^^^^^^^ not found in this scope
|
help: consider importing this struct
|
3 + use core::cell::RefCell;
|

error: failed to resolve: use of undeclared type `RefCell`
--> src/sync/up.rs:14:23
   |
14 |         Self { inner: RefCell::new(value) }
   |                     ^^^^^^^ use of undeclared type `RefCell`
   |
help: consider importing this struct
   |
3+ use core::cell::RefCell;
   |

error: cannot find type `RefMut` in this scope
--> src/sync/up.rs:17:39
   |
17 |   pub fn exclusive_access(&self) -> RefMut<'_, T> {
   |                                       ^^^^^^ not found in this scope
   |
help: consider importing this struct
   |
3+ use core::cell::RefMut;
   |

error: cannot find type `TrapContext` in this scope
--> src/trap/mod.rs:13:30
   |
13 | pub fn trap_handler(cx: &mut TrapContext) -> &mut TrapContext {
   |                              ^^^^^^^^^^^ not found in this scope

error: cannot find type `TrapContext` in this scope
--> src/trap/mod.rs:13:51
   |
13 | pub fn trap_handler(cx: &mut TrapContext) -> &mut TrapContext {
   |                                                   ^^^^^^^^^^^ not found in this scope

error: cannot find function `syscall` in this scope
--> src/trap/mod.rs:19:24
   |
19 |             cx.x = syscall(cx.x, , cx.x, cx.x]) as usize;
   |                        ^^^^^^^ not found in this scope
   |
help: consider importing this function
   |
3+ use crate::syscall::syscall;
   |

error: cannot find function `run_next_app` in this scope
--> src/trap/mod.rs:24:13
   |
24 |             run_next_app();
   |             ^^^^^^^^^^^^ not found in this scope
   |
help: consider importing this function
   |
3+ use crate::batch::run_next_app;
   |

error: cannot find function `run_next_app` in this scope
--> src/trap/mod.rs:28:13
   |
28 |             run_next_app();
   |             ^^^^^^^^^^^^ not found in this scope
   |
help: consider importing this function
   |
3+ use crate::batch::run_next_app;
   |

error: cannot find function `init` in module `batch`
--> src/main.rs:88:12
   |
88 |   batch::init();
   |            ^^^^ not found in `batch`
   |
help: consider importing one of these items
   |
23 + use crate::logging::init;
   |
23 + use crate::trap::init;
   |
help: if you import `init`, refer to it directly
   |
88 -   batch::init();
88 +   init();
   |

error: mismatched types
   --> src/batch.rs:80:41
    |
80|         core::slice::from_raw_parts_mut(APP_BASE_ADDRESS as *const u8, APP_SIZE_LIMIT).fill(0);
    |         ------------------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ in mutability
    |         |
    |         arguments to this function are incorrect
    |
    = note: expected raw pointer `*mut _`
               found raw pointer `*const u8`
note: function defined here
   --> /home/winddevil/.rustup/toolchains/nightly-2024-05-01-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/slice/raw.rs:147:21
    |
147 | pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut {
    |                     ^^^^^^^^^^^^^^^^^^

error: the method `get` exists for struct `Lazy<UPSafeCell>`, but its trait bounds were not satisfied
   --> src/batch.rs:88:1
    |
88| / lazy_static!
89| | {
90| |   static ref APP_MANAGER: UPSafeCell = unsafe
91| |   {
...   |
110 | |   };
111 | | }
    | |_^ method cannot be called on `Lazy<UPSafeCell>` due to unsatisfied trait bounds
    |
   ::: src/sync/up.rs:3:1
    |
3   |   pub struct UPSafeCell<T> {
    |   ------------------------ doesn't satisfy `UPSafeCell: Sized`
    |
    = note: the following trait bounds were not satisfied:
            `{type error}: Sized`
            which is required by `UPSafeCell: Sized`
    = note: this error originates in the macro `__lazy_static_internal` which comes from the expansion of the macro `lazy_static` (in Nightly builds, run with -Z macro-backtrace for more info)

error: failed to resolve: use of undeclared type `TrapContext`
   --> src/batch.rs:126:13
    |
126 |             TrapContext::app_init_context(APP_BASE_ADDRESS, USER_STACK.get_sp())
    |             ^^^^^^^^^^^ use of undeclared type `TrapContext`

error: cannot find function `sys_write` in this scope
--> src/syscall/mod.rs:5:26
|
5 |         SYSCALL_WRITE => sys_write(args, args as *const u8, args),
|                        ^^^^^^^^^ not found in this scope

error: cannot find function `sys_exit` in this scope
--> src/syscall/mod.rs:6:25
|
6 |         SYSCALL_EXIT => sys_exit(args as i32),
|                         ^^^^^^^^ not found in this scope

error: failed to resolve: use of undeclared crate or module `stvec`
--> src/trap/mod.rs:8:9
|
8 |         stvec::write(__alltraps as usize, TrapMode::Direct);
|         ^^^^^ use of undeclared crate or module `stvec`

error: failed to resolve: use of undeclared type `TrapMode`
--> src/trap/mod.rs:8:43
|
8 |         stvec::write(__alltraps as usize, TrapMode::Direct);
|                                           ^^^^^^^^ use of undeclared type `TrapMode`

error: failed to resolve: use of undeclared crate or module `scause`
--> src/trap/mod.rs:14:18
   |
14 |   let scause = scause::read();
   |                  ^^^^^^ use of undeclared crate or module `scause`

error: failed to resolve: use of undeclared crate or module `stval`
--> src/trap/mod.rs:15:17
   |
15 |   let stval = stval::read();
   |               ^^^^^ use of undeclared crate or module `stval`

error: unused variable: `metadata`
--> src/logging.rs:9:23
   |
9|   fn enabled(&self, metadata: &Metadata) -> bool
   |                     ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_metadata`
   |
note: the lint level is defined here
--> src/main.rs:18:9
   |
18 | #!
   |         ^^^^^^^^
   = note: `#` implied by `#`

error: failed to resolve: use of undeclared type `Exception`
--> src/trap/mod.rs:26:25
   |
26 |         Trap::Exception(Exception::IllegalInstruction) => {
   |                         ^^^^^^^^^ use of undeclared type `Exception`

error: failed to resolve: use of undeclared type `Trap`
--> src/trap/mod.rs:26:9
   |
26 |         Trap::Exception(Exception::IllegalInstruction) => {
   |         ^^^^ use of undeclared type `Trap`

error: failed to resolve: use of undeclared type `Exception`
--> src/trap/mod.rs:22:25
   |
22 |         Trap::Exception(Exception::StorePageFault) => {
   |                         ^^^^^^^^^ use of undeclared type `Exception`

error: failed to resolve: use of undeclared type `Trap`
--> src/trap/mod.rs:22:9
   |
22 |         Trap::Exception(Exception::StorePageFault) => {
   |         ^^^^ use of undeclared type `Trap`

error: failed to resolve: use of undeclared type `Exception`
--> src/trap/mod.rs:21:25
   |
21 |         Trap::Exception(Exception::StoreFault) |
   |                         ^^^^^^^^^ use of undeclared type `Exception`

error: failed to resolve: use of undeclared type `Trap`
--> src/trap/mod.rs:17:9
   |
17 |         Trap::Exception(Exception::UserEnvCall) => {
   |         ^^^^ use of undeclared type `Trap`

error: failed to resolve: use of undeclared type `Exception`
--> src/trap/mod.rs:17:25
   |
17 |         Trap::Exception(Exception::UserEnvCall) => {
   |                         ^^^^^^^^^ use of undeclared type `Exception`

error: failed to resolve: use of undeclared type `Trap`
--> src/trap/mod.rs:21:9
   |
21 |         Trap::Exception(Exception::StoreFault) |
   |         ^^^^ use of undeclared type `Trap`

Some errors have detailed explanations: E0308, E0412, E0425, E0433, E0599.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `os` (bin "os") due to 34 previous errors
make: *** Error 101看到大段的报错不要着急,首先先看容易解决,能够解决的.
首先是在batch.rs里加入use core::arch::asm;:
error: cannot find macro `asm` in this scope
--> src/batch.rs:84:9
   |
84 |         asm!("fence.i")
   |         ^^^
   |
help: consider importing this macro
   |
1+ use core::arch::asm;
   |同样地,在src/trap/mod.rs里边加入use core::arch::global_asm;:
error: cannot find macro `global_asm` in this scope
--> src/trap/mod.rs:3:1
|
3 | global_asm!(include_str!("trap.S"));
| ^^^^^^^^^^
|
help: consider importing one of these items
|
3 + use core::arch::global_asm;
|
3 + use crate::global_asm;
|在batch.rs加入use crate::trap::TrapContext;,这时候我们发现实际上在src/trap/mod.rs里也没有声明TrapContext则在里边声明mod context;:
error: cannot find type `TrapContext` in this scope
--> src/batch.rs:34:36
   |
34 |   pub fn push_context(&self, cx: TrapContext) -> &'static mut TrapContext {
   |                                    ^^^^^^^^^^^ not found in this scope后续有很多找不到TrapContext的问题,可能都会解决.
在src/sync/up.rs里加入use core::cell::{RefCell, RefMut};:
error: cannot find type `RefCell` in this scope
--> src/sync/up.rs:5:12
|
5 |   inner: RefCell<T>,
|            ^^^^^^^ not found in this scope
|
help: consider importing this struct
|
3 + use core::cell::RefCell;
|
error: cannot find type `RefMut` in this scope
--> src/sync/up.rs:17:39
   |
17 |   pub fn exclusive_access(&self) -> RefMut<'_, T> {
   |                                       ^^^^^^ not found in this scope
   |
help: consider importing this struct
   |
3+ use core::cell::RefMut;
   |每次运行之后,

[*]因为触发了异常而退出
[*]直接由exit(main());退出
都会陷入trap,然后在trap_handler里处理,只要不出现没有预期到的Expectation都会调用run_next_app,因此所有的app按顺序运行.
最后完美结束了这一章,我真是一条懒狗,怎么什么坑都要踩一遍.

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: [rCore学习笔记 019]在main中测试本章实现