1+ #![ no_std]
2+ #![ no_main]
3+ #![ feature( panic_info_message) ]
4+
5+
6+ use log:: * ;
7+
8+
9+ #[ macro_use]
10+ mod console;
11+ mod lang_items;
12+ mod logging;
13+
14+ // 使用global_asm宏将entry.asm嵌入到代码中
15+ core:: arch:: global_asm!( include_str!( "entry.asm" ) ) ;
16+
17+
18+ const SBI_SET_TIMER : usize = 0 ;
19+ const SBI_CONSOLE_PUTCHAR : usize = 1 ;
20+ const SBI_CONSOLE_GETCHAR : usize = 2 ;
21+ const SYSCALL_EXIT : usize = 93 ;
22+ const SYSCALL_WRITE : usize = 64 ;
23+ const SBI_SHUTDOWN : usize = 8 ;
24+
25+
26+ #[ inline( always) ]
27+ fn syscall ( id : usize , args : [ usize ; 3 ] ) -> usize {
28+ let mut ret;
29+ unsafe {
30+ // 应用程序访问操作系统提供的系统调用指令是ecall
31+ // 操作系统访问RustSBI提供的SBI调用指令也是ecall
32+ // 指令相同但特权级不同,应用程序处于用户级,操作系统处于内核特权级,RustSBI处于机器特权级
33+ core:: arch:: asm!(
34+ "ecall" ,
35+ inlateout( "x10" ) args[ 0 ] => ret,
36+ in( "x11" ) args[ 1 ] ,
37+ in( "x12" ) args[ 2 ] ,
38+ in( "x17" ) id,
39+ ) ;
40+ }
41+ ret
42+ }
43+
44+ pub fn sys_exit ( xstate : i32 ) -> usize {
45+ syscall ( SYSCALL_EXIT , [ xstate as usize , 0 , 0 ] )
46+ }
47+
48+ pub fn sys_write ( fd : usize , buffer : & [ u8 ] ) -> usize {
49+ syscall ( SYSCALL_WRITE , [ fd, buffer. as_ptr ( ) as usize , buffer. len ( ) ] )
50+ }
51+
52+ pub fn console_putchar ( c : usize ) {
53+ syscall ( SBI_CONSOLE_PUTCHAR , [ c, 0 , 0 ] ) ;
54+ }
55+
56+ pub fn console_getchar ( ) -> usize {
57+ syscall ( SBI_CONSOLE_GETCHAR , [ 0 , 0 , 0 ] )
58+ }
59+
60+ pub fn shutdown ( ) -> ! {
61+ syscall ( SBI_SHUTDOWN , [ 0 , 0 , 0 ] ) ;
62+ panic ! ( "It should shutdown!" ) ;
63+ }
64+
65+ fn clear_bss ( ) {
66+ extern "C" {
67+ fn sbss ( ) ;
68+ fn ebss ( ) ;
69+ }
70+ ( sbss as usize ..ebss as usize ) . for_each ( |a| unsafe { ( a as * mut u8 ) . write_volatile ( 0 ) } ) ;
71+ }
72+
73+ // #[no_mangle]
74+ // extern "C" fn _start() {
75+ // // loop {};
76+ // println!("Hello World");
77+ // sys_exit(9);
78+ // shutdown();
79+ // }
80+
81+ // 标记为no_mangle避免编译器对名字混淆,否则entry.asm在链接时找不到rust_main
82+ #[ no_mangle]
83+ pub fn rust_main ( ) -> ! {
84+ extern "C" {
85+ fn stext ( ) ;
86+ fn etext ( ) ;
87+ fn srodata ( ) ;
88+ fn erodata ( ) ;
89+ fn sdata ( ) ;
90+ fn edata ( ) ;
91+ fn sbss ( ) ;
92+ fn ebss ( ) ;
93+ fn boot_stack ( ) ;
94+ fn boot_stack_top ( ) ;
95+ }
96+ clear_bss ( ) ;
97+ logging:: init ( ) ;
98+ println ! ( "Hello, world!" ) ;
99+ trace ! ( ".text [{:#x}, {:#x})" , stext as usize , etext as usize ) ;
100+ debug ! ( ".rodata [{:#x}, {:#x})" , srodata as usize , erodata as usize ) ;
101+ info ! ( ".data [{:#x}, {:#x})" , sdata as usize , edata as usize ) ;
102+ warn ! (
103+ "boot_stack [{:#x}, {:#x})" ,
104+ boot_stack as usize , boot_stack_top as usize
105+ ) ;
106+ error ! ( ".bss [{:#x}, {:#x})" , sbss as usize , ebss as usize ) ;
107+ panic ! ( "Shutdown machine!" ) ;
108+ // shutdown();
109+ }
0 commit comments