#![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 sync;
pub mod trap;
pub mod syscall;
pub mod loader;
pub mod config;
pub mod task;
pub mod timer;

#[path = "boards/qemu.rs"]
mod board;



// 汇编脚本引入, 调整内核的内存布局之后, 会跳入到 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();

    loader::load_app();
    trap::enable_timer_interrupt();  // 允许定时器中断
    timer::set_next_trigger();  // 在进入用户态之前, 设置一个时钟中断, 防止第一个用户任务死循环
    task::run_first_task();

    panic!("Disable run here")
}

/// ## 初始化bss段
///
fn init_bss() {
    unsafe {
        (sbss as usize..ebss as usize).for_each(|p| (p as *mut u8).write_unaligned(0))
    }
}
