#interrupt #bare-metal #userspace #x86-64 #risc-v

nightly no-std trapframe

Handle Trap Frame across kernel and user space on multiple ISAs

21 releases

0.10.0 Jul 12, 2024
0.9.0 Feb 27, 2022
0.8.0 Jul 26, 2021
0.7.0 Feb 13, 2021
0.1.4 Mar 24, 2020

#247 in Embedded development

Download history 1664/week @ 2024-07-19 1564/week @ 2024-07-26 1237/week @ 2024-08-02 1300/week @ 2024-08-09 1473/week @ 2024-08-16 2017/week @ 2024-08-23 1652/week @ 2024-08-30 1033/week @ 2024-09-06 1404/week @ 2024-09-13 477/week @ 2024-09-20 783/week @ 2024-09-27 443/week @ 2024-10-04 486/week @ 2024-10-11 389/week @ 2024-10-18 359/week @ 2024-10-25 371/week @ 2024-11-01

1,691 downloads per month

MIT license

66KB
2K SLoC

Rust 1K SLoC // 0.1% comments GNU Style Assembly 762 SLoC // 0.0% comments

TrapFrame-rs

Crate Docs Actions Status

Handle Trap Frame across kernel and user space on multiple ISAs.

Supported ISA: x86_64, aarch64, riscv32, riscv64, mipsel

Example

Go to user space

use trapframe::{UserContext, GeneralRegs};

fn kernel_thread() {
    // initialize trap handling
    unsafe {
        trapframe::init();
    }
    // construct a user space context, set registers
    let mut context = UserContext {
        general: GeneralRegs {
            rip: 0x1000,
            rsp: 0x10000,
            ..Default::default()
        },
        ..Default::default()
    };
    // go to user space with the context
    context.run();
    // come back from user space, maybe syscall or trap
    println!("back from user: {:#x?}", context);
    // check the context and handle the trap
    match context.trap_num {
        0x3 => println!("breakpoint"),
        0xd => println!("general protection fault"),
        0x100 => println!("syscall: id={}", context.general.rax),
        ...
    }
}

Handle kernel trap

use trapframe::TrapFrame;

#[no_mangle]	// export a function 'trap_handler'
extern "sysv64" fn trap_handler(tf: &mut TrapFrame) {
    match tf.trap_num {
        0x3 => {
            println!("TRAP: Breakpoint");
            tf.rip += 1;
        }
        _ => panic!("TRAP: {:#x?}", tf),
    }
}

More examples

Internal

Control flow on x86_64:

x86_64

Dependencies

~1MB
~19K SLoC