初始化ch3-coop

ch3-coop
zhangxinyu 2 years ago
parent c96b6233bf
commit 445a87d42b

@ -0,0 +1,14 @@
[package]
name = "os"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
# 设置release模式下保存调试信息
[profile.release]
debug=true
[dependencies]
riscv = { git = "https://github.com/rcore-os/riscv", features = ["inline-asm"] }
lazy_static = { version = "1.4.0", features = ["spin_no_std"] }

@ -0,0 +1,51 @@
TARGET := riscv64gc-unknown-none-elf
KERNEL_ENTRY := 0x80200000
MODE := release
KERNEL_ELF := target/$(TARGET)/$(MODE)/os
KERNEL_BIN := $(KERNEL_ELF).bin
SYMBOL_MAP := target/system.map
QEMU_CMD_PATH := /Users/zhangxinyu/Downloads/qemu-7.0.0/build/qemu-system-riscv64
QEMU_PID = $(shell ps aux | grep "[q]emu-system' | awk '{print $$2}")
OBJDUMP := rust-objdump --arch-name=riscv64
OBJCOPY := rust-objcopy --binary-architecture=riscv64
RUST_FLAGS := -Clink-arg=-Tsrc/linker.ld # 使用我们自己的链接脚本
RUST_FLAGS += -Cforce-frame-pointers=yes # 强制编译器生成帧指针
RUST_FLAGS:=$(strip ${RUST_FLAGS})
# 编译elf文件
build_elf: clean
CARGO_BUILD_RUSTFLAGS="$(RUST_FLAGS)" \
cargo build --$(MODE) --target=$(TARGET)
# 导出一个符号表, 供我们查看
$(SYMBOL_MAP):build_elf
nm $(KERNEL_ELF) | sort > $(SYMBOL_MAP)
# 丢弃内核可执行elf文件中的元数据得到内核镜像
$(KERNEL_BIN): build_elf
@$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@
debug:build_elf $(KERNEL_BIN) $(SYMBOL_MAP)
$(QEMU_CMD_PATH) \
-machine virt \
-display none \
-daemonize \
-bios ../../bootloader/rustsbi-qemu.bin \
-device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY) \
-s -S
run:build_elf $(KERNEL_BIN) $(SYMBOL_MAP) kill
$(QEMU_CMD_PATH) \
-machine virt \
-nographic \
-bios ../../bootloader/rustsbi-qemu.bin \
-device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY)
clean:
rm -rf ./target* && rm -rf ./src/link_app.S
kill:
-kill -9 $(QEMU_PID)

@ -0,0 +1,69 @@
use std::fs::{read_dir, File};
use std::io::{Result, Write};
fn main() {
println!("cargo:rerun-if-changed=../user/src/");
println!("cargo:rerun-if-changed={}", TARGET_PATH);
insert_app_data().unwrap();
}
static TARGET_PATH: &str = "../user/target/riscv64gc-unknown-none-elf/release/";
fn insert_app_data() -> Result<()> {
let mut f = File::create("src/link_app.S").unwrap();
let mut apps: Vec<_> = read_dir("../user/src/bin")
.unwrap()
.into_iter()
.map(|dir_entry| {
let mut name_with_ext = dir_entry.unwrap().file_name().into_string().unwrap();
name_with_ext.drain(name_with_ext.find('.').unwrap()..name_with_ext.len());
name_with_ext
})
.collect();
apps.sort();
///
/// .align 3 表示接下来的数据或代码 使用2^3 8字节对齐
/// .section .data 下面属于data段
/// .global _num_app 定义一个全局符号 _num_app
/// _num_app: _num_app的位置的数据
/// .quad 5 用来当做matedata 8字节的整数 表示有5个元素
/// .quad app_0_start 依次存储每个app的开始的位置
/// .quad app_1_start
/// .quad app_2_start
/// .quad app_3_start
/// .quad app_4_start
/// .quad app_4_end
writeln!(
f,
r#"
.align 3
.section .data
.global _num_app
_num_app:
.quad {}"#,
apps.len()
)?;
for i in 0..apps.len() {
writeln!(f, r#" .quad app_{}_start"#, i)?;
}
writeln!(f, r#" .quad app_{}_end"#, apps.len() - 1)?;
for (idx, app) in apps.iter().enumerate() {
println!("app_{}: {}", idx, app);
writeln!(
f,
r#"
.section .data
.global app_{0}_start
.global app_{0}_end
app_{0}_start:
.incbin "{2}{1}.bin"
app_{0}_end:"#,
idx, app, TARGET_PATH
)?;
}
Ok(())
}

@ -0,0 +1,136 @@
use core::arch::asm;
use lazy_static::*;
use riscv::register::mcause::Trap;
use crate::println;
use crate::sync::UPSafeCell;
use crate::trap::TrapContext;
const USER_STACK_SIZE: usize = 4096 * 2; // 栈大小为8kb
const KERNEL_STACK_SIZE: usize = 4096 * 2;
const MAX_APP_NUM: usize = 16; // 系统最大支持的运行程序数量
const APP_BASE_ADDRESS: usize = 0x80400000; // 载入的app的起始的地址
const APP_SIZE_LIMIT: usize = 0x20000; // app的最大的二进制文件能够使用的大小
// 在此之后 应用使用UserStack, 而内核使用KernelStack, entry.asm设置的64k启动栈不再被使用(首次运行run_next_app时被接管了 mv sp, a0)
// KERNEL_STACK 保存的是 Trap Context
static KERNEL_STACK: [u8; KERNEL_STACK_SIZE] = [0; KERNEL_STACK_SIZE];
static USER_STACK: [u8; USER_STACK_SIZE] = [0; USER_STACK_SIZE];
lazy_static! {
static ref APP_MANAGER: UPSafeCell<AppManager> = unsafe {
UPSafeCell::new({
extern "C" {
fn _num_app();
}
let num_app_ptr = _num_app as usize as *const usize;
let num_app = num_app_ptr.read_volatile(); // 用户app的总数量
let mut app_start_lis: [usize; MAX_APP_NUM + 1] = [0; MAX_APP_NUM + 1]; // 创建一个数组, 用来保存每个app的起始位置
// 得到每个app的起始地址
let mut app_start_lis: [usize; MAX_APP_NUM + 1] = [0; MAX_APP_NUM + 1];
let app_start_raw: &[usize] =
core::slice::from_raw_parts(num_app_ptr.add(1), num_app + 1);
app_start_lis[..=num_app].copy_from_slice(app_start_raw);
AppManager{
num_app,
current_app: 0,
app_start_lis
}
})
};
}
// 由build.rs 生成的link_app.S, 根据里面的信息生成的结构体
struct AppManager {
num_app: usize, // 用户app数量
current_app: usize, // 当前需要执行的第几个app
app_start_lis: [usize; MAX_APP_NUM + 1], // 保存了每个app的起始位置, 后面会跳到这里, +1 是因为end的位置也占了一个usize, 需要知道end的位置
}
impl AppManager{
fn show_app_info(&self){
println!("[kernel] num_app = {}", self.num_app);
for i in 0..self.num_app {
println!(
"[kernel] app_{} ({:#x}, {:#x})",
i,
self.app_start_lis[i],
self.app_start_lis[i + 1]
);
}
}
// 把app_idx位置的app 加载到指定的内存APP_BASE_ADDRESS位置
unsafe fn load_app(&self, app_idx: usize){
if app_idx >= self.num_app{
panic!("All applications completed!")
}
// 清空app执行区域的内存
core::slice::from_raw_parts_mut(APP_BASE_ADDRESS as *mut u8, APP_SIZE_LIMIT).fill(0);
// 得到指定app_idx位置的数据(下一个位置的开始 - 需要运行app的开始 = 需要运行app的内存大小
let app_src = core::slice::from_raw_parts(self.app_start_lis[app_idx] as *const u8,
self.app_start_lis[app_idx + 1] - self.app_start_lis[app_idx]);
// 把app的代码 copy到指定的运行的区域
let app_len = app_src.len();
if app_len > APP_SIZE_LIMIT {
panic!("app memory overrun!")
}
core::slice::from_raw_parts_mut(APP_BASE_ADDRESS as *mut u8, app_len)
.copy_from_slice(app_src);
// 刷新cache
asm!("fence.i");
}
}
pub fn init() {
APP_MANAGER.exclusive_access().show_app_info();
}
pub fn run_next_app() -> ! {
// 运行一个新的app
// 把需要执行的指定app, 加载到执行位置APP_BASE_ADDRESS
// app_manager 需要drop 或者在一个作用域中, 因为这个函数不会返回, 后面直接进入用户态了
{
let mut app_manager = APP_MANAGER.exclusive_access();
unsafe{
app_manager.load_app(app_manager.current_app);
println!("------------- run_next_app load app {}", app_manager.current_app);
}
app_manager.current_app += 1;
}
extern "C" {
fn __restore(trap_context_ptr: usize);
}
unsafe {
// 得到用户栈的栈顶
let user_stack_top = USER_STACK.as_ptr() as usize + USER_STACK_SIZE;
// 得到用户trap的上下文以及寄存器状态
let user_trap_context = TrapContext::app_init_context(APP_BASE_ADDRESS, user_stack_top);
// 把用户trap copy到内核栈
let kernel_stack_top = KERNEL_STACK.as_ptr() as usize + KERNEL_STACK_SIZE; // 现在栈顶和栈底都在一个内存位置
// 为trap context 分配栈空间
let kernel_trap_context_ptr = (kernel_stack_top - core::mem::size_of::<TrapContext>()) as * mut TrapContext;
unsafe {
// 把user_trap_context copy到内核栈顶
*kernel_trap_context_ptr = user_trap_context;
// 返回现在的内核栈顶
__restore(kernel_trap_context_ptr as *const _ as usize);
}
}
panic!("Unreachable in batch::run_current_app!");
}

@ -0,0 +1,15 @@
.section .text.entry
.globl _start // _start
_start:
la sp, boot_stack_top_bound
call rust_main
// .bss.stack link .bss
.section .bss.stack
.globl boot_stack_lower_bound //
.globl boot_stack_top_bound //
boot_stack_lower_bound:
.space 4096 * 16
boot_stack_top_bound:

@ -0,0 +1,2 @@
pub mod panic;
pub mod console;

@ -0,0 +1,33 @@
use crate::sbi::console_put_char;
use core::fmt::{self, Write};
struct Stdout;
impl Write for Stdout{
fn write_str(&mut self, s: &str) -> fmt::Result {
for c in s.chars() {
console_put_char(c as usize);
}
Ok(())
}
}
// 用函数包装一下, 表示传进来的参数满足Arguments trait, 然后供宏调用
pub fn print(args: fmt::Arguments) {
Stdout.write_fmt(args).unwrap();
}
#[macro_export] // 导入这个文件即可使用这些宏
macro_rules! print {
($fmt: literal $(, $($arg: tt)+)?) => {
$crate::console::print(format_args!($fmt $(, $($arg)+)?));
}
}
#[macro_export]
macro_rules! println {
($fmt: literal $(, $($arg: tt)+)?) => {
$crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?));
}
}

@ -0,0 +1,18 @@
use core::panic::PanicInfo;
use crate::println;
use crate::sbi::shutdown;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
if let Some(location) = info.location() {
println!(
"Panicked at {}:{} {}",
location.file(),
location.line(),
info.message().unwrap()
);
} else {
println!("Panicked: {}", info.message().unwrap());
}
shutdown();
}

@ -0,0 +1,47 @@
.align 3
.section .data
.global _num_app
_num_app:
.quad 5
.quad app_0_start
.quad app_1_start
.quad app_2_start
.quad app_3_start
.quad app_4_start
.quad app_4_end
.section .data
.global app_0_start
.global app_0_end
app_0_start:
.incbin "../user/target/riscv64gc-unknown-none-elf/release/00hello_world.bin"
app_0_end:
.section .data
.global app_1_start
.global app_1_end
app_1_start:
.incbin "../user/target/riscv64gc-unknown-none-elf/release/01store_fault.bin"
app_1_end:
.section .data
.global app_2_start
.global app_2_end
app_2_start:
.incbin "../user/target/riscv64gc-unknown-none-elf/release/02power.bin"
app_2_end:
.section .data
.global app_3_start
.global app_3_end
app_3_start:
.incbin "../user/target/riscv64gc-unknown-none-elf/release/03priv_inst.bin"
app_3_end:
.section .data
.global app_4_start
.global app_4_end
app_4_start:
.incbin "../user/target/riscv64gc-unknown-none-elf/release/04priv_csr.bin"
app_4_end:

@ -0,0 +1,48 @@
OUTPUT_ARCH(riscv) /* 目标平台 */
ENTRY(_start) /* 设置程序入口点为entry.asm中定义的全局符号 */
BASE_ADDRESS = 0x80200000; /* 一个常量, 我们的kernel将来加载到这个物理地址 */
SECTIONS
{
. = BASE_ADDRESS; /* 我们对 . 进行赋值, 调整接下来的段的开始位置放在我们定义的常量出 */
/* skernel = .;*/
stext = .; /* .text段的开始位置 */
.text : { /* 表示生成一个为 .text的段, 花括号内按照防止顺序表示将输入文件中的哪些段放在 当前.text段中 */
*(.text.entry) /* entry.asm中, 我们自己定义的.text.entry段, 被放在顶部*/
*(.text .text.*)
}
. = ALIGN(4K);
etext = .;
srodata = .;
.rodata : {
*(.rodata .rodata.*)
*(.srodata .srodata.*)
}
. = ALIGN(4K);
erodata = .;
sdata = .;
.data : {
*(.data .data.*)
*(.sdata .sdata.*)
}
. = ALIGN(4K);
edata = .;
.bss : {
*(.bss.stack) /* 全局符号 sbss 和 ebss 分别指向 .bss 段除 .bss.stack 以外的起始和终止地址(.bss.stack是我们在entry.asm中定义的栈) */
sbss = .;
*(.bss .bss.*)
*(.sbss .sbss.*)
}
. = ALIGN(4K);
ebss = .;
ekernel = .;
/DISCARD/ : {
*(.eh_frame)
}
}

@ -0,0 +1,50 @@
#![feature(panic_info_message)]
#![no_std]
#![no_main]
use core::arch::global_asm;
use sbi::{console_put_char, shutdown};
use lang_items::console;
pub mod lang_items;
pub mod sbi;
pub mod batch;
pub mod sync;
pub mod trap;
pub mod syscall;
// 汇编脚本引入, 调整内核的内存布局之后, 会跳入到 rust_main中执行
global_asm!(include_str!("entry.asm"));
// 引入用户的二进制文件
global_asm!(include_str!("link_app.S"));
extern "C" {
fn stext();
fn etext();
fn sbss();
fn ebss();
fn boot_stack_top_bound();
fn boot_stack_lower_bound();
}
#[no_mangle]
pub fn rust_main(){
init_bss();
println!("stext: {:#x}, etext: {:#x}", stext as usize, etext as usize);
println!("sbss: {:#x}, ebss: {:#x}", sbss as usize, ebss as usize);
println!("boot_stack_top_bound: {:#x}, boot_stack_lower_bound: {:#x}", boot_stack_top_bound as usize, boot_stack_lower_bound as usize);
trap::init();
batch::init();
batch::run_next_app();
}
/// ## 初始化bss段
///
fn init_bss() {
unsafe {
(sbss as usize..ebss as usize).for_each(|p| (p as *mut u8).write_unaligned(0))
}
}

@ -0,0 +1,40 @@
use core::arch::asm;
// legacy extensions: ignore fid
const SBI_SET_TIMER: usize = 0;
const SBI_CONSOLE_PUTCHAR: usize = 1;
const SBI_CONSOLE_GETCHAR: usize = 2;
const SBI_CLEAR_IPI: usize = 3;
const SBI_SEND_IPI: usize = 4;
const SBI_REMOTE_FENCE_I: usize = 5;
const SBI_REMOTE_SFENCE_VMA: usize = 6;
const SBI_REMOTE_SFENCE_VMA_ASID: usize = 7;
// system reset extension
const SRST_EXTENSION: usize = 0x53525354;
const SBI_SHUTDOWN: usize = 0;
#[inline(always)]
fn sbi_call(eid: usize, fid: usize, arg0: usize, arg1: usize, arg2: usize) -> usize {
let mut ret;
unsafe {
asm!(
"ecall",
inlateout("x10") arg0 => ret,
in("x11") arg1,
in("x12") arg2,
in("x16") fid,
in("x17") eid,
);
}
ret
}
pub fn console_put_char(c: usize) {
sbi_call(SBI_CONSOLE_PUTCHAR, 0, c, 0, 0);
}
pub fn shutdown() -> ! {
sbi_call(SRST_EXTENSION, SBI_SHUTDOWN, 0, 0, 0);
panic!("It should shutdown!")
}

@ -0,0 +1,4 @@
//! Synchronization and interior mutability primitives
mod up;
pub use up::UPSafeCell;

@ -0,0 +1,31 @@
//! Uniprocessor interior mutability primitives
use core::cell::{RefCell, RefMut};
/// Wrap a static data structure inside it so that we are
/// able to access it without any `unsafe`.
///
/// We should only use it in uniprocessor.
///
/// In order to get mutable reference of inner data, call
/// `exclusive_access`.
pub struct UPSafeCell<T> {
/// inner data
inner: RefCell<T>,
}
unsafe impl<T> Sync for UPSafeCell<T> {}
impl<T> UPSafeCell<T> {
/// User is responsible to guarantee that inner struct is only used in
/// uniprocessor.
pub unsafe fn new(value: T) -> Self {
Self {
inner: RefCell::new(value),
}
}
/// Exclusive access inner data in UPSafeCell. Panic if the data has been borrowed.
pub fn exclusive_access(&self) -> RefMut<'_, T> {
self.inner.borrow_mut()
}
}

@ -0,0 +1,20 @@
//! File and filesystem-related syscalls
use crate::print;
const FD_STDOUT: usize = 1;
/// write buf of length `len` to a file with `fd`
pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize {
match fd {
FD_STDOUT => {
let slice = unsafe { core::slice::from_raw_parts(buf, len) };
let str = core::str::from_utf8(slice).unwrap();
print!("{}", str);
len as isize
}
_ => {
panic!("Unsupported fd in sys_write!");
}
}
}

@ -0,0 +1,17 @@
const SYSCALL_WRITE: usize = 64;
const SYSCALL_EXIT: usize = 93;
mod fs;
mod process;
use fs::*;
use process::*;
/// 根据syscall_id 进行分发
pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize {
match syscall_id {
SYSCALL_WRITE => sys_write(args[0], args[1] as *const u8, args[2]),
SYSCALL_EXIT => sys_exit(args[0] as i32),
_ => panic!("Unsupported syscall_id: {}", syscall_id),
}
}

@ -0,0 +1,9 @@
//! App management syscalls
use crate::batch::run_next_app;
use crate::println;
/// 任务退出, 并立即切换任务
pub fn sys_exit(exit_code: i32) -> ! {
println!("[kernel] Application exited with code {}", exit_code);
run_next_app()
}

@ -0,0 +1,40 @@
use riscv::register::sstatus::{self, Sstatus, SPP};
/// Trap Context
#[repr(C)]
pub struct TrapContext {
/// 保存了 [0..31] 号寄存器, 其中0/2/4 号寄存器我们不保存, 2有特殊用途
/// > 其中 [17] 号寄存器保存的是系统调用号
///
/// > [10]/[11]/[12] 寄存器保存了系统调用时的3个参数
///
/// > [2] 号寄存器因为我们有特殊用途所以也跳过保存, (保存了用户栈)保存了用户 USER_STACK 的 栈顶
///
/// > [0] 被硬编码为了0, 不会有变化, 不需要做任何处理
///
/// > [4] 除非特殊用途使用它, 一般我们也用不到, 不需要做任何处理
pub x: [usize; 32],
/// CSR sstatus 保存的是在trap发生之前, cpu处在哪一个特权级
pub sstatus: Sstatus,
/// CSR sepc 保存的是用户态ecall时 所在的那一行的代码
pub sepc: usize,
}
impl TrapContext {
/// 把用户栈的栈顶 保存到 [2]
pub fn set_sp(&mut self, sp: usize) {
self.x[2] = sp;
}
/// init app context
pub fn app_init_context(entry: usize, sp: usize) -> Self {
let mut sstatus = sstatus::read(); // 读取CSR sstatus
sstatus.set_spp(SPP::User); // 设置特权级为用户模式
let mut cx = Self {
x: [0; 32],
sstatus,
sepc: entry, // 设置代码执行的开头, 将来条入到这里执行
};
cx.set_sp(sp); // 设置用户栈的栈顶
cx // 返回, 外面会恢复完 x[0; 32] 之后最后 sret 根据entry和sstatus 返回
}
}

@ -0,0 +1,66 @@
mod context;
use core::arch::global_asm;
use riscv::register::{
mtvec::TrapMode,
scause::{self, Exception, Trap},
stval, stvec,
};
pub use context::TrapContext;
use crate::batch::run_next_app;
use crate::println;
use crate::syscall::syscall;
// 引入陷入保存寄存器需要的汇编代码
global_asm!(include_str!("trap.S"));
/// 初始化stvec 寄存器, 这个寄存器保存陷入时, 入口函数的地址
pub fn init() {
extern "C" {
fn __alltraps();
}
unsafe {
stvec::write(__alltraps as usize, TrapMode::Direct);
}
}
// 这个函数是 trap.S 中__alltraps 保存完所有寄存器在内核栈 之后会进入到这里
#[no_mangle]
pub fn trap_handler(trap_context: &mut TrapContext) -> &mut TrapContext {
let scause = scause::read(); // trap 发生的原因
let stval = stval::read(); // trap的附加信息
// 根据发生的原因判断是那种类别
match scause.cause() {
// 用户态发出的系统调用
Trap::Exception(Exception::UserEnvCall) => {
trap_context.sepc += 4; // +4 是因为我们需要返回 ecall指令的下一个指令
trap_context.x[10] = syscall(trap_context.x[17], [trap_context.x[10], trap_context.x[11], trap_context.x[12]]) as usize;
}
// 访问不允许的内存
Trap::Exception(Exception::StoreFault) | Trap::Exception(Exception::StorePageFault) => {
println!("[kernel] PageFault in application, kernel killed it.");
run_next_app();
}
// 非法指令
Trap::Exception(Exception::IllegalInstruction) => {
println!("[kernel] IllegalInstruction in application, kernel killed it.");
run_next_app();
}
// 未知错误
_ => {
panic!(
"Unsupported trap {:?}, stval = {:#x}!",
scause.cause(),
stval
);
}
}
trap_context
}

@ -0,0 +1,73 @@
# trap__alltraps, __restore
.altmacro
.macro SAVE_GP n
sd x\n, \n*8(sp) # x_n
.endm
.macro LOAD_GP n
ld x\n, \n*8(sp) # x_n
.endm
.section .text # .text
.globl __alltraps # __alltraps
.globl __restore # __restore
.align 2 # 2^2 = 4
__alltraps: # __alltraps
csrrw sp, sscratch, sp # sp sscratch
# sp sscratch
# TrapContext
addi sp, sp, -34*8 # 34*8
#
sd x1, 1*8(sp) # x1 (x0, 便)
# sp(x2)
sd x3, 3*8(sp) # x3 (x4, 便)
# tp(x4)使
# x5~x31
.set n, 5 # n 5
.rept 27 # 27
SAVE_GP %n # x_n
.set n, n+1 # n 1
.endr #
# 使 t0/t1/t2
csrr t0, sstatus # sstatus
csrr t1, sepc # sepc
sd t0, 32*8(sp) # sstatus
sd t1, 33*8(sp) # sepc
# sscratch
csrr t2, sscratch # sscratch
sd t2, 2*8(sp) # trap context
# trap_handler(cx: &mut TrapContext)
mv a0, sp # TrapContext a0
call trap_handler # trap_handler
__restore: # __restore
# case1:
# case2: U
mv sp, a0 # a0 sp sp KERNEL_STACK_SIZE,
# sstatus/sepc
ld t0, 32*8(sp) # sstatus
ld t1, 33*8(sp) # sepc
ld t2, 2*8(sp) #
csrw sstatus, t0 # sstatus
csrw sepc, t1 # sepc
csrw sscratch, t2 # sscratch
# sp sscratch
# sp/tp
# x0
ld x1, 1*8(sp) # x1
# x2
ld x3, 3*8(sp) # x3
#
.set n, 5 # n 5
.rept 27 # 27
LOAD_GP %n # x_n
.set n, n+1 # n 1
.endr #
# sp sscratch , TrapContext, ,
addi sp, sp, 34*8 # sizeof<TrapContext>
csrrw sp, sscratch, sp # sp sscratch , sscratch, sp USER_STACK()
sret # , sstatus(/) sepc(/ pc)

@ -0,0 +1,12 @@
[package]
name = "user_lib"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
riscv = { git = "https://github.com/rcore-os/riscv", features = ["inline-asm"] }
[profile.release]
debug = true

@ -0,0 +1,29 @@
MODE := release
TARGET := riscv64gc-unknown-none-elf
OBJDUMP := rust-objdump --arch-name=riscv64
OBJCOPY := rust-objcopy --binary-architecture=riscv64
RUST_FLAGS := -Clink-arg=-Tsrc/linker.ld # 使用我们自己的链接脚本
RUST_FLAGS += -Cforce-frame-pointers=yes # 强制编译器生成帧指针
RUST_FLAGS:=$(strip ${RUST_FLAGS})
APP_DIR := src/bin
TARGET_DIR := target/$(TARGET)/$(MODE)
APPS := $(wildcard $(APP_DIR)/*.rs)
ELFS := $(patsubst $(APP_DIR)/%.rs, $(TARGET_DIR)/%, $(APPS))
BINS := $(patsubst $(APP_DIR)/%.rs, $(TARGET_DIR)/%.bin, $(APPS))
# 编译elf文件
build_elf: clean
CARGO_BUILD_RUSTFLAGS="$(RUST_FLAGS)" \
cargo build --$(MODE) --target=$(TARGET)
# 把每个elf文件去掉无关代码
build: build_elf
@$(foreach elf, $(ELFS), $(OBJCOPY) $(elf) --strip-all -O binary $(patsubst $(TARGET_DIR)/%, $(TARGET_DIR)/%.bin, $(elf));)
clean:
rm -rf ./target*

@ -0,0 +1,10 @@
#![no_std]
#![no_main]
use user_lib::*;
#[no_mangle]
fn main() -> i32 {
println!("hello 1");
0
}

@ -0,0 +1,15 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
#[no_mangle]
fn main() -> i32 {
println!("Into Test store_fault, we will insert an invalid store operation...");
println!("Kernel should kill this application!");
unsafe {
core::ptr::null_mut::<u8>().write_volatile(0);
}
0
}

@ -0,0 +1,27 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
const SIZE: usize = 10;
const P: u32 = 3;
const STEP: usize = 100000;
const MOD: u32 = 10007;
#[no_mangle]
fn main() -> i32 {
let mut pow = [0u32; SIZE];
let mut index: usize = 0;
pow[index] = 1;
for i in 1..=STEP {
let last = pow[index];
index = (index + 1) % SIZE;
pow[index] = last * P % MOD;
if i % 10000 == 0 {
println!("{}^{}={}(MOD {})", P, i, pow[index], MOD);
}
}
println!("Test power OK!");
0
}

@ -0,0 +1,17 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use core::arch::asm;
#[no_mangle]
fn main() -> i32 {
println!("Try to execute privileged instruction in U Mode");
println!("Kernel should kill this application!");
unsafe {
asm!("sret");
}
0
}

@ -0,0 +1,17 @@
#![no_std]
#![no_main]
#[macro_use]
extern crate user_lib;
use riscv::register::sstatus::{self, SPP};
#[no_mangle]
fn main() -> i32 {
println!("Try to access privileged CSR in U Mode");
println!("Kernel should kill this application!");
unsafe {
sstatus::set_spp(SPP::User);
}
0
}

@ -0,0 +1,38 @@
#![no_std]
#![feature(linkage)] // 开启弱链接特性
#![feature(panic_info_message)]
pub mod user_lang_items;
pub use user_lang_items::*;
pub mod syscall;
use syscall::{sys_exit};
extern "C" {
fn start_bss();
fn end_bss();
}
// 只要使用这个包, 那么这里就会作为bin程序的开始
#[no_mangle]
#[link_section = ".text.entry"] // 链接到指定的段
pub extern "C" fn _start() -> ! {
clear_bss();
sys_exit(main()); // 这里执行的main程序是我们 bin文件夹里面的main, 而不是下面的, 下面的main程序只有在bin程序没有main函数的时候才会链接
// 正常是不会走到这一步的, 因为上面已经退出了程序
panic!("unreachable after sys_exit!");
}
#[linkage = "weak"] // 设置我们默认的main函数, 弱链接
#[no_mangle]
fn main() -> i32 {
panic!("Cannot find main!");
}
fn clear_bss() {
unsafe {
(start_bss as usize..end_bss as usize).for_each(|p| (p as *mut u8).write_unaligned(0))
};
}

@ -0,0 +1,32 @@
OUTPUT_ARCH(riscv)
ENTRY(_start)
/*设置用户程序链接的基础起始位置为0x80400000*/
BASE_ADDRESS = 0x80400000;
SECTIONS
{
. = BASE_ADDRESS;
.text : {
*(.text.entry)
*(.text .text.*)
}
.rodata : {
*(.rodata .rodata.*)
*(.srodata .srodata.*)
}
.data : {
*(.data .data.*)
*(.sdata .sdata.*)
}
.bss : {
start_bss = .;
*(.bss .bss.*)
*(.sbss .sbss.*)
end_bss = .;
}
/DISCARD/ : {
*(.eh_frame)
*(.debug*)
}
}

@ -0,0 +1,30 @@
use core::arch::asm;
const SYSCALL_WRITE: usize = 64;
const SYSCALL_EXIT: usize = 93;
fn syscall(id: usize, args: [usize; 3]) -> isize {
let mut ret: isize;
unsafe {
// a0寄存器同时作为输入参数和输出参数, {in_var} => {out_var}
asm!(
"ecall",
inlateout("x10") args[0] => ret,
in("x11") args[1],
in("x12") args[2],
in("x17") id
);
}
ret
}
pub fn sys_write(fd: usize, buffer: &[u8]) -> isize {
syscall(SYSCALL_WRITE, [fd, buffer.as_ptr() as usize, buffer.len()])
}
pub fn sys_exit(exit_code: i32) -> isize {
syscall(SYSCALL_EXIT, [exit_code as usize, 0, 0])
}

@ -0,0 +1,2 @@
pub mod user_panic;
pub mod user_console;

@ -0,0 +1,32 @@
use core::fmt::{Arguments, Write, Result};
use crate::syscall::sys_write;
struct Stdout;
const STDOUT: usize = 1;
impl Write for Stdout {
fn write_str(&mut self, s: &str) -> Result {
sys_write(STDOUT, s.as_bytes());
Ok(())
}
}
pub fn print(args: Arguments) {
Stdout.write_fmt(args).unwrap();
}
#[macro_export]
macro_rules! print {
($fmt: literal $(, $($arg: tt)+)?) => {
$crate::user_console::print(format_args!($fmt $(, $($arg)+)?));
}
}
#[macro_export]
macro_rules! println {
($fmt: literal $(, $($arg: tt)+)?) => {
$crate::user_console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?));
}
}

@ -0,0 +1,19 @@
use core::panic::PanicInfo;
use crate::println;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
if let Some(location) = info.location() {
println!(
"Panicked at {}:{} {}",
location.file(),
location.line(),
info.message().unwrap()
);
} else {
println!("Panicked: {}", info.message().unwrap());
}
loop {
}
}
Loading…
Cancel
Save