From a3e18591ec4aebe1503e34b36dcbc2908cf967e7 Mon Sep 17 00:00:00 2001 From: Jonas Kruckenberg Date: Wed, 20 Nov 2024 21:07:10 +0100 Subject: [PATCH] chore: update Rust nightly version to 2024-11-20 (1.84) (#148) * chore: update flake deps and bump rust nightly version * refactor: add explicit lifetime names * refactor: replace removed `CARGO_RUSTC_CURRENT_DIR` ref: https://github.com/rust-lang/cargo/issues/3946 * refactor: switch naked fns to `naked_asm!` Switch to the newly required `naked_asm!` macro in all naked functions. ref: https://github.com/rust-lang/rust/issues/90957 * fix: update custom target manifest files to avoid ICE apparently Rust doesn't like it when the custom target manifest file is missing the `llvm-abiname` field * silence warning about mutable static * refactor: elide lifetimes * fmt * refactor: apply `clippy::manual_div_ceil` suggestion * fix: use explicit `ptr.wrapping_byte_add` for conversions from physmem to virtmem references We previously relied on UB actually doing the wrapping behaviour, but well, that's not ideal is it --- flake.lock | 18 +- flake.nix | 80 ++--- justfile | 4 + kernel/riscv64gc-k23-none-kernel.json | 1 + kernel/src/arch/riscv64/setjmp_longjmp.rs | 14 +- kernel/src/arch/riscv64/trap_handler.rs | 278 +++++++++--------- kernel/src/runtime/errors.rs | 2 +- kernel/src/runtime/instance.rs | 4 +- kernel/src/runtime/translate/func_env.rs | 8 +- kernel/src/runtime/translate/mod.rs | 2 +- kernel/src/runtime/translate/module_env.rs | 2 +- libs/backtrace/src/lib.rs | 2 +- libs/backtrace/src/symbolize.rs | 8 +- libs/dtb-parser/src/debug.rs | 2 +- libs/dtb-parser/src/lib.rs | 2 +- libs/kmm/src/alloc/bump.rs | 6 +- libs/kmm/src/elf.rs | 4 +- libs/ktest/src/run.rs | 2 +- libs/leb128/src/lib.rs | 4 +- libs/sync/src/once.rs | 2 +- libs/unwind2/src/arch/riscv64.rs | 10 +- libs/unwind2/src/eh_info.rs | 1 + libs/wasm-encoder/src/component/types.rs | 2 +- libs/wast/src/component/component.rs | 4 +- libs/wast/src/component/import.rs | 2 +- libs/wast/src/component/item_ref.rs | 4 +- libs/wast/src/core/binary.rs | 18 +- libs/wast/src/core/expr.rs | 4 +- libs/wast/src/core/module.rs | 2 +- .../core/resolve/deinline_import_export.rs | 2 +- libs/wast/src/core/types.rs | 12 +- libs/wast/src/lexer.rs | 2 +- libs/wast/src/token.rs | 6 +- libs/wast/src/wast.rs | 2 +- loader/build.rs | 2 +- loader/riscv64imac-k23-none-loader.json | 2 + loader/src/arch/riscv64.rs | 8 +- loader/src/boot_info.rs | 35 ++- rust-toolchain.toml | 2 +- 39 files changed, 289 insertions(+), 276 deletions(-) diff --git a/flake.lock b/flake.lock index b0ef843f..6bca8bae 100644 --- a/flake.lock +++ b/flake.lock @@ -5,11 +5,11 @@ "systems": "systems" }, "locked": { - "lastModified": 1710146030, - "narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=", + "lastModified": 1731533236, + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", "owner": "numtide", "repo": "flake-utils", - "rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a", + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", "type": "github" }, "original": { @@ -20,11 +20,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1724224976, - "narHash": "sha256-Z/ELQhrSd7bMzTO8r7NZgi9g5emh+aRKoCdaAv5fiO0=", + "lastModified": 1731676054, + "narHash": "sha256-OZiZ3m8SCMfh3B6bfGC/Bm4x3qc1m2SVEAlkV6iY7Yg=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "c374d94f1536013ca8e92341b540eba4c22f9c62", + "rev": "5e4fbfb6b3de1aa2872b76d49fafc942626e2add", "type": "github" }, "original": { @@ -48,11 +48,11 @@ ] }, "locked": { - "lastModified": 1724293269, - "narHash": "sha256-x/XhOAszT/ejditCHUtGOjQcVg2AQhrC/QVew3i7kTI=", + "lastModified": 1732069891, + "narHash": "sha256-moKx8AVJrViCSdA0e0nSsG8b1dAsObI4sRAtbqbvBY8=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "6dc6d34a3a217457d7044dcce32b6d537480a6a1", + "rev": "8509a51241c407d583b1963d5079585a992506e8", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index 1a6b758a..0a9a7986 100644 --- a/flake.nix +++ b/flake.nix @@ -1,48 +1,48 @@ -# forked from https://github.com/tosc-rs/mnemos/blob/main/flake.nix { - description = "Flake providing a development shell for k23"; + description = "Flake providing a development shell for k23"; - inputs = { - nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; - flake-utils.url = "github:numtide/flake-utils"; - rust-overlay = { - url = "github:oxalica/rust-overlay"; - inputs = { - nixpkgs.follows = "nixpkgs"; - }; + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + rust-overlay = { + url = "github:oxalica/rust-overlay"; + inputs = { + nixpkgs.follows = "nixpkgs"; }; }; + }; - outputs = { nixpkgs, flake-utils, rust-overlay, ... }: - flake-utils.lib.eachDefaultSystem (system: - let - overlays = [ (import rust-overlay) ]; - pkgs = import nixpkgs { inherit system overlays; }; - # use the Rust toolchain specified in the project's rust-toolchain.toml - rustToolchain = pkgs.pkgsBuildHost.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; - in - { - devShell = with pkgs; mkShell rec { - name = "k23-dev"; - nativeBuildInputs = [ - # compilers - rustToolchain - clang + outputs = { self, nixpkgs, rust-overlay, flake-utils, ... }: + flake-utils.lib.eachDefaultSystem (system: + let + overlays = [ (import rust-overlay) ]; + pkgs = import nixpkgs { + inherit system overlays; + }; + rustToolchain = with pkgs; rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; + in + { + devShells.default = with pkgs; mkShell rec { + name = "k23-dev"; + buildInputs = [ + # compilers + rustToolchain + clang - # devtools - just - mdbook - socat - wabt + # devtools + just + mdbook + socat + wabt + dtc - # for testing the kernel - qemu - ]; - buildInputs = []; + # for testing the kernel + qemu + ]; - LIBCLANG_PATH = "${llvmPackages.libclang.lib}/lib"; - LD_LIBRARY_PATH = "${lib.makeLibraryPath buildInputs}"; - }; - } - ); -} \ No newline at end of file + LIBCLANG_PATH = "${llvmPackages.libclang.lib}/lib"; + LD_LIBRARY_PATH = "${lib.makeLibraryPath buildInputs}"; + }; + } + ); +} diff --git a/justfile b/justfile index 268475bf..92f1b8fa 100755 --- a/justfile +++ b/justfile @@ -50,6 +50,10 @@ Variables can be set using `just VARIABLE=VALUE ...` or # env var to set the cargo runner for the riscv64 target export CARGO_TARGET_RISCV64GC_K23_NONE_KERNEL_RUNNER := "just _run_riscv64" +# as of recent Rust nightly versions the old `CARGO_RUSTC_CURRENT_DIR` we used to locate the kernel artifact from the +# loader build script got removed :/ This is a stopgap until they come up with a replacement. +# https://github.com/rust-lang/cargo/issues/3946 +export __K23_CARGO_RUSTC_CURRENT_DIR := `dirname "$(cargo locate-project --workspace --message-format plain)"` # default recipe to display help information _default: diff --git a/kernel/riscv64gc-k23-none-kernel.json b/kernel/riscv64gc-k23-none-kernel.json index e12a09ae..6b96ffcc 100644 --- a/kernel/riscv64gc-k23-none-kernel.json +++ b/kernel/riscv64gc-k23-none-kernel.json @@ -18,6 +18,7 @@ "position-independent-executables": true, "relro-level": "full", "supported-sanitizers": [ + "shadow-call-stack", "kernel-address" ], "target-pointer-width": "64" diff --git a/kernel/src/arch/riscv64/setjmp_longjmp.rs b/kernel/src/arch/riscv64/setjmp_longjmp.rs index ef70e9bc..673de6a7 100644 --- a/kernel/src/arch/riscv64/setjmp_longjmp.rs +++ b/kernel/src/arch/riscv64/setjmp_longjmp.rs @@ -36,7 +36,7 @@ //! result. In a nested calls scenario (e.g. host->wasm->host->wasm) it is therefore up to each host function //! to propagate the trap and each host function therefore gets to clean up all its resources. -use core::arch::asm; +use core::arch::naked_asm; use core::ptr; /// A store for the register state used by `setjmp` and `longjmp`. @@ -146,7 +146,7 @@ cfg_if::cfg_if! { pub unsafe extern "C" fn setjmp(buf: *mut JumpBuf) -> isize { cfg_if::cfg_if! { if #[cfg(target_feature = "d")] { - asm! { + naked_asm! { save_gp!(ra => a0[0]), save_gp!(s0 => a0[1]), save_gp!(s1 => a0[2]), @@ -177,10 +177,9 @@ pub unsafe extern "C" fn setjmp(buf: *mut JumpBuf) -> isize { "mv a0, zero", "ret", - options(noreturn) } } else { - asm! { + naked_asm! { save_gp!(ra => a0[0]), save_gp!(s0 => a0[1]), save_gp!(s1 => a0[2]), @@ -197,7 +196,6 @@ pub unsafe extern "C" fn setjmp(buf: *mut JumpBuf) -> isize { save_gp!(sp => a0[13]), "mv a0, zero", "ret", - options(noreturn) } } } @@ -217,7 +215,7 @@ pub unsafe extern "C" fn setjmp(buf: *mut JumpBuf) -> isize { pub unsafe extern "C" fn longjmp(buf: *mut JumpBuf, val: isize) -> ! { cfg_if::cfg_if! { if #[cfg(target_feature = "d")] { - asm! { + naked_asm! { load_gp!(a0[0] => ra), load_gp!(a0[1] => s0), load_gp!(a0[2] => s1), @@ -248,10 +246,9 @@ pub unsafe extern "C" fn longjmp(buf: *mut JumpBuf, val: isize) -> ! { "add a0, a1, zero", "ret", - options(noreturn) } } else { - asm! { + naked_asm! { load_gp!(a0[0] => ra), load_gp!(a0[1] => s0), load_gp!(a0[2] => s1), @@ -269,7 +266,6 @@ pub unsafe extern "C" fn longjmp(buf: *mut JumpBuf, val: isize) -> ! { "add a0, a1, zero", "ret", - options(noreturn) } } } diff --git a/kernel/src/arch/riscv64/trap_handler.rs b/kernel/src/arch/riscv64/trap_handler.rs index a7d668e8..8887850a 100644 --- a/kernel/src/arch/riscv64/trap_handler.rs +++ b/kernel/src/arch/riscv64/trap_handler.rs @@ -1,5 +1,5 @@ use crate::kconfig; -use core::arch::asm; +use core::arch::{asm, naked_asm}; use riscv::scause::{Exception, Trap}; use riscv::{scause, sepc, sstatus, stval, stvec}; use thread_local::declare_thread_local; @@ -44,154 +44,152 @@ unsafe extern "C" fn trap_vec() { // // We can use this to direct some traps that don't need // expensive SBI call handling to cheaper handlers (like timers) - asm! ( - ".align 2", - ".option push", - ".option norvc", - "j {default}", // exception - "j {default}", // supervisor software interrupt - "j {default}", // reserved - "j {default}", // reserved - "j {default}", // reserved - "j {default}", // supervisor timer interrupt - "j {default}", // reserved - "j {default}", // reserved - "j {default}", // reserved - "j {default}", // supervisor external interrupt - ".option pop", - default = sym default_trap_entry, - options(noreturn) - ) + naked_asm! { + ".align 2", + ".option push", + ".option norvc", + "j {default}", // exception + "j {default}", // supervisor software interrupt + "j {default}", // reserved + "j {default}", // reserved + "j {default}", // reserved + "j {default}", // supervisor timer interrupt + "j {default}", // reserved + "j {default}", // reserved + "j {default}", // reserved + "j {default}", // supervisor external interrupt + ".option pop", + default = sym default_trap_entry, + } } #[allow(clippy::too_many_lines)] #[naked] unsafe extern "C" fn default_trap_entry() { - asm! { - ".align 2", - - "mv t0, sp", // save the correct stack pointer - "csrrw sp, sscratch, sp", // t6 points to the TrapFrame - "add sp, sp, -0x210", - - // save gp - " - sd x0, 0x00(sp) - sd ra, 0x08(sp) - sd t0, 0x10(sp) - sd gp, 0x18(sp) - sd tp, 0x20(sp) - sd s0, 0x40(sp) - sd s1, 0x48(sp) - sd s2, 0x90(sp) - sd s3, 0x98(sp) - sd s4, 0xA0(sp) - sd s5, 0xA8(sp) - sd s6, 0xB0(sp) - sd s7, 0xB8(sp) - sd s8, 0xC0(sp) - sd s9, 0xC8(sp) - sd s10, 0xD0(sp) - sd s11, 0xD8(sp) + naked_asm! { + ".align 2", + + "mv t0, sp", // save the correct stack pointer + "csrrw sp, sscratch, sp", // t6 points to the TrapFrame + "add sp, sp, -0x210", + + // save gp + " + sd x0, 0x00(sp) + sd ra, 0x08(sp) + sd t0, 0x10(sp) + sd gp, 0x18(sp) + sd tp, 0x20(sp) + sd s0, 0x40(sp) + sd s1, 0x48(sp) + sd s2, 0x90(sp) + sd s3, 0x98(sp) + sd s4, 0xA0(sp) + sd s5, 0xA8(sp) + sd s6, 0xB0(sp) + sd s7, 0xB8(sp) + sd s8, 0xC0(sp) + sd s9, 0xC8(sp) + sd s10, 0xD0(sp) + sd s11, 0xD8(sp) + ", + + // save fp + " + fsd fs0, 0x140(sp) + fsd fs1, 0x148(sp) + fsd fs2, 0x190(sp) + fsd fs3, 0x198(sp) + fsd fs4, 0x1A0(sp) + fsd fs5, 0x1A8(sp) + fsd fs6, 0x1B0(sp) + fsd fs7, 0x1B8(sp) + fsd fs8, 0x1C0(sp) + fsd fs9, 0x1C8(sp) + fsd fs10, 0x1D0(sp) + fsd fs11, 0x1D8(sp) ", - // save fp - " - fsd fs0, 0x140(sp) - fsd fs1, 0x148(sp) - fsd fs2, 0x190(sp) - fsd fs3, 0x198(sp) - fsd fs4, 0x1A0(sp) - fsd fs5, 0x1A8(sp) - fsd fs6, 0x1B0(sp) - fsd fs7, 0x1B8(sp) - fsd fs8, 0x1C0(sp) - fsd fs9, 0x1C8(sp) - fsd fs10, 0x1D0(sp) - fsd fs11, 0x1D8(sp) - ", - - "mv a0, sp", - - "call {trap_handler}", - - "mv sp, a0", - - // restore gp - "ld ra, 0x08(a0)", - // skip sp since it is saved in sscratch - "ld gp, 0x18(a0) - ld tp, 0x20(a0) - ld t0, 0x28(a0) - ld t1, 0x30(a0) - ld t2, 0x38(a0) - ld s0, 0x40(a0) - ld s1, 0x48(a0) - ld a1, 0x58(a0) - ld a2, 0x60(a0) - ld a3, 0x68(a0) - ld a4, 0x70(a0) - ld a5, 0x78(a0) - ld a6, 0x80(a0) - ld a7, 0x88(a0) - ld s2, 0x90(a0) - ld s3, 0x98(a0) - ld s4, 0xA0(a0) - ld s5, 0xA8(a0) - ld s6, 0xB0(a0) - ld s7, 0xB8(a0) - ld s8, 0xC0(a0) - ld s9, 0xC8(a0) - ld s10, 0xD0(a0) - ld s11, 0xD8(a0) - ld t3, 0xE0(a0) - ld t4, 0xE8(a0) - ld t5, 0xF0(a0) - ld t6, 0xF8(a0) + "mv a0, sp", + + "call {trap_handler}", + + "mv sp, a0", + + // restore gp + "ld ra, 0x08(a0)", + // skip sp since it is saved in sscratch + "ld gp, 0x18(a0) + ld tp, 0x20(a0) + ld t0, 0x28(a0) + ld t1, 0x30(a0) + ld t2, 0x38(a0) + ld s0, 0x40(a0) + ld s1, 0x48(a0) + ld a1, 0x58(a0) + ld a2, 0x60(a0) + ld a3, 0x68(a0) + ld a4, 0x70(a0) + ld a5, 0x78(a0) + ld a6, 0x80(a0) + ld a7, 0x88(a0) + ld s2, 0x90(a0) + ld s3, 0x98(a0) + ld s4, 0xA0(a0) + ld s5, 0xA8(a0) + ld s6, 0xB0(a0) + ld s7, 0xB8(a0) + ld s8, 0xC0(a0) + ld s9, 0xC8(a0) + ld s10, 0xD0(a0) + ld s11, 0xD8(a0) + ld t3, 0xE0(a0) + ld t4, 0xE8(a0) + ld t5, 0xF0(a0) + ld t6, 0xF8(a0) + ", + + // restore fp + " + fld ft0, 0x100(a0) + fld ft1, 0x108(a0) + fld ft2, 0x110(a0) + fld ft3, 0x118(a0) + fld ft4, 0x120(a0) + fld ft5, 0x128(a0) + fld ft6, 0x130(a0) + fld ft7, 0x138(a0) + fld fs0, 0x140(a0) + fld fs1, 0x148(a0) + fld fa0, 0x150(a0) + fld fa1, 0x158(a0) + fld fa2, 0x160(a0) + fld fa3, 0x168(a0) + fld fa4, 0x170(a0) + fld fa5, 0x178(a0) + fld fa6, 0x180(a0) + fld fa7, 0x188(a0) + fld fs2, 0x190(a0) + fld fs3, 0x198(a0) + fld fs4, 0x1A0(a0) + fld fs5, 0x1A8(a0) + fld fs6, 0x1B0(a0) + fld fs7, 0x1B8(a0) + fld fs8, 0x1C0(a0) + fld fs9, 0x1C8(a0) + fld fs10, 0x1D0(a0) + fld fs11, 0x1D8(a0) + fld ft8, 0x1E0(a0) + fld ft9, 0x1E8(a0) + fld ft10, 0x1F0(a0) + fld ft11, 0x1F8(a0) ", - // restore fp - " - fld ft0, 0x100(a0) - fld ft1, 0x108(a0) - fld ft2, 0x110(a0) - fld ft3, 0x118(a0) - fld ft4, 0x120(a0) - fld ft5, 0x128(a0) - fld ft6, 0x130(a0) - fld ft7, 0x138(a0) - fld fs0, 0x140(a0) - fld fs1, 0x148(a0) - fld fa0, 0x150(a0) - fld fa1, 0x158(a0) - fld fa2, 0x160(a0) - fld fa3, 0x168(a0) - fld fa4, 0x170(a0) - fld fa5, 0x178(a0) - fld fa6, 0x180(a0) - fld fa7, 0x188(a0) - fld fs2, 0x190(a0) - fld fs3, 0x198(a0) - fld fs4, 0x1A0(a0) - fld fs5, 0x1A8(a0) - fld fs6, 0x1B0(a0) - fld fs7, 0x1B8(a0) - fld fs8, 0x1C0(a0) - fld fs9, 0x1C8(a0) - fld fs10, 0x1D0(a0) - fld fs11, 0x1D8(a0) - fld ft8, 0x1E0(a0) - fld ft9, 0x1E8(a0) - fld ft10, 0x1F0(a0) - fld ft11, 0x1F8(a0) - ", - - "add sp, sp, 0x210", - "csrrw sp, sscratch, sp", - "sret", - - trap_handler = sym default_trap_handler, - options(noreturn) + "add sp, sp, 0x210", + "csrrw sp, sscratch, sp", + "sret", + + trap_handler = sym default_trap_handler, } } diff --git a/kernel/src/runtime/errors.rs b/kernel/src/runtime/errors.rs index 539de01d..17da4085 100644 --- a/kernel/src/runtime/errors.rs +++ b/kernel/src/runtime/errors.rs @@ -5,7 +5,7 @@ pub enum CompileError { #[error("Cranelift IR to machine code compilation failed {0}")] Compile(cranelift_codegen::CodegenError), } -impl<'a> From> for CompileError { +impl From> for CompileError { fn from(error: cranelift_codegen::CompileError) -> Self { Self::Compile(error.inner) } diff --git a/kernel/src/runtime/instance.rs b/kernel/src/runtime/instance.rs index 31cae885..db5947d7 100644 --- a/kernel/src/runtime/instance.rs +++ b/kernel/src/runtime/instance.rs @@ -53,7 +53,7 @@ impl Instance { data: &'a InstanceData<'wasm>, } - impl<'a, 'wasm> fmt::Debug for Dbg<'a, 'wasm> { + impl fmt::Debug for Dbg<'_, '_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { unsafe { f.debug_struct("VMContext") @@ -96,7 +96,7 @@ pub struct InstanceData<'wasm> { pub memories: PrimaryMap, } -impl<'wasm> InstanceData<'wasm> { +impl InstanceData<'_> { unsafe fn vmctx_magic(&self) -> u32 { *self.vmctx_plus_offset::(self.vmctx_plan.vmctx_magic()) } diff --git a/kernel/src/runtime/translate/func_env.rs b/kernel/src/runtime/translate/func_env.rs index 1e81a0e9..79466193 100644 --- a/kernel/src/runtime/translate/func_env.rs +++ b/kernel/src/runtime/translate/func_env.rs @@ -90,7 +90,7 @@ impl<'module_env, 'wasm> FunctionEnvironment<'module_env, 'wasm> { } } -impl<'module_env, 'wasm> TargetEnvironment for FunctionEnvironment<'module_env, 'wasm> { +impl TargetEnvironment for FunctionEnvironment<'_, '_> { fn target_config(&self) -> TargetFrontendConfig { self.isa.frontend_config() } @@ -113,7 +113,7 @@ impl<'module_env, 'wasm> TargetEnvironment for FunctionEnvironment<'module_env, } } -impl<'module_env, 'wasm> TypeConvert for FunctionEnvironment<'module_env, 'wasm> { +impl TypeConvert for FunctionEnvironment<'_, '_> { fn lookup_heap_type(&self, index: UnpackedIndex) -> WasmHeapType { todo!() } @@ -126,9 +126,7 @@ impl<'module_env, 'wasm> TypeConvert for FunctionEnvironment<'module_env, 'wasm> } } -impl<'module_env, 'wasm> cranelift_wasm::FuncEnvironment - for FunctionEnvironment<'module_env, 'wasm> -{ +impl cranelift_wasm::FuncEnvironment for FunctionEnvironment<'_, '_> { fn param_needs_stack_map(&self, _signature: &Signature, index: usize) -> bool { false } diff --git a/kernel/src/runtime/translate/mod.rs b/kernel/src/runtime/translate/mod.rs index 80d7029d..9ee14992 100644 --- a/kernel/src/runtime/translate/mod.rs +++ b/kernel/src/runtime/translate/mod.rs @@ -208,7 +208,7 @@ pub struct MemoryInitializer<'wasm> { pub bytes: &'wasm [u8], } -impl<'wasm> TranslatedModule<'wasm> { +impl TranslatedModule<'_> { pub fn num_imported_functions(&self) -> u32 { self.num_imported_functions } diff --git a/kernel/src/runtime/translate/module_env.rs b/kernel/src/runtime/translate/module_env.rs index d680489e..1ee67b3f 100644 --- a/kernel/src/runtime/translate/module_env.rs +++ b/kernel/src/runtime/translate/module_env.rs @@ -26,7 +26,7 @@ pub struct ModuleEnvironment<'a, 'wasm> { validator: &'a mut Validator, } -impl<'a, 'wasm> TypeConvert for ModuleEnvironment<'a, 'wasm> { +impl TypeConvert for ModuleEnvironment<'_, '_> { fn lookup_heap_type(&self, _index: UnpackedIndex) -> WasmHeapType { todo!() } diff --git a/libs/backtrace/src/lib.rs b/libs/backtrace/src/lib.rs index 203b6959..2a9cba70 100644 --- a/libs/backtrace/src/lib.rs +++ b/libs/backtrace/src/lib.rs @@ -27,7 +27,7 @@ impl<'a, 'data> Backtrace<'a, 'data> { // FIXME: This *will* dealock rn, since we can't log from within this impl // it will lead to a deadlock since we already hold the stdouts lock -impl<'a, 'data> fmt::Display for Backtrace<'a, 'data> { +impl fmt::Display for Backtrace<'_, '_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { writeln!(f, "stack backtrace:")?; let mut frame_idx = 0; diff --git a/libs/backtrace/src/symbolize.rs b/libs/backtrace/src/symbolize.rs index 002b981d..ab0136f1 100644 --- a/libs/backtrace/src/symbolize.rs +++ b/libs/backtrace/src/symbolize.rs @@ -18,7 +18,7 @@ pub enum Symbol<'a> { Symtab { name: &'a str }, } -impl<'a> Symbol<'a> { +impl Symbol<'_> { pub fn name(&self) -> Option> { match self { Symbol::Frame { name, .. } => { @@ -61,7 +61,7 @@ impl<'a> Symbol<'a> { } } -impl<'a> fmt::Debug for Symbol<'a> { +impl fmt::Debug for Symbol<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut d = f.debug_struct("Symbol"); d.field("name", &self.name()); @@ -93,7 +93,7 @@ impl<'a> SymbolName<'a> { } } -impl<'a> fmt::Display for SymbolName<'a> { +impl fmt::Display for SymbolName<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(ref s) = self.demangled { return s.fmt(f); @@ -103,7 +103,7 @@ impl<'a> fmt::Display for SymbolName<'a> { } } -impl<'a> fmt::Debug for SymbolName<'a> { +impl fmt::Debug for SymbolName<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(ref s) = self.demangled { return s.fmt(f); diff --git a/libs/dtb-parser/src/debug.rs b/libs/dtb-parser/src/debug.rs index ccb20dae..1ab14589 100644 --- a/libs/dtb-parser/src/debug.rs +++ b/libs/dtb-parser/src/debug.rs @@ -17,7 +17,7 @@ impl<'a, T: fmt::Write> DebugVisitor<'a, T> { } } -impl<'a, 'dt, T: fmt::Write> Visitor<'dt> for DebugVisitor<'a, T> { +impl<'dt, T: fmt::Write> Visitor<'dt> for DebugVisitor<'_, T> { type Error = Error; fn visit_subnode(&mut self, name: &'dt str, node: Node<'dt>) -> crate::Result<()> { diff --git a/libs/dtb-parser/src/lib.rs b/libs/dtb-parser/src/lib.rs index df11b7c3..451cdccd 100644 --- a/libs/dtb-parser/src/lib.rs +++ b/libs/dtb-parser/src/lib.rs @@ -239,7 +239,7 @@ pub struct ReserveEntries<'dt> { done: bool, } -impl<'dt> ReserveEntries<'dt> { +impl ReserveEntries<'_> { fn read_u64(&mut self) -> Result { let bytes = self .buf diff --git a/libs/kmm/src/alloc/bump.rs b/libs/kmm/src/alloc/bump.rs index eb788dbe..1d24054b 100644 --- a/libs/kmm/src/alloc/bump.rs +++ b/libs/kmm/src/alloc/bump.rs @@ -83,7 +83,7 @@ pub struct FreeRegions<'a> { inner: iter::Cloned>>>, } -impl<'a> Iterator for FreeRegions<'a> { +impl Iterator for FreeRegions<'_> { type Item = Range; fn next(&mut self) -> Option { @@ -109,7 +109,7 @@ pub struct UsedRegions<'a> { inner: iter::Cloned>>>, } -impl<'a> Iterator for UsedRegions<'a> { +impl Iterator for UsedRegions<'_> { type Item = Range; fn next(&mut self) -> Option { @@ -129,7 +129,7 @@ impl<'a> Iterator for UsedRegions<'a> { } } -impl<'a, M: Mode> FrameAllocator for BumpAllocator<'a, M> { +impl FrameAllocator for BumpAllocator<'_, M> { fn allocate_frames(&mut self, frames: usize) -> crate::Result { let requested_size = frames * M::PAGE_SIZE; let mut offset = self.offset; diff --git a/libs/kmm/src/elf.rs b/libs/kmm/src/elf.rs index ff80012f..7ae099a8 100644 --- a/libs/kmm/src/elf.rs +++ b/libs/kmm/src/elf.rs @@ -22,7 +22,7 @@ pub struct ElfMapper<'p, 'a, M> { virtual_base: VirtualAddress, } -impl<'p, 'a, M: Mode> ElfMapper<'p, 'a, M> { +impl ElfMapper<'_, '_, M> { /// Maps an ELF file into virtual memory. /// /// # Errors @@ -377,7 +377,7 @@ struct ProgramHeader<'a> { ph: &'a ProgramHeader64, } -impl<'a> ProgramHeader<'a> { +impl ProgramHeader<'_> { pub fn parse_rela(&self, elf_file: &ElfFile64) -> Option { if self.p_type == PT_DYNAMIC { let fields = self diff --git a/libs/ktest/src/run.rs b/libs/ktest/src/run.rs index c9a4443d..bc9481c4 100644 --- a/libs/ktest/src/run.rs +++ b/libs/ktest/src/run.rs @@ -115,7 +115,7 @@ pub struct MachineInfo<'dt> { } #[cfg(target_os = "none")] -impl<'dt> MachineInfo<'dt> { +impl MachineInfo<'_> { /// # Safety /// /// The caller has to ensure the provided pointer actually points to a FDT in memory. diff --git a/libs/leb128/src/lib.rs b/libs/leb128/src/lib.rs index c2436136..46fef8f5 100644 --- a/libs/leb128/src/lib.rs +++ b/libs/leb128/src/lib.rs @@ -61,7 +61,7 @@ pub trait Leb128Read { fn read_sleb128(&mut self) -> Result; } -impl<'a> Leb128Read for &'a [u8] { +impl Leb128Read for &'_ [u8] { fn read_byte(&mut self) -> Result { let (byte, rest) = self.split_first().ok_or(Error::UnexpectedEof)?; *self = rest; @@ -133,7 +133,7 @@ pub trait Leb128Write { fn write_sleb128(&mut self, val: i64) -> Result; } -impl<'a> Leb128Write for &'a mut [u8] { +impl Leb128Write for &'_ mut [u8] { #[inline] fn write_byte(&mut self, val: u8) -> Result<()> { let (a, b) = mem::take(self) diff --git a/libs/sync/src/once.rs b/libs/sync/src/once.rs index ed498e7a..80a77e96 100644 --- a/libs/sync/src/once.rs +++ b/libs/sync/src/once.rs @@ -131,7 +131,7 @@ struct PanicGuard<'a> { status: &'a AtomicU8, } -impl<'a> Drop for PanicGuard<'a> { +impl Drop for PanicGuard<'_> { fn drop(&mut self) { self.status.store(STATUS_POISONED, Ordering::Relaxed); } diff --git a/libs/unwind2/src/arch/riscv64.rs b/libs/unwind2/src/arch/riscv64.rs index 1696ce0f..b3139cee 100644 --- a/libs/unwind2/src/arch/riscv64.rs +++ b/libs/unwind2/src/arch/riscv64.rs @@ -1,5 +1,5 @@ //! RISC-V specific unwinding code, mostly saving and restoring registers. -use core::arch::asm; +use core::arch::{asm, naked_asm}; use core::fmt; use core::ops; use gimli::{Register, RiscV}; @@ -184,7 +184,7 @@ pub extern "C-unwind" fn save_context(f: extern "C" fn(&mut Context, *mut ()), p // No need to save caller-saved registers here. #[cfg(target_feature = "d")] unsafe { - asm! { + naked_asm! { " mv t0, sp add sp, sp, -0x210 @@ -203,13 +203,12 @@ pub extern "C-unwind" fn save_context(f: extern "C" fn(&mut Context, *mut ()), p .cfi_def_cfa_offset 0 .cfi_restore ra ret - ", - options(noreturn) + " }; } #[cfg(not(target_feature = "d"))] unsafe { - asm! { + naked_asm! { " mv t0, sp add sp, sp, -0x110 @@ -228,7 +227,6 @@ pub extern "C-unwind" fn save_context(f: extern "C" fn(&mut Context, *mut ()), p .cfi_restore ra ret ", - options(noreturn) }; } } diff --git a/libs/unwind2/src/eh_info.rs b/libs/unwind2/src/eh_info.rs index a51358dc..7b69c878 100644 --- a/libs/unwind2/src/eh_info.rs +++ b/libs/unwind2/src/eh_info.rs @@ -25,6 +25,7 @@ pub struct EhInfo { } pub static EH_INFO: LazyLock = LazyLock::new(|| { + #[allow(static_mut_refs)] let eh_frame_hdr = unsafe { get_unlimited_slice(EH_FRAME_HDR.as_ptr()) }; let mut bases = BaseAddresses::default().set_eh_frame_hdr(eh_frame_hdr.as_ptr() as u64); diff --git a/libs/wasm-encoder/src/component/types.rs b/libs/wasm-encoder/src/component/types.rs index 228a583e..3e327054 100644 --- a/libs/wasm-encoder/src/component/types.rs +++ b/libs/wasm-encoder/src/component/types.rs @@ -79,7 +79,7 @@ impl Encode for ModuleType { #[derive(Debug)] pub struct CoreTypeEncoder<'a>(pub(crate) &'a mut Vec); -impl<'a> CoreTypeEncoder<'a> { +impl CoreTypeEncoder<'_> { /// Define a function type. pub fn function(self, params: P, results: R) where diff --git a/libs/wast/src/component/component.rs b/libs/wast/src/component/component.rs index 7b77eb21..2a005120 100644 --- a/libs/wast/src/component/component.rs +++ b/libs/wast/src/component/component.rs @@ -30,7 +30,7 @@ pub enum ComponentKind<'a> { Binary(Vec<&'a [u8]>), } -impl<'a> Component<'a> { +impl Component<'_> { /// Performs a name resolution pass on this [`Component`], resolving all /// symbolic names to indices. /// @@ -158,7 +158,7 @@ pub enum ComponentField<'a> { } impl<'a> ComponentField<'a> { - fn parse_remaining(parser: Parser<'a>) -> Result> { + fn parse_remaining(parser: Parser<'a>) -> Result>> { let mut fields = Vec::new(); while !parser.is_empty() { fields.push(parser.parens(ComponentField::parse)?); diff --git a/libs/wast/src/component/import.rs b/libs/wast/src/component/import.rs index 6689f4a7..85f36811 100644 --- a/libs/wast/src/component/import.rs +++ b/libs/wast/src/component/import.rs @@ -80,7 +80,7 @@ impl<'a> Parse<'a> for ItemSigNoName<'a> { fn parse_item_sig<'a>(parser: Parser<'a>, name: bool) -> Result> { let mut l = parser.lookahead1(); - let (span, parse_kind): (_, fn(Parser<'a>) -> Result) = if l.peek::()? { + let (span, parse_kind): (_, fn(Parser<'a>) -> Result>) = if l.peek::()? { let span = parser.parse::()?.0; parser.parse::()?; (span, |parser| Ok(ItemSigKind::CoreModule(parser.parse()?))) diff --git a/libs/wast/src/component/item_ref.rs b/libs/wast/src/component/item_ref.rs index 5ee673ef..8cb18be7 100644 --- a/libs/wast/src/component/item_ref.rs +++ b/libs/wast/src/component/item_ref.rs @@ -65,7 +65,7 @@ impl<'a, K: Parse<'a>> Parse<'a> for CoreItemRef<'a, K> { } } -impl<'a, K: Peek> Peek for CoreItemRef<'a, K> { +impl Peek for CoreItemRef<'_, K> { fn peek(cursor: Cursor<'_>) -> Result { peek::(cursor) } @@ -102,7 +102,7 @@ impl<'a, K: Parse<'a>> Parse<'a> for ItemRef<'a, K> { } } -impl<'a, K: Peek> Peek for ItemRef<'a, K> { +impl Peek for ItemRef<'_, K> { fn peek(cursor: Cursor<'_>) -> Result { peek::(cursor) } diff --git a/libs/wast/src/core/binary.rs b/libs/wast/src/core/binary.rs index 2d271bc3..5555863a 100644 --- a/libs/wast/src/core/binary.rs +++ b/libs/wast/src/core/binary.rs @@ -400,7 +400,7 @@ impl Encode for Option> { } } -impl<'a> Encode for ValType<'a> { +impl Encode for ValType<'_> { fn encode(&self, e: &mut Vec) { match self { ValType::I32 => e.push(0x7f), @@ -415,7 +415,7 @@ impl<'a> Encode for ValType<'a> { } } -impl<'a> Encode for HeapType<'a> { +impl Encode for HeapType<'_> { fn encode(&self, e: &mut Vec) { match self { HeapType::Abstract { shared, ty } => { @@ -454,7 +454,7 @@ impl Encode for AbstractHeapType { } } -impl<'a> Encode for RefType<'a> { +impl Encode for RefType<'_> { fn encode(&self, e: &mut Vec) { match self { // Binary abbreviations (i.e., short form), for when the ref is @@ -490,7 +490,7 @@ impl<'a> Encode for RefType<'a> { } } -impl<'a> Encode for StorageType<'a> { +impl Encode for StorageType<'_> { fn encode(&self, e: &mut Vec) { match self { StorageType::I8 => e.push(0x78), @@ -555,7 +555,7 @@ impl Encode for Index<'_> { } } -impl<'a> Encode for TableType<'a> { +impl Encode for TableType<'_> { fn encode(&self, e: &mut Vec) { self.elem.encode(e); @@ -603,7 +603,7 @@ impl Encode for MemoryType { } } -impl<'a> Encode for GlobalType<'a> { +impl Encode for GlobalType<'_> { fn encode(&self, e: &mut Vec) { self.ty.encode(e); let mut flags = 0; @@ -1283,14 +1283,14 @@ impl Encode for Id<'_> { } } -impl<'a> Encode for TryTable<'a> { +impl Encode for TryTable<'_> { fn encode(&self, dst: &mut Vec) { self.block.encode(dst); self.catches.encode(dst); } } -impl<'a> Encode for TryTableCatch<'a> { +impl Encode for TryTableCatch<'_> { fn encode(&self, dst: &mut Vec) { let flag_byte: u8 = match self.kind { TryTableCatchKind::Catch(..) => 0, @@ -1321,7 +1321,7 @@ impl Encode for I8x16Shuffle { } } -impl<'a> Encode for SelectTypes<'a> { +impl Encode for SelectTypes<'_> { fn encode(&self, dst: &mut Vec) { match &self.tys { Some(list) => { diff --git a/libs/wast/src/core/expr.rs b/libs/wast/src/core/expr.rs index 5f42db44..8b870af9 100644 --- a/libs/wast/src/core/expr.rs +++ b/libs/wast/src/core/expr.rs @@ -165,7 +165,7 @@ enum If<'a> { } impl<'a> ExpressionParser<'a> { - fn new(parser: Parser<'a>) -> ExpressionParser { + fn new(parser: Parser<'a>) -> ExpressionParser<'a> { ExpressionParser { raw_instrs: Vec::new(), stack: Vec::new(), @@ -1204,7 +1204,7 @@ const _: () = { assert!(size <= pointer * 10); }; -impl<'a> Instruction<'a> { +impl Instruction<'_> { pub(crate) fn needs_data_count(&self) -> bool { matches!( self, diff --git a/libs/wast/src/core/module.rs b/libs/wast/src/core/module.rs index 19879063..36debef2 100644 --- a/libs/wast/src/core/module.rs +++ b/libs/wast/src/core/module.rs @@ -157,7 +157,7 @@ pub enum ModuleField<'a> { } impl<'a> ModuleField<'a> { - pub(crate) fn parse_remaining(parser: Parser<'a>) -> Result> { + pub(crate) fn parse_remaining(parser: Parser<'a>) -> Result>> { let mut fields = Vec::new(); while !parser.is_empty() { fields.push(parser.parens(ModuleField::parse)?); diff --git a/libs/wast/src/core/resolve/deinline_import_export.rs b/libs/wast/src/core/resolve/deinline_import_export.rs index f2f736d8..8823d72e 100644 --- a/libs/wast/src/core/resolve/deinline_import_export.rs +++ b/libs/wast/src/core/resolve/deinline_import_export.rs @@ -51,7 +51,7 @@ pub fn run(fields: &mut Vec) { // field here instead, switching this to a `Normal` memory. MemoryKind::Inline { is64, ref data } => { let len = data.iter().map(|l| l.len()).sum::() as u64; - let pages = (len + default_page_size() - 1) / default_page_size(); + let pages = len.div_ceil(default_page_size()); let kind = MemoryKind::Normal(MemoryType { limits: Limits { is64, diff --git a/libs/wast/src/core/types.rs b/libs/wast/src/core/types.rs index 308571e6..9af4dda3 100644 --- a/libs/wast/src/core/types.rs +++ b/libs/wast/src/core/types.rs @@ -47,7 +47,7 @@ impl<'a> Parse<'a> for ValType<'a> { } } -impl<'a> Peek for ValType<'a> { +impl Peek for ValType<'_> { fn peek(cursor: Cursor<'_>) -> Result { Ok(kw::i32::peek(cursor)? || kw::i64::peek(cursor)? @@ -97,7 +97,7 @@ impl<'a> Parse<'a> for HeapType<'a> { } } -impl<'a> Peek for HeapType<'a> { +impl Peek for HeapType<'_> { fn peek(cursor: Cursor<'_>) -> Result { Ok(AbstractHeapType::peek(cursor)? || (LParen::peek(cursor)? && kw::shared::peek2(cursor)?) @@ -460,7 +460,7 @@ impl<'a> Parse<'a> for RefType<'a> { } } -impl<'a> Peek for RefType<'a> { +impl Peek for RefType<'_> { fn peek(cursor: Cursor<'_>) -> Result { Ok(kw::funcref::peek(cursor)? || kw::externref::peek(cursor)? @@ -723,7 +723,7 @@ impl<'a> Parse<'a> for FunctionType<'a> { } } -impl<'a> Peek for FunctionType<'a> { +impl Peek for FunctionType<'_> { fn peek(cursor: Cursor<'_>) -> Result { if let Some(next) = cursor.lparen()? { match next.keyword()? { @@ -755,7 +755,7 @@ impl<'a> Parse<'a> for FunctionTypeNoNames<'a> { } } -impl<'a> Peek for FunctionTypeNoNames<'a> { +impl Peek for FunctionTypeNoNames<'_> { fn peek(cursor: Cursor<'_>) -> Result { FunctionType::peek(cursor) } @@ -946,7 +946,7 @@ pub struct Type<'a> { pub final_type: Option, } -impl<'a> Peek for Type<'a> { +impl Peek for Type<'_> { fn peek(cursor: Cursor<'_>) -> Result { kw::r#type::peek(cursor) } diff --git a/libs/wast/src/lexer.rs b/libs/wast/src/lexer.rs index 57bb327e..7222bb13 100644 --- a/libs/wast/src/lexer.rs +++ b/libs/wast/src/lexer.rs @@ -1171,7 +1171,7 @@ impl Token { } } -impl<'a> Integer<'a> { +impl Integer<'_> { /// Returns the sign token for this integer. pub fn sign(&self) -> Option { self.sign diff --git a/libs/wast/src/token.rs b/libs/wast/src/token.rs index 472c126f..6a1b1744 100644 --- a/libs/wast/src/token.rs +++ b/libs/wast/src/token.rs @@ -95,7 +95,7 @@ impl<'a> Id<'a> { } } -impl<'a> Hash for Id<'a> { +impl Hash for Id<'_> { fn hash(&self, hasher: &mut H) { self.name.hash(hasher); self.gen.hash(hasher); @@ -108,7 +108,7 @@ impl<'a> PartialEq for Id<'a> { } } -impl<'a> Eq for Id<'a> {} +impl Eq for Id<'_> {} impl<'a> Parse<'a> for Id<'a> { fn parse(parser: Parser<'a>) -> Result { @@ -255,7 +255,7 @@ impl<'a, K: Parse<'a>> Parse<'a> for ItemRef<'a, K> { } } -impl<'a, K: Peek> Peek for ItemRef<'a, K> { +impl Peek for ItemRef<'_, K> { fn peek(cursor: Cursor<'_>) -> Result { match cursor.lparen()? { Some(remaining) => K::peek(remaining), diff --git a/libs/wast/src/wast.rs b/libs/wast/src/wast.rs index 42fdf9ab..e93b0068 100644 --- a/libs/wast/src/wast.rs +++ b/libs/wast/src/wast.rs @@ -226,7 +226,7 @@ pub enum WastExecute<'a> { }, } -impl<'a> WastExecute<'a> { +impl WastExecute<'_> { /// Returns the first span for this execute statement. pub fn span(&self) -> Span { match self { diff --git a/loader/build.rs b/loader/build.rs index 5066747f..6d682493 100644 --- a/loader/build.rs +++ b/loader/build.rs @@ -2,7 +2,7 @@ use std::path::{Path, PathBuf}; use std::{env, fs}; fn main() { - let workspace_root = Path::new(env!("CARGO_RUSTC_CURRENT_DIR")); + let workspace_root = PathBuf::from(env::var_os("__K23_CARGO_RUSTC_CURRENT_DIR").unwrap()); let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); println!("cargo::rerun-if-env-changed=KERNEL"); diff --git a/loader/riscv64imac-k23-none-loader.json b/loader/riscv64imac-k23-none-loader.json index e871ed83..b1cb7326 100644 --- a/loader/riscv64imac-k23-none-loader.json +++ b/loader/riscv64imac-k23-none-loader.json @@ -8,11 +8,13 @@ "features": "+m,+a,+c", "linker": "rust-lld", "linker-flavor": "gnu-lld", + "llvm-abiname": "lp64", "llvm-target": "riscv64", "max-atomic-width": 64, "panic-strategy": "abort", "relocation-model": "static", "supported-sanitizers": [ + "shadow-call-stack", "kernel-address" ], "target-pointer-width": "64" diff --git a/loader/src/arch/riscv64.rs b/loader/src/arch/riscv64.rs index 5018f82c..f713d393 100644 --- a/loader/src/arch/riscv64.rs +++ b/loader/src/arch/riscv64.rs @@ -1,6 +1,6 @@ use crate::kconfig; use crate::machine_info::MachineInfo; -use core::arch::asm; +use core::arch::{asm, naked_asm}; use core::ops::Range; use core::ptr; use core::ptr::addr_of_mut; @@ -24,7 +24,7 @@ pub fn machine_info() -> &'static MachineInfo<'static> { #[no_mangle] #[naked] unsafe extern "C" fn _start() -> ! { - asm!( + naked_asm!( ".option push", ".option norelax", "la gp, __global_pointer$", @@ -44,7 +44,6 @@ unsafe extern "C" fn _start() -> ! { fillstack = sym fillstack, start_rust = sym start, - options(noreturn) ) } @@ -98,7 +97,7 @@ fn zero_bss() { /// expects the bottom of `stack_size` in `t0` and the top of stack in `sp` #[naked] unsafe extern "C" fn fillstack() { - asm!( + naked_asm!( "li t1, 0xACE0BACE", "sub t0, sp, t0", // subtract stack_size from sp to get the bottom of stack "100:", @@ -106,7 +105,6 @@ unsafe extern "C" fn fillstack() { "addi t0, t0, 8", "bltu t0, sp, 100b", "ret", - options(noreturn) ) } diff --git a/loader/src/boot_info.rs b/loader/src/boot_info.rs index 825b4359..9c033801 100644 --- a/loader/src/boot_info.rs +++ b/loader/src/boot_info.rs @@ -3,7 +3,7 @@ use crate::kernel::Kernel; use crate::paging::PageTableResult; use core::mem::MaybeUninit; use core::ops::Div; -use core::slice; +use core::{ptr, slice}; use kmm::{BumpAllocator, FrameAllocator, PhysicalAddress, VirtualAddress}; use loader_api::{BootInfo, MemoryRegion, MemoryRegionKind}; @@ -22,12 +22,7 @@ pub fn init_boot_info( // memory_regions: &'static mut [MemoryRegion] is a reference to physical memory, but going forward // we need it to be a reference to virtual memory. - let memory_regions = unsafe { - let ptr = memory_regions - .as_mut_ptr() - .byte_add(physical_memory_offset.as_raw()); - slice::from_raw_parts_mut(ptr, memory_regions.len()) - }; + let memory_regions = unsafe { phys_to_virt_mut(physical_memory_offset, memory_regions) }; let boot_info = unsafe { &mut *(frame.as_raw() as *mut MaybeUninit) }; let boot_info = boot_info.write(BootInfo::new( @@ -90,8 +85,30 @@ fn init_boot_info_memory_regions( unsafe { MaybeUninit::slice_assume_init_mut(&mut raw_regions[0..next_region]) } } -unsafe fn phys_to_virt_ref(physmem_off: VirtualAddress, phys: &T) -> &T { - let ptr = (phys as *const T).byte_add(physmem_off.as_raw()); +/// Convert a reference in physical memory to a reference in virtual memory. +/// +/// Note that `wrapping_byte_add` here is *crucial* since we're intentionally wrapping around +/// (from "positive" physmem addresses to "negavtive" kernelspace virtmem addresses). Previously, +/// we relied on the UB of LLVM to do the correct wrapping thing which obviously isn't great. +/// +/// # Safety +/// +/// well... nothing of this is safe, we're just wholesale making up new references. And references +/// we're actually not even allowed to touch until the MMU is turned on... Maybe we should change the +/// API to use only raw pointers instead... +unsafe fn phys_to_virt_ref(physmem_off: VirtualAddress, phys: &T) -> &T { + let ptr = (phys as *const T).wrapping_byte_add(physmem_off.as_raw()); &*ptr } + +/// Convert a mutable reference in physical memory to a reference in virtual memory. +/// +/// # Safety +/// +/// The same safety rules as [phys_to_virt_ref] apply. +unsafe fn phys_to_virt_mut(physmem_off: VirtualAddress, phys: &mut T) -> &mut T { + let ptr = ptr::from_mut(phys).wrapping_byte_add(physmem_off.as_raw()); + + &mut *ptr +} diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 62f4c3ce..34da33e5 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,5 +1,5 @@ [toolchain] -channel = "nightly-2024-08-15" +channel = "nightly-2024-11-20" components = ["rustfmt", "clippy", "rust-src", "llvm-tools"] targets = ["wasm32-unknown-unknown"] profile = "minimal"