diff --git a/Cargo.lock b/Cargo.lock index 72540ef06..4be73f2ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1508,6 +1508,16 @@ dependencies = [ "xous-names", ] +[[package]] +name = "svd2repl" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "convert_case", + "quick-xml", +] + [[package]] name = "svd2utra" version = "0.1.0" @@ -1922,7 +1932,7 @@ checksum = "b07db065a5cf61a7e4ba64f29e67db906fb1787316516c4e6e5ff0fea1efcd8a" [[package]] name = "xous" -version = "0.8.0" +version = "0.8.3" dependencies = [ "bitflags", "compiler_builtins", diff --git a/Cargo.toml b/Cargo.toml index 227c392de..aaf72aeeb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,6 +47,7 @@ members = [ "services/rkyv-test-server", "services/rkyv-test-client", "services/shellchat", + "svd2repl", "svd2utra", "xtask", "imports/blitstr-ref", diff --git a/docs/flash.md b/docs/flash.md index c3e1f863f..710f0d4fa 100644 --- a/docs/flash.md +++ b/docs/flash.md @@ -64,6 +64,37 @@ of wear leveling, however. +-----------+----------------------------------------+ ``` +The EC update block is further structured as follows: +``` ++-----------+----------------------------------------+ ++ 27F8_0000 | wf200 firmware control page | ++ +1000 | | ++-----------+----------------------------------------+ ++ 27F8_1000 | up to 311k for wf200 firmware | ++ +4_D000 | padded with trailing 0xFF | ++-----------+----------------------------------------+ ++ 27FC_E000 | EC firmware control page | ++ +1000 | | ++-----------+----------------------------------------+ ++ 27FC_F000 | up to 199k EC fw | ++ +3_1000 | padded with trailing 0xFF | ++-----------+----------------------------------------+ + +``` + +The firmware control pages have the following structure: +``` +base + 0x0000: [u8; 32] = SHA-512/256 hash from base+0x20 to last byte of firmware +base + 0x0020: [u8; 4] = EC: [0x70, 0x72, 0x65, 0x63]; // signature 'cerp' ('prec' in big endian) or WF200: [0x77, 0x66, 0x32, 0x30]; // 'wf20' +base + 0x0024: u32 = firmware control page version number (currently 1) +base + 0x0028: u32 = length of firmware in bytes, computed from start of first firmware page +base + 0x002c: [u8; 4052] = [0xff as u8; 4052] 0xff padding to start of first firmware page +base + 0x1000: [u8; FW_LEN] = actual firmware + +remainder of unused sectors are 0xff pad. The 0xff pad is not hashed for performance reasons, and should +be considered insecure/untrusted. +``` + The csr.csv block is further structured as follows: diff --git a/docs/memory.md b/docs/memory.md index 9b9a5c5ca..9e43fbf93 100644 --- a/docs/memory.md +++ b/docs/memory.md @@ -44,6 +44,7 @@ the need from ever switching back to process 1. Note that the kernel takes up a single 4 MB megapage, so it can be assigned to every process simply by mapping megapage 1023 (`0xffc00000`). +``` | Address | Description | ---------- | ----------- | 0x00100000 | Default entrypoint for riscv64-unknown-elf-ld (as shown by `riscv64-unknown-elf-ld --verbose`) @@ -54,12 +55,14 @@ assigned to every process simply by mapping megapage 1023 (`0xffc00000`). | 0xff801000 | Context data (registers, etc.) | 0xff802000 | Return address from syscalls (never allocated) | 0xffc00000 | Kernel arguments, allocation tables +| 0xffcd0000 | Kernel WFI CSR page | 0xffce0000 | Kernel TRNG CSR page | 0xffcf0000 | Supervisor UART CSR page | 0xffd00000 | Kernel binary image and data section | 0xfffefffc | "default" stack pointer (used by interrupt handlers) | 0xffff0000 | Kernel stack top | 0xfff00000 | {unused} +``` Note that the stack pointer is not necessarily fixed, and may be changed in a later revision. diff --git a/kernel/src/test/shutdown.rs b/emulation/peripherals/com_ec.cs similarity index 100% rename from kernel/src/test/shutdown.rs rename to emulation/peripherals/com_ec.cs diff --git a/emulation/peripherals/ticktimer.cs b/emulation/peripherals/ticktimer.cs index 4cb034876..0cfc588df 100644 --- a/emulation/peripherals/ticktimer.cs +++ b/emulation/peripherals/ticktimer.cs @@ -21,7 +21,7 @@ namespace Antmicro.Renode.Peripherals.Timers [AllowedTranslations(AllowedTranslation.ByteToDoubleWord)] public class TickTimer : BasicDoubleWordPeripheral, IKnownSize { - public TickTimer(Machine machine, ulong periodInMs) : base(machine) + public TickTimer(Machine machine, ulong periodInMs = 1) : base(machine) { machine.ClockSource.AddClockEntry(new ClockEntry(periodInMs, ClockEntry.FrequencyToRatio(this, 1000), OnTick, this, "TickTimer")); this.IRQ = new GPIO(); diff --git a/emulation/peripherals/trng_kernel.cs b/emulation/peripherals/trng_kernel.cs index 79c46d3c6..a34578c92 100644 --- a/emulation/peripherals/trng_kernel.cs +++ b/emulation/peripherals/trng_kernel.cs @@ -14,6 +14,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous { public BetrustedRNGKernel(Machine machine) : base(machine) { + this.IRQ = new GPIO(); DefineRegisters(); } @@ -35,6 +36,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous } private readonly PseudorandomNumberGenerator rng = EmulationManager.Instance.CurrentEmulation.RandomGenerator; + public GPIO IRQ { get; private set; } private enum Registers { diff --git a/emulation/peripherals/trng_server.cs b/emulation/peripherals/trng_server.cs index b05e03df7..88e58b5a4 100644 --- a/emulation/peripherals/trng_server.cs +++ b/emulation/peripherals/trng_server.cs @@ -14,6 +14,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous { public BetrustedRNGServer(Machine machine) : base(machine) { + this.IRQ = new GPIO(); DefineRegisters(); } @@ -35,6 +36,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous } private readonly PseudorandomNumberGenerator rng = EmulationManager.Instance.CurrentEmulation.RandomGenerator; + public GPIO IRQ { get; private set; } private enum Registers { diff --git a/emulation/soc/betrusted-soc.repl b/emulation/soc/betrusted-soc.repl index 2b2bbec39..4f81049e1 100644 --- a/emulation/soc/betrusted-soc.repl +++ b/emulation/soc/betrusted-soc.repl @@ -1,62 +1,115 @@ +// Renode Platform file generated by svd2repl +// This file is automatically generated cpu: CPU.VexRiscv @ sysbus cpuType: "rv32imac" privilegeArchitecture: PrivilegeArchitecture.Priv1_10 PerformanceInMips: 120 +// Platform Peripherals +// Unrecognized peripheral: reboot -uart: UART.LiteX_UART @ { - sysbus 0xF0004000 // shadow - } - -> cpu@1002 +// Unrecognized peripheral: crg -console: UART.LiteX_UART @ { - sysbus 0xF0006000 - } - -> cpu@1003 +// Unrecognized peripheral: gpio -app_uart: UART.LiteX_UART @ { - sysbus 0xF0008000 - } - -> cpu@1004 +uart: UART.LiteX_UART @ sysbus 0xf0004000 + -> cpu @ 1002 -timer0: Timers.LiteX_Timer_32 @ { - sysbus 0xF0022000 - } - frequency: 100000000 - -> cpu@1001 +console: UART.LiteX_UART @ sysbus 0xf0006000 + -> cpu @ 1003 -rom: Memory.MappedMemory @ { - sysbus 0x00000000; - sysbus 0x80000000 // shadow - } - size: 0x00002000 +app_uart: UART.LiteX_UART @ sysbus 0xf0008000 + -> cpu @ 1004 -sram: Memory.MappedMemory @ { - sysbus 0x40000000; - sysbus 0x90000000 // shadow - } - size: 16777216 +// Unrecognized peripheral: info -fbmem: Memory.MappedMemory @ sysbus 0xB0000000 - size: 0x6000 +// Unrecognized peripheral: sram_ext -memlcd: Video.BetrustedLCD @ sysbus 0xF000B000 +memlcd: Video.BetrustedLCD @ sysbus 0xf000b000 -keyboard: Input.BetrustedKbd @ sysbus 0xF0015000 - -> cpu @ 1011 +// Unrecognized peripheral: com -trng_kernel: Miscellaneous.BetrustedRNGKernel @ sysbus 0xF001A000 +// Unrecognized peripheral: i2c -trng_server: Miscellaneous.BetrustedRNGServer @ sysbus 0xF001B000 +// Unrecognized peripheral: btevents -ticktimer: Timers.TickTimer @ sysbus 0xF0011000 - periodInMs: 1 +// Unrecognized peripheral: messible + +// Unrecognized peripheral: messible2 + +ticktimer: Timers.TickTimer @ sysbus 0xf0011000 -> cpu @ 1008 -flash_mem: Memory.MappedMemory @ { - sysbus 0x20000000; - sysbus 0xA0000000 // shadow - } - size: 0x8000000 +// Unrecognized peripheral: susres + +// Unrecognized peripheral: power + +// Unrecognized peripheral: spinor + +keyboard: Input.BetrustedKbd @ sysbus 0xf0015000 + -> cpu @ 1011 + +// Unrecognized peripheral: keyinject + +// Unrecognized peripheral: seed + +// Unrecognized peripheral: keyrom + +// Unrecognized peripheral: audio + +trng_kernel: Miscellaneous.BetrustedRNGKernel @ sysbus 0xf001a000 + -> cpu @ 1013 + +trng_server: Miscellaneous.BetrustedRNGServer @ sysbus 0xf001b000 + -> cpu @ 1014 + +// Unrecognized peripheral: trng + +// Unrecognized peripheral: sha512 + +// Unrecognized peripheral: engine + +// Unrecognized peripheral: jtag + +// Unrecognized peripheral: wdt + +// Unrecognized peripheral: d11ctime + +// Unrecognized peripheral: identifier_mem + +timer0: Timers.LiteX_Timer_32 @ sysbus 0xf0023000 + frequency: 100000000 + -> cpu @ 1000 + + +// Physical base addresses of memory regions +rom: Memory.MappedMemory @ sysbus 0x00000000 + size: 0x00008000 + +sram: Memory.MappedMemory @ sysbus 0x10000000 + size: 0x00020000 + +vexriscv_debug: Memory.MappedMemory @ sysbus 0xefff0000 + size: 0x00001000 + +sram_ext: Memory.MappedMemory @ sysbus 0x40000000 + size: 0x01000000 + +fbmem: Memory.MappedMemory @ sysbus 0xb0000000 + size: 0x00006000 + +spiflash: Memory.MappedMemory @ sysbus 0x20000000 + size: 0x08000000 + +audio: Memory.MappedMemory @ sysbus 0xe0000000 + size: 0x00001000 + +sha512: Memory.MappedMemory @ sysbus 0xe0002000 + size: 0x00001000 + +engine: Memory.MappedMemory @ sysbus 0xe0020000 + size: 0x00020000 + + sysbus: init: diff --git a/kernel/Cargo.lock b/kernel/Cargo.lock index 9748665a6..4c81f94ce 100644 --- a/kernel/Cargo.lock +++ b/kernel/Cargo.lock @@ -247,7 +247,7 @@ checksum = "67c21572b4949434e4fc1e1978b99c5f77064153c59d998bf13ecd96fb5ecba7" [[package]] name = "kernel" -version = "0.8.0" +version = "0.8.2" dependencies = [ "bitflags", "crossbeam-channel", @@ -551,7 +551,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "xous" -version = "0.8.0" +version = "0.8.3" dependencies = [ "bitflags", "hex", diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index 32d347566..1678c004a 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -1,18 +1,18 @@ [package] -name = "kernel" -version = "0.8.0" authors = ["Sean Cross "] -edition = "2018" description = "Core kernel for Xous, including task switching and memory management" +edition = "2018" +name = "kernel" +version = "0.8.2" [dependencies] bitflags = "1.2.1" -xous-kernel = { package = "xous", path = "../xous-rs", features = ["forget-memory-messages"] } -stats_alloc = { version = "0.1.8", optional = true } -sha3 = { default-features = false, version = "0.8.2" } +sha3 = {default-features = false, version = "0.8.2"} +stats_alloc = {version = "0.1.8", optional = true} +xous-kernel = {package = "xous", path = "../xous-rs", features = ["forget-memory-messages"]} [target.'cfg(not(any(windows, unix)))'.dependencies] -utralib = { path = "../utralib"} +utralib = {path = "../utralib"} [target.'cfg(target_arch = "riscv32")'.dependencies] riscv = "0.5.6" @@ -22,15 +22,15 @@ debug-print = [] print-panics = [] report-memory = ["stats_alloc"] wrap-print = [] -#default = ["print-panics", "debug-print"] +# default = ["print-panics", "debug-print", "wrap-print"] default = ["print-panics"] [target.'cfg(any(windows, unix))'.dependencies] +crossbeam-channel = "0.5" +debug-here = "0.2.2" +hex = "0.4" lazy_static = "1.4" rand = "0.7" -hex = "0.4" -debug-here = "0.2.2" -crossbeam-channel = "0.5" [profile.release] codegen-units = 1 # 1 better optimizations diff --git a/kernel/src/arch/hosted.rs b/kernel/src/arch/hosted.rs index 7750cdc78..4a30a817c 100644 --- a/kernel/src/arch/hosted.rs +++ b/kernel/src/arch/hosted.rs @@ -241,7 +241,12 @@ fn handle_connection( | xous_kernel::Message::BlockingScalar(_) => (), } } - SysCall::ReturnMemory(ref _sender, ref mut buf, ref _offset, ref _valid) => { + SysCall::ReturnMemory( + ref _sender, + ref mut buf, + ref _offset, + ref _valid, + ) => { let sliced_data = data.into_boxed_slice(); assert_eq!( sliced_data.len(), @@ -275,7 +280,7 @@ fn handle_connection( chn.send(ThreadMessage::SysCall( pid, 1, - xous_kernel::SysCall::TerminateProcess, + xous_kernel::SysCall::TerminateProcess(0), )) .unwrap(); } @@ -537,7 +542,7 @@ pub fn idle() -> bool { // If the call being made is to terminate the current process, we need to know // because we won't be able to send a response. - let is_terminate = call == SysCall::TerminateProcess; + let is_terminate = call == SysCall::TerminateProcess(0); let is_shutdown = call == SysCall::Shutdown; // For a "Shutdown" command, send the response before we issue the shutdown. @@ -557,7 +562,7 @@ pub fn idle() -> bool { "Unable to send response to process: {:?} -- terminating", _e ); - crate::syscall::handle(pid, thread_id, false, SysCall::TerminateProcess) + crate::syscall::handle(pid, thread_id, false, SysCall::TerminateProcess(0)) .ok(); }); // println!("KERNEL: Done sending"); @@ -599,7 +604,7 @@ pub fn idle() -> bool { "KERNEL({}): Unable to send response to process: {:?} -- terminating", pid, _e ); - crate::syscall::handle(pid, thread_id, false, SysCall::TerminateProcess) + crate::syscall::handle(pid, thread_id, false, SysCall::TerminateProcess(0)) .ok(); }); crate::arch::process::set_current_pid(existing_pid); diff --git a/kernel/src/arch/hosted/irq.rs b/kernel/src/arch/hosted/irq.rs index 5151506a4..7b5c3060a 100644 --- a/kernel/src/arch/hosted/irq.rs +++ b/kernel/src/arch/hosted/irq.rs @@ -1,10 +1,14 @@ // SPDX-FileCopyrightText: 2020 Sean Cross // SPDX-License-Identifier: Apache-2.0 -use xous_kernel::{TID, PID}; +use xous_kernel::{PID, TID}; pub fn enable_irq(_irq_no: usize) { - unimplemented!(); + unimplemented!() +} + +pub fn disable_irq(_irq_no: usize) -> Result<(), xous_kernel::Error> { + unimplemented!() } pub unsafe fn set_isr_return_pair(_pid: PID, _ctx: TID) { diff --git a/kernel/src/arch/hosted/mem.rs b/kernel/src/arch/hosted/mem.rs index 8de7dd72f..b301b1b9a 100644 --- a/kernel/src/arch/hosted/mem.rs +++ b/kernel/src/arch/hosted/mem.rs @@ -100,10 +100,6 @@ pub fn return_page_inner( unimplemented!() } -pub fn ensure_page_exists_inner(address: usize) -> Result { - unimplemented!() -} - pub fn unmap_page_inner(_mm: &mut MemoryManager, virt: usize) -> Result { Ok(virt) } diff --git a/kernel/src/arch/hosted/process.rs b/kernel/src/arch/hosted/process.rs index d2ba45a15..5f458c4c7 100644 --- a/kernel/src/arch/hosted/process.rs +++ b/kernel/src/arch/hosted/process.rs @@ -272,6 +272,10 @@ impl Process { }) } + pub fn thread_exists(&self, _tid: TID) -> bool { + false + } + pub fn set_thread_result(&mut self, tid: TID, result: xous_kernel::Result) { assert!(tid > 0); PROCESS_TABLE.with(|pt| { diff --git a/kernel/src/arch/mod.rs b/kernel/src/arch/mod.rs index fc75c7869..370c6a380 100644 --- a/kernel/src/arch/mod.rs +++ b/kernel/src/arch/mod.rs @@ -1,9 +1,9 @@ // SPDX-FileCopyrightText: 2020 Sean Cross // SPDX-License-Identifier: Apache-2.0 -#[cfg(any(windows,unix))] +#[cfg(any(windows, unix))] mod hosted; -#[cfg(any(windows,unix))] +#[cfg(any(windows, unix))] pub use hosted::*; #[cfg(target_arch = "riscv32")] @@ -16,7 +16,7 @@ mod riscv; #[cfg(all(target_arch = "riscv64", not(target_os = "xous")))] pub use riscv::*; -#[cfg(all(target_arch = "x86_64", not(any(windows,unix))))] +#[cfg(all(target_arch = "x86_64", not(any(windows, unix))))] mod x86_64; -#[cfg(all(target_arch = "x86_64", not(any(windows,unix))))] +#[cfg(all(target_arch = "x86_64", not(any(windows, unix))))] pub use x86_64::*; diff --git a/kernel/src/arch/riscv.rs b/kernel/src/arch/riscv.rs index 69ecc4085..ac1d1fb99 100644 --- a/kernel/src/arch/riscv.rs +++ b/kernel/src/arch/riscv.rs @@ -60,7 +60,7 @@ pub fn idle() -> bool { // Issue `wfi`. This will return as soon as an external interrupt // is available. if false { - // "traditional" path for stopping a clock + // "traditional" path for stopping a clock - effectively a NOP, doesn't do anything unsafe { riscv::asm::wfi() }; } else { // this invokes Precusor-SoC specific path to gate clocks: diff --git a/kernel/src/arch/riscv/exception.rs b/kernel/src/arch/riscv/exception.rs index c74949787..fbe668069 100644 --- a/kernel/src/arch/riscv/exception.rs +++ b/kernel/src/arch/riscv/exception.rs @@ -213,9 +213,7 @@ impl RiscvException { 15 => StorePageFault(epc, tval), x @ 10 | x @ 14 | x @ 16..=0x7fffffff => ReservedFault(x, epc, tval), - x => { - ReservedInterrupt(x & 0x7fffffff, epc) - } + x => ReservedInterrupt(x & 0x7fffffff, epc), } } } diff --git a/kernel/src/arch/riscv/irq.rs b/kernel/src/arch/riscv/irq.rs index 3f84ddd14..3cff1d6f8 100644 --- a/kernel/src/arch/riscv/irq.rs +++ b/kernel/src/arch/riscv/irq.rs @@ -4,7 +4,7 @@ use crate::arch::current_pid; use crate::arch::mem::MemoryMapping; use crate::arch::process::Process as ArchProcess; -use crate::arch::process::{Thread, RETURN_FROM_ISR}; +use crate::arch::process::{Thread, EXIT_THREAD, RETURN_FROM_ISR}; use crate::services::SystemServices; use riscv::register::{scause, sepc, sstatus, stval, vexriscv::sim, vexriscv::sip}; use xous_kernel::{SysCall, PID, TID}; @@ -77,7 +77,7 @@ pub extern "C" fn trap_handler( panic!("Ran out of kernel stack"); } - let pid = crate::arch::current_pid(); + let pid = current_pid(); if (sc.bits() == 9) || (sc.bits() == 8) { // We got here because of an `ecall` instruction. When we return, skip @@ -149,6 +149,18 @@ pub extern "C" fn trap_handler( ); println!("Page was not allocated"); } + RiscvException::InstructionPageFault(EXIT_THREAD, _offset) => { + let tid = ArchProcess::with_current(|process| process.current_tid()); + + // This address indicates a thread has exited. Destroy the thread. + // This activates another thread within this process. + SystemServices::with_mut(|ss| ss.destroy_thread(pid, tid)).unwrap(); + + // Resume the new thread within the same process. + ArchProcess::with_current_mut(|p| { + crate::arch::syscall::resume(current_pid().get() == 1, p.current_thread()) + }); + } RiscvException::InstructionPageFault(RETURN_FROM_ISR, _offset) => { // If we hit this address, then an ISR has just returned. Since // we're in an interrupt context, it is safe to access this diff --git a/kernel/src/arch/riscv/mem.rs b/kernel/src/arch/riscv/mem.rs index db14954cb..34e6a6fbb 100644 --- a/kernel/src/arch/riscv/mem.rs +++ b/kernel/src/arch/riscv/mem.rs @@ -21,6 +21,15 @@ extern "C" { fn flush_mmu(); } +pub unsafe fn memset(s: *mut u8, c: i32, n: usize) -> *mut u8 { + let mut i = 0; + while i < n { + *s.offset(i as isize) = c as u8; + i += 1; + } + s +} + bitflags! { pub struct MMUFlags: usize { const NONE = 0b00_0000_0000; @@ -199,7 +208,7 @@ impl MemoryMapping { // Zero-out the new page let page_addr = l0pt_virt as *mut usize; - unsafe { page_addr.write_bytes(0, PAGE_SIZE / core::mem::size_of::()) }; + unsafe { memset(page_addr as *mut u8, 0, PAGE_SIZE) }; } let ref mut l0_pt = unsafe { &mut (*(l0pt_virt as *mut LeafPageTable)) }; @@ -337,46 +346,52 @@ pub fn map_page_inner( assert!((virt & 0xfff) == 0); // The root (l1) pagetable is defined to be mapped into our virtual - // address space at this address. - let l1_pt = unsafe { &mut (*(PAGE_TABLE_ROOT_OFFSET as *mut RootPageTable)) }; - let ref mut l1_pt = l1_pt.entries; + // address space at 0xff80_0000. + let l1_pt = PAGE_TABLE_ROOT_OFFSET as *mut usize; // Subsequent pagetables are defined as being mapped starting at - // offset 0x0020_0004, so 4 must be added to the ppn1 value. - let l0pt_virt = PAGE_TABLE_OFFSET + vpn1 * PAGE_SIZE; - let ref mut l0_pt = unsafe { &mut (*(l0pt_virt as *mut LeafPageTable)) }; + // offset 0xff40_0000. + let l0_pt = (PAGE_TABLE_OFFSET + vpn1 * PAGE_SIZE) as *mut usize; // Allocate a new level 1 pagetable entry if one doesn't exist. - if l1_pt[vpn1 as usize] & MMUFlags::VALID.bits() == 0 { - // Allocate a fresh page - let l0pt_phys = mm.alloc_page(pid)?; + if unsafe { l1_pt.add(vpn1).read_volatile() } & MMUFlags::VALID.bits() == 0 { + // Allocate a fresh page for the level 1 page table. + let l0_pt_phys = mm.alloc_page(pid)?; // Mark this entry as a leaf node (WRX as 0), and indicate // it is a valid page by setting "V". - l1_pt[vpn1 as usize] = ((l0pt_phys >> 12) << 10) | MMUFlags::VALID.bits(); - unsafe { flush_mmu() }; + unsafe { + l1_pt + .add(vpn1) + .write_volatile(((l0_pt_phys >> 12) << 10) | MMUFlags::VALID.bits()); + flush_mmu(); + } // Map the new physical page to the virtual page, so we can access it. map_page_inner( mm, pid, - l0pt_phys, - l0pt_virt, + l0_pt_phys, + l0_pt as usize, MemoryFlags::W | MemoryFlags::R, false, )?; // Zero-out the new page - let page_addr = l0pt_virt as *mut usize; - unsafe { page_addr.write_bytes(0, PAGE_SIZE / core::mem::size_of::()) }; + unsafe { memset(l0_pt as *mut u8, 0, PAGE_SIZE) }; } // Ensure the entry hasn't already been mapped. - if l0_pt.entries[vpn0 as usize] & 1 != 0 { + if unsafe { l0_pt.add(vpn0).read_volatile() } & 1 != 0 { panic!("Page {:08x} already allocated!", virt); } - l0_pt.entries[vpn0 as usize] = - (ppn1 << 20) | (ppn0 << 10) | (flags | MMUFlags::VALID | MMUFlags::D | MMUFlags::A).bits(); + unsafe { + l0_pt.add(vpn0).write_volatile( + (ppn1 << 20) + | (ppn0 << 10) + | (flags | MMUFlags::VALID | MMUFlags::D | MMUFlags::A).bits(), + ) + }; unsafe { flush_mmu() }; Ok(()) @@ -462,6 +477,16 @@ pub fn move_page_inner( result } +/// Determine if a page has been lent. +pub fn page_is_lent(src_addr: *mut u8) -> bool { + let entry = if let Ok(val) = pagetable_entry(src_addr as usize) { + val + } else { + return false; + }; + *entry & MMUFlags::S.bits() != 0 +} + /// Mark the given virtual address as being lent. If `writable`, clear the /// `valid` bit so that this process can't accidentally write to this page while /// it is lent. @@ -650,7 +675,7 @@ pub fn ensure_page_exists_inner(address: usize) -> Result()); + memset(virt as *mut u8, 0, PAGE_SIZE); // Move the page into userspace *entry = (ppn1 << 20) diff --git a/kernel/src/arch/riscv/process.rs b/kernel/src/arch/riscv/process.rs index ec7824101..40de6608f 100644 --- a/kernel/src/arch/riscv/process.rs +++ b/kernel/src/arch/riscv/process.rs @@ -19,7 +19,7 @@ pub const MAX_PROCESS_COUNT: usize = 64; pub const RETURN_FROM_ISR: usize = 0xff80_2000; /// This is the address a thread will return to when it exits. -const EXIT_THREAD: usize = 0xff80_3000; +pub const EXIT_THREAD: usize = 0xff80_3000; // Thread IDs have three possible meaning: // Logical Thread ID: What the user sees @@ -35,13 +35,16 @@ const EXIT_THREAD: usize = 0xff80_3000; // Therefore, the first Logical Thread ID is 1, which maps // to Hardware Thread ID 2, which is Thread Context Index 1. // -// +----------------+---------------+------------------+ -// | Logical Thread | Context Index | Hardware Thread | -// +================+===============+==================+ -// | ISR Context | 0 | 1 | -// | 1 | 1 | 2 | -// | 2 | 2 | 3 | +// +-----------------+-----------------+-----------------+ +// | Thread ID | Context Index | Hardware Thread | +// +=================+=================+=================+ +// | ISR Context | 0 | 1 | +// | 1 | 1 | 2 | +// | 2 | 2 | 3 | +// ProcessImpl occupies a multiple of pages mapped to virtual address `0xff80_1000`. +// Each thread is 128 bytes (32 4-byte registers). The first "thread" does not exist, +// and instead is any bookkeeping information related to the process. #[derive(Debug, Copy, Clone)] #[repr(C)] struct ProcessImpl { @@ -70,16 +73,13 @@ struct ProcessTable { /// The process upon which the current syscall is operating current: PID, - /// The number of processes that exist - // total: usize, - - /// The actual table contents + /// The actual table contents. `true` if a process is allocated, + /// `false` if it is free. table: [bool; MAX_PROCESS_COUNT], } static mut PROCESS_TABLE: ProcessTable = ProcessTable { current: unsafe { PID::new_unchecked(1) }, - // total: 0, table: [false; MAX_PROCESS_COUNT], }; @@ -185,6 +185,10 @@ impl Process { process.hardware_thread - 1 } + pub fn thread_exists(&self, tid: TID) -> bool { + self.thread(tid).sepc != 0 + } + /// Set the current thread number. pub fn set_thread(&mut self, thread: TID) -> Result<(), xous_kernel::Error> { let mut process = unsafe { &mut *PROCESS }; @@ -208,15 +212,15 @@ impl Process { &mut process.threads[thread] } - // pub fn thread(&self, thread: TID) -> &Thread { - // let process = unsafe { &mut *PROCESS }; - // assert!( - // thread <= process.threads.len(), - // "attempt to retrieve an invalid thread {}", - // thread - // ); - // &process.threads[thread] - // } + pub fn thread(&self, thread: TID) -> &Thread { + let process = unsafe { &mut *PROCESS }; + assert!( + thread <= process.threads.len(), + "attempt to retrieve an invalid thread {}", + thread + ); + &process.threads[thread] + } pub fn find_free_thread(&self) -> Option { let process = unsafe { &mut *PROCESS }; @@ -353,6 +357,38 @@ impl Process { Ok(()) } + /// Destroy a given thread and return its return value. + /// + /// # Returns + /// The return value of the function + /// + /// # Errors + /// xous::ThreadNotAvailable - the thread did not exist + pub fn destroy_thread(&mut self, tid: TID) -> Result { + let thread = self.thread_mut(tid); + + // Ensure this thread is valid + if thread.sepc == 0 || tid == IRQ_TID { + Err(xous_kernel::Error::ThreadNotAvailable)?; + } + + // thread.registers[0] == x1 + // thread.registers[1] == x2 + // ... + // thread.registers[4] == x5 == t0 + // ... + // thread.registers[9] == x10 == a0 + // thread.registers[10] == x11 == a1 + let return_value = thread.registers[9]; + + for val in &mut thread.registers { + *val = 0; + } + thread.sepc = 0; + + Ok(return_value) + } + pub fn print_all_threads(&self) { let process = unsafe { &mut *PROCESS }; &mut process.threads[process.hardware_thread - 1]; @@ -432,17 +468,30 @@ impl Process { todo!(); } - pub fn destroy(_pid: PID) -> Result<(), xous_kernel::Error> { - todo!(); - // let mut process_table = unsafe { &mut *PROCESS }; - // let pid_idx = pid.get() as usize - 1; - // if pid_idx >= process_table.table.len() { - // panic!("attempted to destroy PID that exceeds table index: {}", pid); - // } - // let process = process_table.table[pid_idx].as_mut().unwrap(); - // process_table.table[pid_idx] = None; - // process_table.total -= 1; - // Ok(()) + pub fn destroy(pid: PID) -> Result<(), xous_kernel::Error> { + let mut process_table = unsafe { &mut PROCESS_TABLE }; + let pid_idx = pid.get() as usize - 1; + if pid_idx >= process_table.table.len() { + panic!("attempted to destroy PID that exceeds table index: {}", pid); + } + process_table.table[pid_idx] = false; + Ok(()) + } + + pub fn find_thread(&self, op: F) -> Option<(TID, &mut Thread)> + where + F: Fn(TID, &Thread) -> bool, + { + let process = unsafe { &mut *PROCESS }; + for (idx, thread) in process.threads.iter_mut().enumerate() { + if thread.sepc == 0 { + continue; + } + if op(idx, thread) { + return Some((idx, thread)); + } + } + None } } @@ -451,6 +500,15 @@ impl Thread { pub fn stack_pointer(&self) -> usize { self.registers[1] } + + pub fn a0(&self) -> usize { + self.registers[9] + } + + pub fn a1(&self) -> usize { + self.registers[10] + } + } pub fn set_current_pid(pid: PID) { @@ -473,31 +531,3 @@ pub fn current_pid() -> PID { pub fn current_tid() -> TID { unsafe { ((*PROCESS).hardware_thread) - 1 } } - -// pub struct ProcessHandle<'a> { -// process: &'a mut Process, -// } - -// /// Wraps the MemoryManager in a safe mutex. Because of this, accesses -// /// to the Memory Manager should only be made during interrupt contexts. -// impl<'a> ProcessHandle<'a> { -// /// Get the singleton Process. -// pub fn get() -> ProcessHandle<'a> { -// ProcessHandle { -// process: unsafe { &mut *PROCESS }, -// } -// } -// } - -// use core::ops::{Deref, DerefMut}; -// impl Deref for ProcessHandle<'_> { -// type Target = Process; -// fn deref(&self) -> &Process { -// &*self.process -// } -// } -// impl DerefMut for ProcessHandle<'_> { -// fn deref_mut(&mut self) -> &mut Process { -// &mut *self.process -// } -// } diff --git a/kernel/src/arch/riscv/rand.rs b/kernel/src/arch/riscv/rand.rs index 1491696ee..67eb501a5 100644 --- a/kernel/src/arch/riscv/rand.rs +++ b/kernel/src/arch/riscv/rand.rs @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: 2020 Sean Cross // SPDX-License-Identifier: Apache-2.0 -use utralib::generated::*; use crate::mem::MemoryManager; +use utralib::generated::*; use xous_kernel::{MemoryFlags, MemoryType, PID}; pub const TRNG_KERNEL: Trng = Trng { diff --git a/kernel/src/arch/x86_64.rs b/kernel/src/arch/x86_64.rs index 4e6c17ef7..1c5d4e326 100644 --- a/kernel/src/arch/x86_64.rs +++ b/kernel/src/arch/x86_64.rs @@ -53,7 +53,7 @@ pub mod syscall { pub mod mem { use crate::mem::MemoryManager; - use xous::{MemoryFlags, Error, PID}; + use xous::{Error, MemoryFlags, PID}; #[derive(Copy, Clone, Default, PartialEq)] pub struct MemoryMapping {} impl MemoryMapping { @@ -101,10 +101,7 @@ pub mod mem { unimplemented!(); } - pub fn unmap_page_inner( - mm: &mut MemoryManager, - virt: usize, - ) -> Result { + pub fn unmap_page_inner(mm: &mut MemoryManager, virt: usize) -> Result { unimplemented!(); } diff --git a/kernel/src/args.rs b/kernel/src/args.rs index acab328ce..862c0ead1 100644 --- a/kernel/src/args.rs +++ b/kernel/src/args.rs @@ -28,7 +28,9 @@ pub struct KernelArgumentsIterator { #[allow(dead_code)] impl KernelArguments { pub fn get() -> Self { - KernelArguments { base: unsafe { KERNEL_ARGUMENTS_BASE } } + KernelArguments { + base: unsafe { KERNEL_ARGUMENTS_BASE }, + } } pub unsafe fn init(base: *const u32) { @@ -58,14 +60,8 @@ pub struct KernelArgument { impl KernelArgument { pub fn new(base: *const u32, offset: usize) -> Self { let name = unsafe { base.add(offset / 4).read() } as u32; - let size = unsafe { - (base.add(offset / 4 + 1) as *const u16) - .add(1) - .read() - } as usize; - let data = unsafe { - core::slice::from_raw_parts(base.add(offset / 4 + 2), size) - }; + let size = unsafe { (base.add(offset / 4 + 1) as *const u16).add(1).read() } as usize; + let data = unsafe { core::slice::from_raw_parts(base.add(offset / 4 + 2), size) }; KernelArgument { name, size: size * 4, diff --git a/kernel/src/debug.rs b/kernel/src/debug.rs index a35b37cdc..7d85a4c0b 100644 --- a/kernel/src/debug.rs +++ b/kernel/src/debug.rs @@ -60,9 +60,7 @@ macro_rules! println } #[cfg(baremetal)] -pub struct Uart { - // pub base: *mut usize, -} +pub struct Uart {} #[cfg(baremetal)] static mut INITIALIZED: bool = false; @@ -140,7 +138,11 @@ pub fn irq(_irq_number: usize, _arg: *mut usize) { let current_pid = system_services.current_pid(); for process in &system_services.processes { if !process.free() { - println!("PID {} {}:", process.pid, system_services.process_name(process.pid).unwrap_or("")); + println!( + "PID {} {}:", + process.pid, + system_services.process_name(process.pid).unwrap_or("") + ); process.activate().unwrap(); crate::arch::mem::MemoryMapping::current().print_map(); println!(); @@ -159,7 +161,11 @@ pub fn irq(_irq_number: usize, _arg: *mut usize) { let current_pid = system_services.current_pid(); for process in &system_services.processes { if !process.free() { - println!("PID {} {}:", process.pid, system_services.process_name(process.pid).unwrap_or("")); + println!( + "{:?} {}:", + process, + system_services.process_name(process.pid).unwrap_or("") + ); process.activate().unwrap(); crate::arch::process::Process::with_current_mut(|arch_process| { arch_process.print_all_threads() diff --git a/kernel/src/irq.rs b/kernel/src/irq.rs index dec50ba4d..b056253be 100644 --- a/kernel/src/irq.rs +++ b/kernel/src/irq.rs @@ -65,3 +65,18 @@ pub fn interrupt_claim( result } } + +/// Iterate through the IRQ handlers and remove any handler that exists +/// for the given PID. +pub fn release_interrupts_for_pid(pid: PID) { + unsafe { + for (irq, handler) in IRQ_HANDLERS.iter_mut().enumerate() { + if let Some(h) = handler { + if h.0 == pid { + arch::irq::disable_irq(irq).unwrap(); + *handler = None; + } + } + } + } +} diff --git a/kernel/src/main.rs b/kernel/src/main.rs index 16bebe099..ad2d4cf8d 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -63,6 +63,8 @@ pub extern "C" fn init(arg_offset: *const u32, init_offset: *const u32, rpt_offs #[cfg(any(feature = "debug-print", feature = "print-panics"))] { use utralib::generated::*; + xous_kernel::claim_interrupt(utra::uart::UART_IRQ, debug::irq, 0 as *mut usize) + .expect("Couldn't claim debug interrupt"); // Map the serial port so println!() works as expected. mem::MemoryManager::with_mut(|memory_manager| { memory_manager @@ -76,11 +78,9 @@ pub extern "C" fn init(arg_offset: *const u32, init_offset: *const u32, rpt_offs ) .expect("unable to map serial port") }); - debug::Uart{}.init(); + debug::Uart {}.init(); println!("KMAIN (clean boot): Supervisor mode started..."); println!("Claiming IRQ {} via syscall...", utra::uart::UART_IRQ); - xous_kernel::claim_interrupt(utra::uart::UART_IRQ, debug::irq, 0 as *mut usize) - .expect("Couldn't claim debug interrupt"); print!("}} "); // Print the processed kernel arguments @@ -168,7 +168,7 @@ pub extern "C" fn kmain() { #[cfg(feature = "debug-print")] SystemServices::with(|system_services| { for (test_idx, process) in system_services.processes.iter().enumerate() { - if ! process.free() { + if !process.free() { println!("PID {}: {:?}", test_idx + 1, process); } } diff --git a/kernel/src/mem.rs b/kernel/src/mem.rs index a17dd27ab..4e51244a1 100644 --- a/kernel/src/mem.rs +++ b/kernel/src/mem.rs @@ -2,8 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 use core::fmt; -use core::slice; -use core::str; pub use crate::arch::mem::{MemoryMapping, PAGE_SIZE}; use crate::arch::process::Process; @@ -27,18 +25,13 @@ pub struct MemoryRangeExtra { impl fmt::Display for MemoryRangeExtra { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let tag_name_bytes = self.mem_tag.to_le_bytes(); - let s = unsafe { - // First, we build a &[u8]... - let slice = slice::from_raw_parts(tag_name_bytes.as_ptr(), 4); - // ... and then convert that slice into a string slice - str::from_utf8_unchecked(slice) - }; - write!( f, - "{} ({:08x}) {:08x} - {:08x} {} bytes", - s, + "{}{}{}{} - ({:08x}) {:08x} - {:08x} {} bytes", + ((self.mem_tag >> 0) & 0xff) as u8 as char, + ((self.mem_tag >> 8) & 0xff) as u8 as char, + ((self.mem_tag >> 16) & 0xff) as u8 as char, + ((self.mem_tag >> 24) & 0xff) as u8 as char, self.mem_tag, self.mem_start, self.mem_start + self.mem_size, @@ -114,6 +107,7 @@ impl MemoryManager { MEMORY_MANAGER.with(|ss| f(&mut ss.borrow_mut())) } + #[cfg(baremetal)] pub fn with(f: F) -> R where F: FnOnce(&MemoryManager) -> R, @@ -132,6 +126,7 @@ impl MemoryManager { base: *mut u32, args: &crate::args::KernelArguments, ) -> Result<(), xous_kernel::Error> { + use core::slice; let mut args_iter = args.iter(); let xarg_def = args_iter.next().expect("mm: no kernel arguments found"); unsafe { @@ -195,11 +190,6 @@ impl MemoryManager { owned_bytes } - #[cfg(not(baremetal))] - pub fn ram_used_by(&self, _pid: PID) -> usize { - 0 - } - #[cfg(all(baremetal, feature = "print-debug"))] pub fn print_ownership(&self) { println!("Ownership ({} bytes in all):", unsafe { @@ -594,6 +584,7 @@ impl MemoryManager { ) } + #[cfg(baremetal)] pub fn ensure_page_exists(&mut self, address: usize) -> Result<(), xous_kernel::Error> { crate::arch::mem::ensure_page_exists_inner(address).and(Ok(())) } @@ -699,4 +690,57 @@ impl MemoryManager { fn release_page(&mut self, addr: *mut usize, pid: PID) -> Result<(), xous_kernel::Error> { self.claim_release_move(addr, pid, ClaimReleaseMove::Release) } + + /// Convert an offset in the `MEMORY_ALLOCATIONS` array into a physical address. + #[cfg(baremetal)] + fn allocation_offset_to_address(&self, offset: usize) -> Option { + // If the offset is within the RAM size, simply turn it into + // an address. + if offset < self.ram_size as usize / PAGE_SIZE { + Some(self.ram_start as usize + offset * PAGE_SIZE) + } else { + // The offset is not within RAM, so it must be in the extra + // regions list. Loop through all regions looking for the + // address. NOTE: This needs to be linear because each memory + // region has a different length. + let mut offset_in_region = offset - (self.ram_size as usize / PAGE_SIZE); + unsafe { + for region in EXTRA_REGIONS { + // If the offset exceeds the current region, skip to the + // next region. + if offset_in_region >= (region.mem_size as usize / PAGE_SIZE) { + offset_in_region -= region.mem_size as usize / PAGE_SIZE; + continue; + } + return Some(region.mem_start as usize + (offset_in_region * PAGE_SIZE)); + } + } + + // No region was found. + None + } + } + + /// Free all memory that belongs to a process. This does not unmap the + /// memory from the process, it only marks it as free. + /// This is very unsafe because the memory can immediately be re-allocated + /// to another process, so only call this as part of destroying a process. + pub unsafe fn release_all_memory_for_process(&mut self, _pid: PID) { + #[cfg(baremetal)] + for (idx, owner) in MEMORY_ALLOCATIONS.iter_mut().enumerate() { + // If this address has been allocated to this process, consider + // freeing it or reparenting it. + if owner == &mut Some(_pid) { + let phys_addr = self.allocation_offset_to_address(idx).unwrap(); + if crate::arch::mem::page_is_lent(phys_addr as *mut u8) { + // If the page is lent, reparent it to PID 1 so it will + // get freed when it is returned. + *owner = PID::new(1); + } else { + // Mark this page as free, which allows it to be re-allocated. + *owner = None; + } + } + } + } } diff --git a/kernel/src/server.rs b/kernel/src/server.rs index b84d0bebd..06c750c64 100644 --- a/kernel/src/server.rs +++ b/kernel/src/server.rs @@ -308,11 +308,7 @@ impl Server { /// Take a current slot and replace it with `None`, clearing out the contents of the queue. /// Returns an error if the queue has any waiting elements. /// Returns a list of threads that should be readied. - pub fn destroy( - mut self, - ss: &mut SystemServices, - ) -> Result<(), Self> { - + pub fn destroy(mut self, ss: &mut SystemServices) -> Result<(), Self> { // First determine if the server has any Waiting messages. That is, any messages // that are currently sitting in the memory space of the Server. These cannot // safely be handled, and will cause an error if we try to mess with them. diff --git a/kernel/src/services.rs b/kernel/src/services.rs index 0191291b1..4ede57fe6 100644 --- a/kernel/src/services.rs +++ b/kernel/src/services.rs @@ -194,11 +194,15 @@ impl Process { return Err(xous_kernel::Error::ProcessNotFound); } - // TODO: Free all pages + // Free all associated memory pages + unsafe { + crate::mem::MemoryManager::with_mut(|mm| mm.release_all_memory_for_process(self.pid)) + }; - // TODO: Free all IRQs + // Free all claimed IRQs + crate::irq::release_interrupts_for_pid(self.pid); - // TODO: Free memory mapping + // Remove this PID from the process table crate::arch::process::Process::destroy(self.pid)?; self.state = ProcessState::Free; Ok(()) @@ -567,10 +571,7 @@ impl SystemServices { pid, tid, other ), }; - // println!( - // "KERNEL({}): Readying context {} -> {:?}", - // pid, context, process.state - // ); + klog!("Readying ({}:{}) -> {:?}", pid, tid, process.state); Ok(()) } @@ -585,12 +586,12 @@ impl SystemServices { tid: Option, ) -> Result<(), xous_kernel::Error> { let process = self.get_process_mut(pid)?; - // println!( + // klog!( // "switch_to_thread({}:{:?}): Old state was {:?}", // pid, tid, process.state // ); - // Determine which context number to switch to + // Determine which thread to switch to process.state = match process.state { ProcessState::Free => return Err(xous_kernel::Error::ProcessNotFound), ProcessState::Sleeping => return Err(xous_kernel::Error::ProcessNotFound), @@ -1289,6 +1290,10 @@ impl SystemServices { Err(xous_kernel::Error::BadAddress)?; } + // If memory is getting returned to the kernel, then it is memory that was + // borrowed but + if dest_pid.get() == 1 {} + // Iterators and `ptr.wrapping_add()` operate on `usize` types, // which effectively lowers the `len`. let usize_len = len / core::mem::size_of::(); @@ -1306,9 +1311,7 @@ impl SystemServices { let mut error = None; // Lend each subsequent page. - for offset in (0..usize_len) - .step_by(usize_page) - { + for offset in (0..usize_len).step_by(usize_page) { assert!(((src_virt.wrapping_add(offset) as usize) & 0xfff) == 0); assert!(((dest_virt.wrapping_add(offset) as usize) & 0xfff) == 0); mm.unlend_page( @@ -1330,7 +1333,8 @@ impl SystemServices { }); } error.map_or_else(|| Ok(dest_virt), |e| Err(e)) - }).map(|val| val as *mut usize) + }) + .map(|val| val as *mut usize) } #[cfg(not(baremetal))] @@ -1405,6 +1409,78 @@ impl SystemServices { Ok(new_tid) } + /// Destroy the given thread. + /// NOTE: You MUST immediately switch away from this process. + /// # Errors + /// + /// * **ThreadNotAvailable**: The thread does not exist in this process + #[cfg(baremetal)] + pub fn destroy_thread(&mut self, pid: PID, tid: TID) -> Result { + let current_pid = self.current_pid(); + assert_eq!(pid, current_pid); + + let mut waiting_threads = match self.get_process_mut(pid)?.state { + ProcessState::Running(x) => x, + state => panic!("Process was in an invalid state: {:?}", state), + }; + + // Destroy the thread at a hardware level + let mut arch_process = crate::arch::process::Process::current(); + let return_value = arch_process.destroy_thread(tid).unwrap(); + + // If there's another thread waiting on the return value of this thread, + // wake it up and set its return value. + if let Some((waiting_tid, _thread)) = arch_process.find_thread(|waiting_tid, thr| { + (waiting_threads & (1 << waiting_tid)) == 0 // Thread is waiting (i.e. not ready to run) + && thr.a0() == (xous_kernel::SysCallNumber::JoinThread as usize) // Thread called `JoinThread` + && thr.a1() == (tid as usize) // It is waiting on our thread + }) { + // Wake up the thread + self.set_thread_result(pid, waiting_tid, xous_kernel::Result::Scalar1(return_value))?; + waiting_threads |= 1 << waiting_tid; + } + + // Mark this process as `Ready`. + // We can do this because the current thread has just exited. Note that if there + // are no threads available, this is an error. + self.get_process_mut(pid)?.state = ProcessState::Ready(waiting_threads); + + // Switch to the next available TID. This moves the process back to a `Running` state. + self.switch_to_thread(pid, None)?; + + Ok(return_value) + } + + /// Park this thread if the target thread is currently running. Otherwise, + /// return the value of the given thread. + pub fn join_thread( + &mut self, + pid: PID, + tid: TID, + join_tid: TID, + ) -> Result { + let current_pid = self.current_pid(); + assert_eq!(pid, current_pid); + + // We cannot wait on ourselves. + if tid == join_tid { + Err(xous_kernel::Error::ThreadNotAvailable)? + } + + // If the target thread exists, put this thread to sleep. + let arch_process = crate::arch::process::Process::current(); + if arch_process.thread_exists(join_tid) { + // The target thread exists -- put this thread to sleep + let ppid = self.get_process(pid).unwrap().ppid; + self.activate_process_thread(tid, ppid, 0, false) + .map(|_| Ok(xous_kernel::Result::ResumeProcess)) + .unwrap_or(Err(xous_kernel::Error::ProcessNotFound)) + } else { + // The thread does not exist -- continue execution + Err(xous_kernel::Error::ThreadNotAvailable) + } + } + /// Allocate a new server ID for this process and return the address. If the /// server table is full, or if there is not enough memory to map the server queue, /// return an error. @@ -1572,7 +1648,6 @@ impl SystemServices { // yet connected. let pid = crate::arch::process::current_pid(); - // println!("KERNEL({}): Server table: {:?}", _pid.get(), self.servers); ArchProcess::with_inner_mut(|process_inner| { assert_eq!(pid, process_inner.pid); let mut slot_idx = None; @@ -1846,6 +1921,8 @@ impl SystemServices { } } + let process = self.processes[(server.pid.get() - 1) as usize]; + process.activate().unwrap(); // Look through this server's memory space to determine if this process // is mentioned there as having some memory lent out. server.discard_messages_for_pid(target_pid); @@ -1855,10 +1932,8 @@ impl SystemServices { process.activate()?; let parent_pid = process.ppid; process.terminate()?; - // println!("KERNEL({}): Terminated", target_pid); - let process = self.get_process(parent_pid)?; - process.activate().unwrap(); + self.switch_to_thread(parent_pid, None).unwrap(); Ok(parent_pid) } @@ -1883,6 +1958,7 @@ impl SystemServices { } /// Returns the process name, if any, of a given PID + #[cfg(baremetal)] pub fn process_name(&self, pid: PID) -> Option<&str> { let args = crate::args::KernelArguments::get(); for arg in args.iter() { @@ -1896,17 +1972,27 @@ impl SystemServices { }; let mut offset = 0; while offset <= arg.size { - let check_pid = u32::from_le_bytes([data[offset+0],data[offset+1],data[offset+2],data[offset+3]]); - let str_len = u32::from_le_bytes([data[offset+4],data[offset+5],data[offset+6],data[offset+7]]) as usize; + let check_pid = u32::from_le_bytes([ + data[offset + 0], + data[offset + 1], + data[offset + 2], + data[offset + 3], + ]); + let str_len = u32::from_le_bytes([ + data[offset + 4], + data[offset + 5], + data[offset + 6], + data[offset + 7], + ]) as usize; if check_pid == pid.get() as _ { - if let Ok(s) = core::str::from_utf8(&data[offset+8..offset+8+str_len]){ + if let Ok(s) = core::str::from_utf8(&data[offset + 8..offset + 8 + str_len]) { return Some(s); } else { return None; } } offset += str_len + 8; - offset += (4-(offset & 3))&3; + offset += (4 - (offset & 3)) & 3; } } None diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index a86f1c17f..a8eb9a23a 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -256,8 +256,8 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes } fn return_memory( - pid: PID, - tid: TID, + server_pid: PID, + server_tid: TID, in_irq: bool, sender: MessageSender, buf: MemoryRange, @@ -270,12 +270,12 @@ fn return_memory( let server = ss .server_from_sidx_mut(sender.sidx) .ok_or(xous_kernel::Error::ServerNotFound)?; - if server.pid != pid { + if server.pid != server_pid { return Err(xous_kernel::Error::ServerNotFound); } let result = server.take_waiting_message(sender.idx, Some(&buf))?; klog!("waiting message was: {:?}", result); - let (client_pid, client_tid, server_addr, client_addr, len) = match result { + let (client_pid, client_tid, _server_addr, client_addr, len) = match result { WaitingMessage::BorrowedMemory( client_pid, client_ctx, @@ -318,14 +318,14 @@ fn return_memory( // "KERNEL({}): Returning {} bytes from {:08x} in PID {} to {:08x} in PID {} in context {}", // pid, // len, - // server_addr.get(), + // _server_addr.get(), // pid, // client_addr.get(), // client_pid, // client_tid // ); #[cfg(baremetal)] - let src_virt = server_addr.get() as _; + let src_virt = _server_addr.get() as _; #[cfg(not(baremetal))] let src_virt = buf.addr.get() as _; @@ -354,9 +354,9 @@ fn return_memory( Ok(xous_kernel::Result::Ok) } else { // Switch away from the server, but leave it as Runnable - ss.switch_from_thread(pid, tid)?; - ss.ready_thread(pid, tid)?; - ss.set_thread_result(pid, tid, xous_kernel::Result::Ok)?; + ss.switch_from_thread(server_pid, server_tid)?; + ss.ready_thread(server_pid, server_tid)?; + ss.set_thread_result(server_pid, server_tid, xous_kernel::Result::Ok)?; // Switch to the client ss.ready_thread(client_pid, client_tid)?; @@ -579,7 +579,7 @@ pub fn handle(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallResult #[cfg(feature = "debug-print")] println!( - " -> ({}:{}) {:?}", + " -> ({}:{}) {:x?}", crate::arch::current_pid(), crate::arch::process::Process::current().current_tid(), result @@ -718,7 +718,8 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR unsafe { assert!( SWITCHTO_CALLER.is_none(), - "SWITCHTO_CALLER was not None, indicating SwitchTo was called twice" + "SWITCHTO_CALLER was {:?} and not None, indicating SwitchTo was called twice", + SWITCHTO_CALLER, ); SWITCHTO_CALLER = Some((pid, tid)); } @@ -799,15 +800,12 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR return_scalar2(pid, tid, in_irq, sender, arg1, arg2) } SysCall::TrySendMessage(cid, message) => send_message(pid, tid, cid, message), - SysCall::TerminateProcess => SystemServices::with_mut(|ss| { + SysCall::TerminateProcess(_ret) => SystemServices::with_mut(|ss| { ss.switch_from_thread(pid, tid)?; - let ppid = ss.terminate_process(pid)?; - if cfg!(baremetal) { - ss.switch_to_thread(ppid, None) - .map(|_| xous_kernel::Result::ResumeProcess) - } else { - Ok(xous_kernel::Result::Ok) - } + ss.terminate_process(pid)?; + // Clear out `SWITCHTO_CALLER` since we're resuming the parent process. + unsafe { SWITCHTO_CALLER = None }; + Ok(xous_kernel::Result::ResumeProcess) }), SysCall::Shutdown => { SystemServices::with_mut(|ss| ss.shutdown().map(|_| xous_kernel::Result::Ok)) @@ -852,6 +850,12 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR SysCall::DestroyServer(sid) => SystemServices::with_mut(|ss| { ss.destroy_server(pid, sid).and(Ok(xous_kernel::Result::Ok)) }), + SysCall::JoinThread(other_tid) => { + SystemServices::with_mut(|ss| ss.join_thread(pid, tid, other_tid)).map(|ret| { + unsafe { SWITCHTO_CALLER = None }; + ret + }) + } _ => Err(xous_kernel::Error::UnhandledSyscall), } } diff --git a/kernel/src/test.rs b/kernel/src/test.rs index b3c02d52c..202e29810 100644 --- a/kernel/src/test.rs +++ b/kernel/src/test.rs @@ -4,12 +4,10 @@ use crate::kmain; use std::thread::JoinHandle; -use std::net::ToSocketAddrs; use crossbeam_channel::unbounded; +use std::net::ToSocketAddrs; use xous_kernel::{rsyscall, SysCall}; -mod shutdown; - #[cfg(feature = "report-memory")] use stats_alloc::{Region, Stats, StatsAlloc, INSTRUMENTED_SYSTEM}; #[cfg(feature = "report-memory")] @@ -170,7 +168,8 @@ fn connect_for_process() { } else { panic!("Unexpected return value"); }; - xous_kernel::return_scalar(envelope.sender, new_cid as usize).expect("couldn't return scalar"); + xous_kernel::return_scalar(envelope.sender, new_cid as usize) + .expect("couldn't return scalar"); }), ) .expect("couldn't spawn client process"); diff --git a/services/cb-test-c1/src/main.rs b/services/cb-test-c1/src/main.rs index 6a16b4a4f..7c5cda460 100644 --- a/services/cb-test-c1/src/main.rs +++ b/services/cb-test-c1/src/main.rs @@ -76,5 +76,5 @@ fn xmain() -> ! { xns.unregister_server(sid).unwrap(); xous::destroy_server(sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/cb-test-c2/src/main.rs b/services/cb-test-c2/src/main.rs index 8d50c8b7e..38eb1e5e0 100644 --- a/services/cb-test-c2/src/main.rs +++ b/services/cb-test-c2/src/main.rs @@ -76,5 +76,5 @@ fn xmain() -> ! { xns.unregister_server(sid).unwrap(); xous::destroy_server(sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/codec/src/main.rs b/services/codec/src/main.rs index eaa377fc6..25091c43f 100644 --- a/services/codec/src/main.rs +++ b/services/codec/src/main.rs @@ -163,7 +163,7 @@ fn xmain() -> ! { xns.unregister_server(codec_sid).unwrap(); xous::destroy_server(codec_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } @@ -209,4 +209,4 @@ fn send_event(cb_conns: &[Option; 32], free_play: usize, avail_r ).unwrap(); }; } -} \ No newline at end of file +} diff --git a/services/com/src/main.rs b/services/com/src/main.rs index f2d3272ca..cd3bc423c 100644 --- a/services/com/src/main.rs +++ b/services/com/src/main.rs @@ -600,5 +600,5 @@ fn xmain() -> ! { xns.unregister_server(com_sid).unwrap(); xous::destroy_server(com_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/engine-sha512/src/main.rs b/services/engine-sha512/src/main.rs index ac51b0767..b06178ed5 100644 --- a/services/engine-sha512/src/main.rs +++ b/services/engine-sha512/src/main.rs @@ -250,6 +250,7 @@ mod implementation { #[cfg(not(target_os = "none"))] mod implementation { use log::info; + use crate::Sha2Config; pub(crate) struct Engine512 { } @@ -265,6 +266,16 @@ mod implementation { } pub(crate) fn reset(&self) { } + pub(crate) fn setup(&mut self, _config: Sha2Config) { + } + pub(crate) fn update(&mut self, _buf: &[u8]) { + } + pub(crate) fn finalize(&mut self) -> ([u8; 64], u64) { + ([0; 64], 0) + } + pub(crate) fn is_idle(&mut self) -> bool { + false + } } } @@ -460,5 +471,5 @@ fn xmain() -> ! { xns.unregister_server(engine512_sid).unwrap(); xous::destroy_server(engine512_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index dec9f1346..b42da9b42 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -443,5 +443,5 @@ fn xmain() -> ! { xns.unregister_server(gam_sid).unwrap(); xous::destroy_server(gam_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/graphics-server/src/main.rs b/services/graphics-server/src/main.rs index e13a202da..b4acc2ad4 100644 --- a/services/graphics-server/src/main.rs +++ b/services/graphics-server/src/main.rs @@ -394,5 +394,5 @@ fn xmain() -> ! { xns.unregister_server(sid).unwrap(); xous::destroy_server(sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/ime-frontend/src/main.rs b/services/ime-frontend/src/main.rs index 048c28527..4316e5a94 100644 --- a/services/ime-frontend/src/main.rs +++ b/services/ime-frontend/src/main.rs @@ -740,5 +740,5 @@ fn xmain() -> ! { xns.unregister_server(imef_sid).unwrap(); xous::destroy_server(imef_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/ime-plugin-shell/src/main.rs b/services/ime-plugin-shell/src/main.rs index f4bd227af..c2f701d98 100644 --- a/services/ime-plugin-shell/src/main.rs +++ b/services/ime-plugin-shell/src/main.rs @@ -129,5 +129,5 @@ fn xmain() -> ! { xns.unregister_server(ime_sh_sid).unwrap(); xous::destroy_server(ime_sh_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index 2aa2737f2..66f3ed436 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -1003,5 +1003,5 @@ fn xmain() -> ! { xns.unregister_server(kbd_sid).unwrap(); xous::destroy_server(kbd_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index b5d56b1a0..831c0571e 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -534,6 +534,15 @@ mod implementation { } pub fn usb_int_ena(self, _ena: bool) { } + pub fn debug_powerdown(&mut self, _ena: bool) { + } + pub fn debug_wakeup(&mut self, _ena: bool) { + } + pub fn activity_get_period(&mut self) -> u32 { + 12_000_000 + } + pub fn wfi_override(&mut self, _override_: bool) { + } } } @@ -868,7 +877,7 @@ fn xmain() -> ! { xns.unregister_server(llio_sid).unwrap(); xous::destroy_server(llio_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } fn do_hook(hookdata: ScalarHook, cb_conns: &mut [Option; 32]) { @@ -913,4 +922,4 @@ fn send_event(cb_conns: &[Option; 32], which: usize) { ).unwrap(); }; } -} \ No newline at end of file +} diff --git a/services/log-server/build.rs b/services/log-server/build.rs index 5fd27838d..de9132b19 100644 --- a/services/log-server/build.rs +++ b/services/log-server/build.rs @@ -2,7 +2,7 @@ use std::env; extern crate vergen; -use vergen::{ConstantsFlags, generate_cargo_keys}; +use vergen::{generate_cargo_keys, ConstantsFlags}; fn main() { let target = env::var("TARGET").unwrap(); @@ -16,7 +16,10 @@ fn main() { println!("cargo:rustc-cfg=baremetal"); } - generate_cargo_keys(ConstantsFlags::SHA /*| ConstantsFlags::BUILD_TIMESTAMP*/).unwrap(); + generate_cargo_keys( + ConstantsFlags::SHA, /*| ConstantsFlags::BUILD_TIMESTAMP*/ + ) + .unwrap(); // BUILD_TIMESTAMP doesn't work -- it doesn't update because of the below line // removing the below line causes a lengthy full-rebuild just to capture a timestamp. // so, we're removing the timestamp. diff --git a/services/log-server/src/api.rs b/services/log-server/src/api.rs index a068c0a59..8e8ef9343 100644 --- a/services/log-server/src/api.rs +++ b/services/log-server/src/api.rs @@ -12,13 +12,13 @@ pub enum Opcode { /// A `LogRecord` message, delivering structured log output LogRecord = 0, - /// A `xous::String` destined for stdout + /// A `&[u8]` destined for stdout StandardOutput = 1, - /// A `xous::String` destined for stderr + /// A `&[u8]` destined for stderr StandardError = 2, - /// A `xous::String` containing this program's name + /// A `xous::StringBuffer` containing this program's name ProgramName = 3, /// A panic occurred, and a panic log is forthcoming diff --git a/services/log-server/src/main.rs b/services/log-server/src/main.rs index 1beebbb92..cf71a6b55 100644 --- a/services/log-server/src/main.rs +++ b/services/log-server/src/main.rs @@ -86,6 +86,20 @@ mod implementation { pub fn putc(&self, c: u8) { self.tx.send(ControlMessage::Byte(c)).unwrap(); } + + /// Write a buffer to the output and return the number of + /// bytes written. This is mostly compatible with `std::io::Write`, + /// except it is infallible. + pub fn write(&mut self, buf: &[u8]) -> usize { + for c in buf { + self.putc(*c); + } + buf.len() + } + + pub fn write_all(&mut self, buf: &[u8]) -> core::result::Result { + Ok(self.write(buf)) + } } impl Write for OutputWriter { @@ -177,6 +191,20 @@ mod implementation { uart_csr.wo(utra::uart::RXTX, c as u32); } } + + /// Write a buffer to the output and return the number of + /// bytes written. This is mostly compatible with `std::io::Write`, + /// except it is infallible. + pub fn write(&mut self, buf: &[u8]) -> usize { + for c in buf { + self.putc(*c); + } + buf.len() + } + + pub fn write_all(&mut self, buf: &[u8]) -> core::result::Result { + Ok(self.write(buf)) + } } impl Write for OutputWriter { @@ -199,7 +227,7 @@ fn handle_scalar( sender_pid: xous::PID, ) { match msg.id { - 1000 => writeln!(output, "PANIC from PID {} | {}", sender_pid, sender).unwrap(), + 1000 => writeln!(output, "PANIC in PID {}:", sender_pid).unwrap(), 1100 => (), 1101..=1132 => { let mut output_bfr = [0u8; core::mem::size_of::() * 4]; @@ -279,8 +307,29 @@ fn handle_opcode( } } api::Opcode::StandardOutput | api::Opcode::StandardError => { - let string = unsafe { xous::stringbuffer::StringBuffer::from_memory_message(mem) }; - write!(output, "{}", string).unwrap(); + // let mut buffer_start_offset = mem.offset.map(|o| o.get()).unwrap_or(0); + let mut buffer_start_offset = 0; + let mut buffer_length = mem.valid.map(|v| v.get()).unwrap_or(mem.buf.len()); + + // Ensure that `buffer_start_offset` is within the range of `buffer`. + if buffer_start_offset >= mem.buf.len() { + buffer_start_offset = mem.buf.len() - 1; + } + + // Clamp the buffer length so that it fits within the buffer + if buffer_start_offset + buffer_length >= mem.buf.len() { + buffer_length = mem.buf.len() - buffer_start_offset; + } + + // Safe because we validated the offsets above + let buffer = unsafe { + core::slice::from_raw_parts( + mem.buf.as_ptr().add(buffer_start_offset), + buffer_length, + ) + }; + output.write_all(buffer).unwrap(); + // TODO: If the buffer is mutable, set `length` to 0. } _ => { writeln!(output, "Unhandled opcode").unwrap(); @@ -345,7 +394,7 @@ fn reader_thread(arg: usize) { log::trace!("main loop exit, destroying servers"); xous::destroy_server(server_addr).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) */ } diff --git a/services/log-test-client/Cargo.toml b/services/log-test-client/Cargo.toml new file mode 100644 index 000000000..ab6ff52da --- /dev/null +++ b/services/log-test-client/Cargo.toml @@ -0,0 +1,12 @@ +[package] +authors = ["Sean Cross "] +description = "Program to test the log server" +edition = "2018" +name = "log-test-client" +version = "0.1.0" + +[dependencies] +xous = {path = "../../xous-rs"} + +[features] +default = [] diff --git a/services/log-test-client/README.md b/services/log-test-client/README.md new file mode 100644 index 000000000..f1d1ca67f --- /dev/null +++ b/services/log-test-client/README.md @@ -0,0 +1,5 @@ +# Kernel Test + +Run various tests inside the kernel. + +This is supposed to be the only program running. diff --git a/services/log-test-client/src/main.rs b/services/log-test-client/src/main.rs new file mode 100644 index 000000000..9f20ac65a --- /dev/null +++ b/services/log-test-client/src/main.rs @@ -0,0 +1,22 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +use xous::StringBuffer; +use core::fmt::Write; + +#[xous::xous_main] +fn test_main() -> ! { + let connection = xous::connect(xous::SID::from_bytes(b"xous-log-server ").unwrap()).unwrap(); + + let mut log_string= StringBuffer::new(); + for i in 0.. { + log_string.clear(); + writeln!(log_string, "Hello, world! Loop {}", i).unwrap(); + log_string.lend(connection, 1).unwrap(); + + log_string.lend_mut(connection, 1).unwrap(); + log_string.lend(connection, 1).unwrap(); + xous::yield_slice(); + } + panic!("Finished an infinite loop"); +} diff --git a/services/rkyv-test-server/src/main.rs b/services/rkyv-test-server/src/main.rs index 41846f711..51f6b4804 100644 --- a/services/rkyv-test-server/src/main.rs +++ b/services/rkyv-test-server/src/main.rs @@ -179,5 +179,5 @@ fn test_main() -> ! { xns.unregister_server(sid).unwrap(); xous::destroy_server(sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/rtc/src/main.rs b/services/rtc/src/main.rs index 38932be7c..bff85cb73 100644 --- a/services/rtc/src/main.rs +++ b/services/rtc/src/main.rs @@ -675,5 +675,5 @@ fn xmain() -> ! { xns.unregister_server(rtc_sid).unwrap(); xous::destroy_server(rtc_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/shellchat/src/cmds/ecup.rs b/services/shellchat/src/cmds/ecup.rs index 0b3ef73d8..ea8e16b38 100644 --- a/services/shellchat/src/cmds/ecup.rs +++ b/services/shellchat/src/cmds/ecup.rs @@ -186,18 +186,35 @@ fn ecupdate_thread(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { log::error!("couldn't acquire exclusive access to the EC updater mechanism. All other operations will fail!"); } + #[cfg(target_os = "none")] let ec_package = xous::syscall::map_memory( xous::MemoryAddress::new(xous::EC_FW_PKG_LOC as usize), None, xous::EC_FW_PKG_LEN as usize, xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map EC firmware package memory range"); + #[cfg(target_os = "none")] let wf_package = xous::syscall::map_memory( xous::MemoryAddress::new(xous::EC_WF200_PKG_LOC as usize), None, xous::EC_WF200_PKG_LEN as usize, xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map EC wf200 package memory range"); + #[cfg(not(target_os = "none"))] + let ec_package = xous::syscall::map_memory( + None, + None, + xous::EC_FW_PKG_LEN as usize, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map EC firmware package memory range"); + #[cfg(not(target_os = "none"))] + let wf_package = xous::syscall::map_memory( + None, + None, + xous::EC_WF200_PKG_LEN as usize, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map EC wf200 package memory range"); + loop { let msg = xous::receive_message(sid).unwrap(); log::debug!("EC updater got msg {:?}", msg); diff --git a/services/shellchat/src/main.rs b/services/shellchat/src/main.rs index e0369fb64..80059c2eb 100644 --- a/services/shellchat/src/main.rs +++ b/services/shellchat/src/main.rs @@ -321,5 +321,5 @@ fn xmain() -> ! { xns.unregister_server(shch_sid).unwrap(); xous::destroy_server(shch_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/skeleton/src/main.rs b/services/skeleton/src/main.rs index 729a83021..00507117c 100644 --- a/services/skeleton/src/main.rs +++ b/services/skeleton/src/main.rs @@ -116,5 +116,5 @@ fn xmain() -> ! { xns.unregister_server(codec_sid).unwrap(); xous::destroy_server(codec_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/susres/src/main.rs b/services/susres/src/main.rs index 80a2efdb8..328575a30 100644 --- a/services/susres/src/main.rs +++ b/services/susres/src/main.rs @@ -690,7 +690,7 @@ fn xmain() -> ! { xns.unregister_server(susres_sid).unwrap(); xous::destroy_server(susres_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } fn do_hook(hookdata: ScalarHook, cb_conns: &mut [Option; 32]) { diff --git a/services/ticktimer-server/src/api.rs b/services/ticktimer-server/src/api.rs index 156e1090e..963eab83d 100644 --- a/services/ticktimer-server/src/api.rs +++ b/services/ticktimer-server/src/api.rs @@ -1,14 +1,14 @@ #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] pub(crate) enum Opcode { /// Get the elapsed time in milliseconds - ElapsedMs, + ElapsedMs = 0, /// Sleep for the specified numer of milliseconds - SleepMs, + SleepMs = 1, /// Recalculate the sleep time - RecalculateSleep, + RecalculateSleep = 2, /// Suspend/resume callback - SuspendResume, + SuspendResume = 3, } diff --git a/services/ticktimer-server/src/main.rs b/services/ticktimer-server/src/main.rs index fac31cbb0..6d1ebf93e 100644 --- a/services/ticktimer-server/src/main.rs +++ b/services/ticktimer-server/src/main.rs @@ -559,5 +559,5 @@ fn xmain() -> ! { log::trace!("main loop exit, destroying servers"); xous::destroy_server(ticktimer_server).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0); } diff --git a/services/trng/src/main.rs b/services/trng/src/main.rs index ad6d03655..1f4bff5d2 100644 --- a/services/trng/src/main.rs +++ b/services/trng/src/main.rs @@ -413,5 +413,5 @@ fn xmain() -> ! { xns.unregister_server(trng_sid).unwrap(); xous::destroy_server(trng_sid).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0) } diff --git a/services/xous-names/src/main.rs b/services/xous-names/src/main.rs index 520d52ef2..8a9270ef6 100644 --- a/services/xous-names/src/main.rs +++ b/services/xous-names/src/main.rs @@ -238,5 +238,5 @@ fn xmain() -> ! { log::trace!("main loop exit, destroying servers"); xous::destroy_server(name_server).unwrap(); log::trace!("quitting"); - xous::terminate_process(); loop {} + xous::terminate_process(0); } diff --git a/svd2repl/Cargo.toml b/svd2repl/Cargo.toml new file mode 100644 index 000000000..e428874ee --- /dev/null +++ b/svd2repl/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "svd2repl" +description = "Convert an SVD file into a Renode Platform description" +version = "0.1.0" +authors = ["Sean Cross "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +quick-xml = "0.19" +clap = "2" +anyhow = "1.0" +convert_case = "0.4" diff --git a/svd2repl/build.rs b/svd2repl/build.rs new file mode 100644 index 000000000..56ee3e0a1 --- /dev/null +++ b/svd2repl/build.rs @@ -0,0 +1,51 @@ +use std::env; +use std::error::Error; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; +use std::process::Command; + +struct IgnoredError {} + +impl From for IgnoredError +where + E: Error, +{ + fn from(_: E) -> IgnoredError { + IgnoredError {} + } +} + +fn main() { + let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); + + File::create(out_dir.join("commit-info.txt")) + .unwrap() + .write_all(commit_info().as_bytes()) + .unwrap(); +} + +fn commit_info() -> String { + match (commit_hash(), commit_date()) { + (Ok(hash), Ok(date)) => format!(" ({} {})", hash.trim(), date.trim()), + _ => String::new(), + } +} + +fn commit_hash() -> Result { + Ok(String::from_utf8( + Command::new("git") + .args(&["rev-parse", "--short", "HEAD"]) + .output()? + .stdout, + )?) +} + +fn commit_date() -> Result { + Ok(String::from_utf8( + Command::new("git") + .args(&["log", "-1", "--date=short", "--pretty=format:%cd"]) + .output()? + .stdout, + )?) +} diff --git a/svd2repl/src/generate.rs b/svd2repl/src/generate.rs new file mode 100644 index 000000000..a12f97831 --- /dev/null +++ b/svd2repl/src/generate.rs @@ -0,0 +1,630 @@ +use quick_xml::events::Event; +use quick_xml::Reader; +use std::io::{BufRead, BufReader, Read, Write}; +#[derive(Debug)] +pub enum ParseError { + UnexpectedTag, + MissingValue, + ParseIntError, + NonUTF8, + WriteError, +} + +#[derive(Default, Debug)] +pub struct Field { + name: String, + lsb: usize, + msb: usize, +} + +#[derive(Default, Debug)] +pub struct Register { + name: String, + offset: usize, + description: Option, + fields: Vec, +} + +#[derive(Default, Debug)] +pub struct Interrupt { + name: String, + value: usize, +} + +#[derive(Default, Debug)] +pub struct Peripheral { + name: String, + pub base: usize, + size: usize, + interrupt: Vec, + registers: Vec, +} + +#[derive(Default, Debug)] +pub struct MemoryRegion { + pub name: String, + pub base: usize, + pub size: usize, +} + +#[derive(Default, Debug)] +pub struct Constant { + pub name: String, + pub value: String, +} + +#[derive(Default, Debug)] +pub struct Description { + pub peripherals: Vec, + pub memory_regions: Vec, + pub constants: Vec, +} + +impl core::fmt::Display for ParseError { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + use ParseError::*; + match *self { + UnexpectedTag => write!(f, "unexpected XML tag encountered"), + MissingValue => write!(f, "XML tag should have contained a value"), + ParseIntError => write!(f, "unable to parse number"), + NonUTF8 => write!(f, "file is not UTF-8"), + WriteError => write!(f, "unable to write destination file"), + } + } +} + +impl std::error::Error for ParseError {} + +pub fn get_base(value: &str) -> (&str, u32) { + if value.starts_with("0x") { + (value.trim_start_matches("0x"), 16) + } else if value.starts_with("0X") { + (value.trim_start_matches("0X"), 16) + } else if value.starts_with("0b") { + (value.trim_start_matches("0b"), 2) + } else if value.starts_with("0B") { + (value.trim_start_matches("0B"), 2) + } else if value.starts_with('0') && value != "0" { + (value.trim_start_matches('0'), 8) + } else { + (value, 10) + } +} + +fn parse_usize(value: &[u8]) -> Result { + let value_as_str = String::from_utf8(value.to_vec()).or(Err(ParseError::NonUTF8))?; + let (value, base) = get_base(&value_as_str); + usize::from_str_radix(value, base).or(Err(ParseError::ParseIntError)) +} + +fn extract_contents(reader: &mut Reader) -> Result { + let mut buf = Vec::new(); + let contents = reader + .read_event(&mut buf) + .map_err(|_| ParseError::UnexpectedTag)?; + match contents { + Event::Text(t) => t + .unescape_and_decode(reader) + .map_err(|_| ParseError::NonUTF8), + _ => Err(ParseError::UnexpectedTag), + } +} + +fn generate_field(reader: &mut Reader) -> Result { + let mut buf = Vec::new(); + let mut name = None; + let mut lsb = None; + let mut msb = None; + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => { + let tag_name = e + .unescape_and_decode(reader) + .map_err(|_| ParseError::NonUTF8)?; + match tag_name.as_str() { + "name" => name = Some(extract_contents(reader)?), + "lsb" => lsb = Some(parse_usize(extract_contents(reader)?.as_bytes())?), + "msb" => msb = Some(parse_usize(extract_contents(reader)?.as_bytes())?), + _ => (), + } + } + Ok(Event::End(ref e)) => { + if let b"field" = e.name() { + break; + } + } + Ok(_) => (), + Err(e) => panic!("error parsing: {:?}", e), + } + } + + Ok(Field { + name: name.ok_or(ParseError::MissingValue)?, + lsb: lsb.ok_or(ParseError::MissingValue)?, + msb: msb.ok_or(ParseError::MissingValue)?, + }) +} + +fn generate_fields( + reader: &mut Reader, + fields: &mut Vec, +) -> Result<(), ParseError> { + let mut buf = Vec::new(); + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => match e.name() { + b"field" => fields.push(generate_field(reader)?), + _ => panic!("unexpected tag in : {:?}", e), + }, + Ok(Event::End(ref e)) => match e.name() { + b"fields" => { + // println!("End fields"); + break; + } + e => panic!("unhandled value: {:?}", e), + }, + Ok(Event::Text(_)) => (), + e => panic!("unhandled value: {:?}", e), + } + } + Ok(()) +} + +fn generate_register(reader: &mut Reader) -> Result { + let mut buf = Vec::new(); + let mut name = None; + let mut offset = None; + let description = None; + let mut fields = vec![]; + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => { + let tag_name = e + .unescape_and_decode(reader) + .map_err(|_| ParseError::NonUTF8)?; + match tag_name.as_str() { + "name" => name = Some(extract_contents(reader)?), + "addressOffset" => { + offset = Some(parse_usize(extract_contents(reader)?.as_bytes())?) + } + "fields" => generate_fields(reader, &mut fields)?, + _ => (), + } + } + Ok(Event::End(ref e)) => { + if let b"register" = e.name() { + break; + } + } + Ok(_) => (), + Err(e) => panic!("error parsing: {:?}", e), + } + } + + Ok(Register { + name: name.ok_or(ParseError::MissingValue)?, + offset: offset.ok_or(ParseError::MissingValue)?, + description, + fields, + }) +} + +fn generate_interrupts( + reader: &mut Reader, + interrupts: &mut Vec, +) -> Result<(), ParseError> { + let mut buf = Vec::new(); + let mut name = None; + let mut value = None; + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => { + let tag_name = e + .unescape_and_decode(reader) + .map_err(|_| ParseError::NonUTF8)?; + match tag_name.as_str() { + "name" => name = Some(extract_contents(reader)?), + "value" => value = Some(parse_usize(extract_contents(reader)?.as_bytes())?), + _ => (), + } + } + Ok(Event::End(ref e)) => { + if let b"interrupt" = e.name() { + break; + } + } + Ok(_) => (), + Err(e) => panic!("error parsing: {:?}", e), + } + } + + interrupts.push(Interrupt { + name: name.ok_or(ParseError::MissingValue)?, + value: value.ok_or(ParseError::MissingValue)?, + }); + + Ok(()) +} + +fn generate_registers( + reader: &mut Reader, + registers: &mut Vec, +) -> Result<(), ParseError> { + let mut buf = Vec::new(); + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => match e.name() { + b"register" => registers.push(generate_register(reader)?), + _ => panic!("unexpected tag in : {:?}", e), + }, + Ok(Event::End(ref e)) => match e.name() { + b"registers" => { + break; + } + e => panic!("unhandled value: {:?}", e), + }, + Ok(Event::Text(_)) => (), + e => panic!("unhandled value: {:?}", e), + } + } + Ok(()) +} + +fn generate_peripheral(reader: &mut Reader) -> Result { + let mut buf = Vec::new(); + let mut name = None; + let mut base = None; + let mut size = None; + let mut registers = vec![]; + let mut interrupts = vec![]; + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => { + let tag_name = e + .unescape_and_decode(reader) + .map_err(|_| ParseError::NonUTF8)?; + match tag_name.as_str() { + "name" => name = Some(extract_contents(reader)?), + "baseAddress" => { + base = Some(parse_usize(extract_contents(reader)?.as_bytes())?) + } + "size" => size = Some(parse_usize(extract_contents(reader)?.as_bytes())?), + "registers" => generate_registers(reader, &mut registers)?, + "interrupt" => generate_interrupts(reader, &mut interrupts)?, + _ => (), + } + } + Ok(Event::End(ref e)) => { + if let b"peripheral" = e.name() { + break; + } + } + Ok(_) => (), + Err(e) => panic!("error parsing: {:?}", e), + } + } + + Ok(Peripheral { + name: name.ok_or(ParseError::MissingValue)?, + base: base.ok_or(ParseError::MissingValue)?, + size: size.ok_or(ParseError::MissingValue)?, + interrupt: interrupts, + registers, + }) +} + +fn generate_peripherals(reader: &mut Reader) -> Result, ParseError> { + let mut buf = Vec::new(); + let mut peripherals = vec![]; + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => match e.name() { + b"peripheral" => peripherals.push(generate_peripheral(reader)?), + _ => panic!("unexpected tag in : {:?}", e), + }, + Ok(Event::End(ref e)) => match e.name() { + b"peripherals" => { + break; + } + e => panic!("unhandled value: {:?}", e), + }, + Ok(Event::Text(_)) => (), + e => panic!("unhandled value: {:?}", e), + } + } + Ok(peripherals) +} + +fn generate_memory_region(reader: &mut Reader) -> Result { + let mut buf = Vec::new(); + let mut name = None; + let mut base = None; + let mut size = None; + + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => { + let tag_name = e + .unescape_and_decode(reader) + .map_err(|_| ParseError::NonUTF8)?; + match tag_name.as_str() { + "name" => name = Some(extract_contents(reader)?), + "baseAddress" => { + base = Some(parse_usize(extract_contents(reader)?.as_bytes())?) + } + "size" => size = Some(parse_usize(extract_contents(reader)?.as_bytes())?), + _ => (), + } + } + Ok(Event::End(ref e)) => { + if let b"memoryRegion" = e.name() { + break; + } + } + Ok(_) => (), + Err(e) => panic!("error parsing: {:?}", e), + } + } + + Ok(MemoryRegion { + name: name.ok_or(ParseError::MissingValue)?, + base: base.ok_or(ParseError::MissingValue)?, + size: size.ok_or(ParseError::MissingValue)?, + }) +} + +fn parse_memory_regions( + reader: &mut Reader, + description: &mut Description, +) -> Result<(), ParseError> { + let mut buf = Vec::new(); + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => match e.name() { + b"memoryRegion" => description + .memory_regions + .push(generate_memory_region(reader)?), + _ => panic!("unexpected tag in : {:?}", e), + }, + Ok(Event::End(ref e)) => match e.name() { + b"memoryRegions" => { + break; + } + e => panic!("unhandled value: {:?}", e), + }, + Ok(Event::Text(_)) => (), + e => panic!("unhandled value: {:?}", e), + } + } + Ok(()) +} + +fn generate_constants( + reader: &mut Reader, + description: &mut Description, +) -> Result<(), ParseError> { + let mut buf = Vec::new(); + loop { + match reader.read_event(&mut buf) { + Ok(Event::Empty(ref e)) => match e.name() { + b"constant" => { + let mut constant_descriptor = Constant::default(); + for maybe_att in e.attributes() { + match maybe_att { + Ok(att) => { + let att_name = String::from_utf8(att.key.to_vec()) + .expect("constant: error parsing attribute name"); + let att_value = String::from_utf8(att.value.to_vec()) + .expect("constant: error parsing attribute value"); + match att_name { + _ if att_name == "name" => constant_descriptor.name = att_value, + _ if att_name == "value" => { + constant_descriptor.value = att_value + } + _ => panic!("unexpected attribute name"), + } + } + _ => panic!("unexpected value in constant: {:?}", maybe_att), + } + } + description.constants.push(constant_descriptor) + } + _ => panic!("unexpected tag in : {:?}", e), + }, + // note to future self: if Litex goe away from attributes to nested elements, you would want + // Ok(Event::Start(ref e) => match e.name() ... to descend into the next tag level, and then + // use the tag_name match and extract_contents methods from other functions to generate + // the structure. + // note that the two formats could be mutually exclusively compatible within the same code base: + // if there are no attributes, the attribute iterator would do nothing; and if there are no + // child elements, the recursive descent would also do nothing. + Ok(Event::End(ref e)) => match e.name() { + b"constants" => break, + e => panic!("unhandled value: {:?}", e), + }, + Ok(Event::Text(_)) => (), + e => panic!("unhandled value: {:?}", e), + } + } + Ok(()) +} + +fn parse_vendor_extensions( + reader: &mut Reader, + description: &mut Description, +) -> Result<(), ParseError> { + let mut buf = Vec::new(); + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => match e.name() { + b"memoryRegions" => parse_memory_regions(reader, description)?, + b"constants" => generate_constants(reader, description)?, + _ => panic!("unexpected tag in : {:?}", e), + }, + Ok(Event::End(ref e)) => match e.name() { + b"vendorExtensions" => { + break; + } + e => panic!("unhandled value: {:?}", e), + }, + Ok(Event::Text(_)) => (), + e => panic!("unhandled value: {:?}", e), + } + } + Ok(()) +} + +fn print_header(out: &mut U) -> std::io::Result<()> { + let s = r####"// Renode Platform file generated by svd2repl +// This file is automatically generated +cpu: CPU.VexRiscv @ sysbus + cpuType: "rv32imac" + privilegeArchitecture: PrivilegeArchitecture.Priv1_10 + PerformanceInMips: 120 +"####; + out.write_all(s.as_bytes()) +} + +fn print_footer(out: &mut U) -> std::io::Result<()> { + let s = r####" +sysbus: + init: + ApplySVD @soc/renode.svd +"####; + out.write_all(s.as_bytes()) +} + +fn print_memory_regions(regions: &[MemoryRegion], out: &mut U) -> std::io::Result<()> { + writeln!(out, "// Physical base addresses of memory regions")?; + for region in regions { + let mut region_name = region.name.to_lowercase(); + let region_size = if region.size < 4096 { + 4096 + } else { + if region.size & 4095 != 0 { + region.size + 4096 - (region.size & 4095) + } else { + region.size + } + }; + + // Ignore the CSR region, since we explicitly define registers there. + if region_name == "csr" { + continue; + } + + // The current design doubles-up on this identifier, so bodge in a new name. + if region_name == "memlcd" { + region_name = "fbmem".to_string(); + } + + writeln!( + out, + "{}: Memory.MappedMemory @ sysbus 0x{:08x}", + region_name, region.base + )?; + writeln!(out, " size: 0x{:08x}", region_size)?; + writeln!(out)?; + } + writeln!(out)?; + Ok(()) +} + +fn print_peripherals( + peripherals: &[Peripheral], + constants: &[Constant], + out: &mut U, +) -> std::io::Result<()> { + use std::collections::HashMap; + let mut known_peripherals = HashMap::new(); + known_peripherals.insert("console", "UART.LiteX_UART"); + known_peripherals.insert("uart", "UART.LiteX_UART"); + known_peripherals.insert("app_uart", "UART.LiteX_UART"); + known_peripherals.insert("timer0", "Timers.LiteX_Timer_32"); + + known_peripherals.insert("memlcd", "Video.BetrustedLCD"); + known_peripherals.insert("keyboard", "Input.BetrustedKbd"); + known_peripherals.insert("trng_kernel", "Miscellaneous.BetrustedRNGKernel"); + known_peripherals.insert("trng_server", "Miscellaneous.BetrustedRNGServer"); + known_peripherals.insert("ticktimer", "Timers.TickTimer"); + writeln!(out, "// Platform Peripherals")?; + for peripheral in peripherals { + let lc_name = peripheral.name.to_lowercase(); + // let peripheral_size = if peripheral.size < 4096 { + // 4096 + // } else { + // peripheral.size + // }; + if let Some(renode_device) = known_peripherals.get(lc_name.as_str()) { + writeln!( + out, + "{}: {} @ sysbus 0x{:08x}", + lc_name, renode_device, peripheral.base + )?; + + // TODO: Get the frequency from the `constants` table under `CONFIG_CLOCK_FREQUENCY` + if lc_name == "timer0" { + let mut freq_found = false; + for constant in constants { + if constant.name == "CONFIG_CLOCK_FREQUENCY" { + writeln!(out, " frequency: {}", constant.value)?; + freq_found = true; + } + } + if !freq_found { + panic!("Couldn't discover clock frequency when creating timer0 object"); + } + } + + // Note: we skip the `size` value here, since peripherals don't have a known size. + + // Add the interrupt, if one exists. + if let Some(irq) = peripheral.interrupt.get(0) { + writeln!(out, " -> cpu @ {}", 1000 + irq.value)?; + } + } else { + writeln!(out, "// Unrecognized peripheral: {}", lc_name)?; + } + writeln!(out)?; + } + writeln!(out)?; + + Ok(()) +} + +pub fn parse_svd(src: T) -> Result { + let mut buf = Vec::new(); + let buf_reader = BufReader::new(src); + let mut reader = Reader::from_reader(buf_reader); + let mut description = Description::default(); + loop { + match reader.read_event(&mut buf) { + Ok(Event::Start(ref e)) => match e.name() { + b"peripherals" => { + description.peripherals = generate_peripherals(&mut reader)?; + } + b"vendorExtensions" => { + parse_vendor_extensions(&mut reader, &mut description)?; + } + _ => (), + }, + Ok(Event::Eof) => break, + Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e), + _ => (), + } + buf.clear(); + } + Ok(description) +} + +pub fn generate(src: T, dest: &mut U) -> Result<(), ParseError> { + let description = parse_svd(src)?; + + print_header(dest).or(Err(ParseError::WriteError))?; + print_peripherals(&description.peripherals, &description.constants, dest) + .or(Err(ParseError::WriteError))?; + print_memory_regions(&description.memory_regions, dest).or(Err(ParseError::WriteError))?; + print_footer(dest).or(Err(ParseError::WriteError))?; + + Ok(()) +} diff --git a/svd2repl/src/lib.rs b/svd2repl/src/lib.rs new file mode 100644 index 000000000..4a81ed72c --- /dev/null +++ b/svd2repl/src/lib.rs @@ -0,0 +1,15 @@ +mod generate; +pub use generate::*; + +#[cfg(test)] +mod tests { + use super::*; + use std::fs::{DirBuilder, File}; + #[test] + fn basic_generate() { + let src = File::open("examples/soc.svd").unwrap(); + DirBuilder::new().recursive(true).create("target").unwrap(); + let mut dest = File::create("target/example.rs").unwrap(); + generate(src, &mut dest).unwrap(); + } +} diff --git a/svd2repl/src/main.rs b/svd2repl/src/main.rs new file mode 100644 index 000000000..cb324f679 --- /dev/null +++ b/svd2repl/src/main.rs @@ -0,0 +1,44 @@ +mod generate; + +use anyhow::Context; +use clap::{App, Arg}; +use std::fs::File; +use std::io::{Read, Write}; + +fn main() -> anyhow::Result<()> { + let matches = App::new("svd2repl") + .about("Generate a Rebide Platform description from SVD files") + .arg( + Arg::with_name("input") + .help("Input SVD file") + .short("i") + .takes_value(true) + .value_name("FILE"), + ) + .arg( + Arg::with_name("output") + .help("Output .repl file or directory") + .short("o") + .takes_value(true) + .value_name("FILE"), + ) + .version(concat!( + env!("CARGO_PKG_VERSION"), + include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt")) + )) + .get_matches(); + + let src: Box = match matches.value_of("input") { + Some(file) => Box::new(File::open(file).context("Cannot open the SVD file")?), + None => Box::new(std::io::stdin()), + }; + + let mut dest: Box = match matches.value_of("output") { + None => Box::new(std::io::stdout()), + Some(path) => Box::new(File::create(path).context("Cannot open destination file")?), + }; + + generate::generate(src, &mut dest).context("Cannot generate output file")?; + + Ok(()) +} diff --git a/tools/src/tags/pnam.rs b/tools/src/tags/pnam.rs index bc062152f..86f6ee208 100644 --- a/tools/src/tags/pnam.rs +++ b/tools/src/tags/pnam.rs @@ -1,7 +1,7 @@ use crate::xous_arguments::{XousArgument, XousArgumentCode, XousSize}; +use std::collections::BTreeMap; use std::fmt; use std::io; -use std::collections::BTreeMap; #[derive(Debug)] pub struct ProcessNames { @@ -21,7 +21,9 @@ impl fmt::Display for ProcessNames { impl ProcessNames { pub fn new() -> ProcessNames { - ProcessNames { names: BTreeMap::new() } + ProcessNames { + names: BTreeMap::new(), + } } pub fn set(&mut self, pid: u32, name: &str) { @@ -41,7 +43,7 @@ impl XousArgument for ProcessNames { size += 4; size += val.len(); // Pad it to 4-bytes - size += (4-(val.len() & 3))&3; + size += (4 - (val.len() & 3)) & 3; } size as XousSize } @@ -54,7 +56,7 @@ impl XousArgument for ProcessNames { written += output.write(name.as_bytes())?; // Pad it to 4-bytes - for _ in 0..(4-(name.len() & 3))&3 { + for _ in 0..(4 - (name.len() & 3)) & 3 { written += output.write(&[0])?; } } diff --git a/tools/usb_update.py b/tools/usb_update.py index ca58a5f16..164500362 100755 --- a/tools/usb_update.py +++ b/tools/usb_update.py @@ -436,7 +436,7 @@ def main(): LOC_WF200 = 0x07F80000 LOC_EC = 0x07FCE000 else: - print("SoC is from an unknow rev, use --force to continue anyways with v0.8 firmware offsets") + print("SoC is from an unknow rev '{}', use --force to continue anyways with v0.8 firmware offsets".format(pc_usb.load_csrs())) exit(1) vexdbg_addr = int(pc_usb.regions['vexriscv_debug'][0], 0) diff --git a/xous-rs/Cargo.toml b/xous-rs/Cargo.toml index f2795651f..c1a211689 100644 --- a/xous-rs/Cargo.toml +++ b/xous-rs/Cargo.toml @@ -1,10 +1,12 @@ [package] name = "xous" -version = "0.8.0" +version = "0.8.3" authors = ["Sean Cross "] edition = "2018" license = "MIT OR Apache-2.0" description = "System call interface for Xous" +repository = "https://github.com/betrusted-io/xous-core/" +homepage = "https://betrusted.io/" [dependencies] bitflags = {version = "1", optional = true } diff --git a/xous-rs/src/arch/hosted.rs b/xous-rs/src/arch/hosted.rs index ca1e586a8..7efe75c4c 100644 --- a/xous-rs/src/arch/hosted.rs +++ b/xous-rs/src/arch/hosted.rs @@ -297,9 +297,7 @@ fn xous_address() -> SocketAddr { .unwrap_or_else(default_xous_address) } -pub fn create_thread_0_pre( - _f: &fn() -> U, -) -> core::result::Result +pub fn create_thread_0_pre(_f: &fn() -> U) -> core::result::Result where U: Send + 'static, { diff --git a/xous-rs/src/arch/native.rs b/xous-rs/src/arch/native.rs index bcebc89dd..bbce6c22e 100644 --- a/xous-rs/src/arch/native.rs +++ b/xous-rs/src/arch/native.rs @@ -70,7 +70,10 @@ pub struct ProcessInit { pub key: ProcessKey, } -pub struct WaitHandle(core::marker::PhantomData); +pub struct WaitHandle { + tid: TID, + data: core::marker::PhantomData, +} pub struct ProcessHandle(()); pub fn thread_to_args(syscall: usize, init: &ThreadInit) -> [usize; 8] { @@ -130,8 +133,9 @@ where todo!() } -pub fn wait_thread(_joiner: WaitHandle) -> crate::SysCallResult { - todo!() +pub fn wait_thread(joiner: WaitHandle) -> crate::SysCallResult { + let call = crate::SysCall::JoinThread(joiner.tid); + crate::syscall::rsyscall(call) } pub fn process_to_args(call: usize, init: &ProcessInit) -> [usize; 8] { @@ -359,12 +363,15 @@ pub fn create_thread_n_post( _arg2: usize, _arg3: usize, _arg4: usize, - _thread_id: TID, + thread_id: TID, ) -> core::result::Result, crate::Error> where U: Send + 'static, { - Ok(WaitHandle(core::marker::PhantomData)) + Ok(WaitHandle { + tid: thread_id, + data: core::marker::PhantomData, + }) } pub fn wait_process(_joiner: ProcessHandle) -> crate::SysCallResult { diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index c8abc41b4..4b68e486e 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -413,6 +413,34 @@ impl Message { }) } + pub fn new_lend( + id: usize, + buf: MemoryRange, + offset: Option, + valid: Option, + ) -> crate::Message { + Message::Borrow(crate::MemoryMessage { + id, + buf, + offset, + valid, + }) + } + + pub fn new_lend_mut( + id: usize, + buf: MemoryRange, + offset: Option, + valid: Option, + ) -> crate::Message { + Message::MutableBorrow(crate::MemoryMessage { + id, + buf, + offset, + valid, + }) + } + /// Determine whether the specified Message will block pub fn is_blocking(&self) -> bool { match *self { diff --git a/xous-rs/src/lib.rs b/xous-rs/src/lib.rs index d60363484..e7974837d 100644 --- a/xous-rs/src/lib.rs +++ b/xous-rs/src/lib.rs @@ -155,8 +155,7 @@ macro_rules! maybe_main { try_send_message(conn, Message::Scalar(panic_start_msg)).ok(); } wait_event(); - terminate_process(); - loop {} + terminate_process(1); } extern "Rust" { diff --git a/xous-rs/src/names.rs b/xous-rs/src/names.rs index 2bd0cd5cc..0188a3cbc 100644 --- a/xous-rs/src/names.rs +++ b/xous-rs/src/names.rs @@ -26,7 +26,7 @@ Here is the allocation so far: */ -pub const GID_KEYBOARD_KEYSTATE_EVENT: usize = 0x01_000000; -pub const GID_KEYBOARD_RAW_KEYSTATE_EVENT: usize = 0x01_000001; +pub const GID_KEYBOARD_KEYSTATE_EVENT: usize = 0x01_000000; +pub const GID_KEYBOARD_RAW_KEYSTATE_EVENT: usize = 0x01_000001; -pub const GID_COM_BATTSTATS_EVENT: usize = 0x02_000000; +pub const GID_COM_BATTSTATS_EVENT: usize = 0x02_000000; diff --git a/xous-rs/src/stringbuffer.rs b/xous-rs/src/stringbuffer.rs index c157e8df3..cdf0b6f93 100644 --- a/xous-rs/src/stringbuffer.rs +++ b/xous-rs/src/stringbuffer.rs @@ -1,13 +1,13 @@ use crate::{ - map_memory, send_message, unmap_memory, Error, MemoryFlags, MemoryMessage, MemoryRange, - MemorySize, Message, Result, CID, + map_memory, send_message, unmap_memory, Error, MemoryMessage, MemoryRange, MemorySize, Message, + Result, CID, }; /// A buffered String suitable for sending across as a message pub struct StringBuffer<'a> { /// The backing store for this string, as a mutable pointer to /// page-aligned memory. - bytes: &'a mut [u8], + bytes: Option<&'a mut [u8]>, // Current length of the string, in bytes length: u32, @@ -28,9 +28,7 @@ impl<'a> StringBuffer<'a> { /// resized as soon as data is written to it. pub fn new() -> Self { StringBuffer { - bytes: unsafe { - core::slice::from_raw_parts_mut(core::ptr::NonNull::dangling().as_ptr(), 0) - }, + bytes: None, length: 0, should_free: true, memory_message: None, @@ -46,7 +44,10 @@ impl<'a> StringBuffer<'a> { 0x1000 - (capacity & 0xFFF) }; - let flags = MemoryFlags::R | MemoryFlags::W; + #[cfg(feature = "bit-flags")] + let flags = crate::MemoryFlags::R | crate::MemoryFlags::W; + #[cfg(not(feature = "bit-flags"))] + let flags = 0b0000_0010 | 0b0000_0100; // Allocate enough memory to hold the requested data let new_mem = map_memory( @@ -62,9 +63,9 @@ impl<'a> StringBuffer<'a> { valid.size = MemorySize::new(capacity + remainder).unwrap(); StringBuffer { - bytes: unsafe { + bytes: Some(unsafe { core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), capacity + remainder) - }, + }), length: 0, should_free: true, memory_message: None, @@ -85,29 +86,40 @@ impl<'a> StringBuffer<'a> { // If the new size is the same as the current size, don't do anything. let rounded_new_capacity = new_capacity + remainder; - if rounded_new_capacity == self.bytes.len() { + if rounded_new_capacity == self.bytes.as_ref().map(|b| b.len()).unwrap_or(0) { return; } - let flags = MemoryFlags::R | MemoryFlags::W; + #[cfg(feature = "bit-flags")] + let flags = crate::MemoryFlags::R | crate::MemoryFlags::W; + #[cfg(not(feature = "bit-flags"))] + let flags = 0b0000_0010 | 0b0000_0100; // Allocate enough memory to hold the new requested data - let new_mem = map_memory(None, None, rounded_new_capacity, flags) - .expect("Buffer: error in new()/map_memory"); - let new_slice = - unsafe { core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), rounded_new_capacity) }; + let new_slice = if rounded_new_capacity > 0 { + let new_mem = map_memory(None, None, rounded_new_capacity, flags) + .expect("Buffer: error in new()/map_memory"); + let new_slice = unsafe { + core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), rounded_new_capacity) + }; + // Copy the existing string to the new slice + for (dest_byte, src_byte) in new_slice + .iter_mut() + .zip(self.as_bytes()[0..self.len()].iter()) + { + *dest_byte = *src_byte; + } + Some(new_slice) + } else { + None + }; - // Copy the existing string to the new slice - for (dest_byte, src_byte) in new_slice.iter_mut().zip(self.bytes[0..self.len()].iter()) { - *dest_byte = *src_byte; - } - - let old_addr = self.bytes.as_ptr(); - let old_length = self.bytes.len(); - self.bytes = new_slice; - if old_length != 0 { + if let Some(old_slice) = self.bytes.take() { + let old_addr = old_slice.as_ptr(); + let old_length = old_slice.len(); unmap_memory(MemoryRange::new(old_addr as usize, old_length).unwrap()).unwrap(); } + self.bytes = new_slice; // If the string has shrunk, truncate the string. if new_capacity < self.len() { @@ -122,12 +134,12 @@ impl<'a> StringBuffer<'a> { let src = src.as_ref(); let mut s = Self::with_capacity(src.len()); // Copy the string into our backing store. - for (dest_byte, src_byte) in s.bytes.iter_mut().zip(src.as_bytes()) { + for (dest_byte, src_byte) in s.bytes.as_mut().unwrap().iter_mut().zip(src.as_bytes()) { *dest_byte = *src_byte; } // Set the string length to the length of the passed-in String, // or the maximum possible length. Which ever is smaller. - s.length = s.bytes.len().min(src.as_bytes().len()) as u32; + s.length = s.as_bytes().len().min(src.as_bytes().len()) as u32; // If the string is not valid, set its length to 0. if s.as_str().is_err() { @@ -138,11 +150,27 @@ impl<'a> StringBuffer<'a> { } pub fn as_bytes(&self) -> &[u8] { - self.bytes + if let Some(bytes) = &self.bytes { + bytes + } else { + &[] + } + } + + pub fn as_bytes_mut(&mut self) -> &mut [u8] { + if let Some(bytes) = self.bytes.as_mut() { + bytes + } else { + &mut [] + } } pub fn as_str(&self) -> core::result::Result<&str, core::str::Utf8Error> { - core::str::from_utf8(&self.bytes[0..self.len()]) + if let Some(bytes) = &self.bytes { + core::str::from_utf8(&bytes[0..self.len()]) + } else { + Ok("") + } } pub fn len(&self) -> usize { @@ -162,23 +190,34 @@ impl<'a> StringBuffer<'a> { } pub fn to_str(&self) -> &str { - unsafe { core::str::from_utf8_unchecked(&self.bytes[0..self.len()]) } + if let Some(bytes) = &self.bytes { + unsafe { core::str::from_utf8_unchecked(&bytes[0..self.len()]) } + } else { + "" + } } fn create_memory_message(&self, id: u32) -> MemoryMessage { - let backing_store = MemoryRange::new(self.bytes.as_ptr() as _, self.bytes.len()).unwrap(); - MemoryMessage { - id: id as usize, - buf: backing_store, - offset: None, - valid: MemorySize::new(self.len()), + if let Some(bytes) = &self.bytes { + let backing_store = MemoryRange::new(bytes.as_ptr() as _, bytes.len()).unwrap(); + MemoryMessage { + id: id as usize, + buf: backing_store, + offset: None, + valid: MemorySize::new(self.len()), + } + } else { + panic!("Tried to create a memory message with no string!"); } } pub unsafe fn from_memory_message(mem: &'a MemoryMessage) -> Self { StringBuffer { // range: mem.buf, - bytes: core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr(), mem.buf.len()), + bytes: Some(core::slice::from_raw_parts_mut( + mem.buf.as_mut_ptr(), + mem.buf.len(), + )), length: mem.valid.map(|v| v.get()).unwrap_or(0) as u32, // offset: mem.offset, should_free: false, @@ -189,7 +228,10 @@ impl<'a> StringBuffer<'a> { pub unsafe fn from_memory_message_mut(mem: &'a mut MemoryMessage) -> Self { StringBuffer { // range: mem.buf, - bytes: core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr(), mem.buf.len()), + bytes: Some(core::slice::from_raw_parts_mut( + mem.buf.as_mut_ptr(), + mem.buf.len(), + )), length: mem.valid.map(|v| v.get()).unwrap_or(0) as u32, // valid: mem.buf, // offset: mem.offset, @@ -239,7 +281,7 @@ impl<'a> core::fmt::Write for StringBuffer<'a> { // Copy the data over let length = self.len(); - for (dest, src) in self.bytes[length..].iter_mut().zip(s.as_bytes()) { + for (dest, src) in self.as_bytes_mut()[length..].iter_mut().zip(s.as_bytes()) { *dest = *src; } self.length += s.len() as u32; @@ -264,7 +306,8 @@ impl<'a> core::convert::AsRef for StringBuffer<'a> { impl<'a> PartialEq for StringBuffer<'a> { fn eq(&self, other: &Self) -> bool { - self.length == other.length && self.bytes[..self.len()] == other.bytes[..other.len()] + self.length == other.length + && self.as_bytes()[..self.len()] == other.as_bytes()[..other.len()] } } @@ -272,8 +315,9 @@ impl<'a> Eq for StringBuffer<'a> {} impl<'a> Drop for StringBuffer<'a> { fn drop(&mut self) { - if self.should_free { - let range = MemoryRange::new(self.bytes.as_ptr() as _, self.bytes.len()).unwrap(); + if self.should_free && self.as_bytes().len() != 0 { + let range = + MemoryRange::new(self.as_bytes().as_ptr() as _, self.as_bytes().len()).unwrap(); unmap_memory(range).expect("Buffer: failed to drop memory"); } } diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 1f183e111..7f3650f53 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -274,7 +274,7 @@ pub enum SysCall { CreateProcess(ProcessInit), /// Terminate the current process, closing all server connections. - TerminateProcess, + TerminateProcess(u32), /// Shut down the entire system Shutdown, @@ -318,6 +318,9 @@ pub enum SysCall { /// in a future reconnection. Disconnect(CID), + /// Waits for a thread to finish, and returns the return value of that thread. + JoinThread(TID), + /// This syscall does not exist. It captures all possible /// arguments so detailed analysis can be performed. Invalid(usize, usize, usize, usize, usize, usize, usize), @@ -359,6 +362,7 @@ pub enum SysCallNumber { GetProcessId = 33, DestroyServer = 34, Disconnect = 35, + JoinThread = 36, Invalid, } @@ -400,6 +404,7 @@ impl SysCallNumber { 33 => GetProcessId, 34 => DestroyServer, 35 => Disconnect, + 36 => JoinThread, _ => Invalid, } } @@ -630,9 +635,9 @@ impl SysCall { SysCall::CreateProcess(init) => { crate::arch::process_to_args(SysCallNumber::CreateProcess as usize, init) } - SysCall::TerminateProcess => [ + SysCall::TerminateProcess(exit_code) => [ SysCallNumber::TerminateProcess as usize, - 0, + *exit_code as usize, 0, 0, 0, @@ -721,6 +726,16 @@ impl SysCall { 0, 0, ], + SysCall::JoinThread(tid) => [ + SysCallNumber::JoinThread as usize, + *tid as usize, + 0, + 0, + 0, + 0, + 0, + 0, + ], SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7) => [ SysCallNumber::Invalid as usize, *a1, @@ -810,7 +825,7 @@ impl SysCall { SysCallNumber::CreateProcess => { SysCall::CreateProcess(crate::arch::args_to_process(a1, a2, a3, a4, a5, a6, a7)?) } - SysCallNumber::TerminateProcess => SysCall::TerminateProcess, + SysCallNumber::TerminateProcess => SysCall::TerminateProcess(a1 as u32), SysCallNumber::Shutdown => SysCall::Shutdown, SysCallNumber::TryConnect => { SysCall::TryConnect(SID::from_u32(a1 as _, a2 as _, a3 as _, a4 as _)) @@ -882,6 +897,7 @@ impl SysCall { SysCall::DestroyServer(SID::from_u32(a1 as _, a2 as _, a3 as _, a4 as _)) } SysCallNumber::Disconnect => SysCall::Disconnect(a1 as _), + SysCallNumber::JoinThread => SysCall::JoinThread(a1 as _), SysCallNumber::Invalid => SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7), }) } @@ -1338,8 +1354,8 @@ pub fn send_message(connection: CID, message: Message) -> core::result::Result ! { + rsyscall(SysCall::TerminateProcess(exit_code)).expect("terminate_process returned an error"); panic!("process didn't terminate"); } @@ -1481,7 +1497,7 @@ where }) } -/// Wait for a thread to finish +/// Wait for a thread to finish. This is equivalent to `join_thread` pub fn wait_thread(joiner: crate::arch::WaitHandle) -> SysCallResult { crate::arch::wait_thread(joiner) } @@ -1560,6 +1576,9 @@ pub fn destroy_server(sid: SID) -> core::result::Result<(), Error> { }) } +/// Disconnect the specified connection ID and mark it as free. This +/// connection ID may be reused by the server in the future, so ensure +/// no other threads are using the connection ID before disposing of it. pub unsafe fn disconnect(cid: CID) -> core::result::Result<(), Error> { rsyscall(SysCall::Disconnect(cid)).and_then(|result| { if let Result::Ok = result { @@ -1570,6 +1589,26 @@ pub unsafe fn disconnect(cid: CID) -> core::result::Result<(), Error> { }) } +/// Block the current thread and wait for the specified thread to +/// return. Returns the return value of the thread. +/// +/// # Errors +/// +/// * **ThreadNotAvailable**: The thread could not be found, or was not sleeping. +pub fn join_thread(tid: TID) -> core::result::Result { + rsyscall(SysCall::JoinThread(tid)).and_then(|result| { + if let Result::Scalar1(val) = result { + Ok(val) + } else if let Result::Error(Error::ThreadNotAvailable) = result { + Err(Error::ThreadNotAvailable) + } else { + Err(Error::InternalError) + } + }) +} + +/// Perform a raw syscall and return the result. This will transform +/// `xous::Result::Error(e)` into an `Err(e)`. pub fn rsyscall(call: SysCall) -> SysCallResult { let mut ret = Result::Ok; let args = call.as_args(); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index cc0a105a9..fc4e0c3b7 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -102,22 +102,31 @@ fn try_main() -> Result<(), DynError> { let task = env::args().nth(1); match task.as_deref() { Some("renode-image") => renode_image(false, &hw_pkgs)?, - Some("renode-test") => renode_image( - false, - &cbtest_pkgs, - )?, + Some("renode-test") => renode_image(false, &cbtest_pkgs)?, Some("renode-image-debug") => renode_image(true, &hw_pkgs)?, Some("run") => run(false, &hw_pkgs)?, Some("hw-image") => build_hw_image(false, env::args().nth(2), &hw_pkgs, None)?, Some("benchmark") => build_hw_image(false, env::args().nth(2), &benchmark_pkgs, None)?, Some("minimal") => build_hw_image(false, env::args().nth(2), &minimal_pkgs, None)?, Some("cbtest") => build_hw_image(false, env::args().nth(2), &cbtest_pkgs, None)?, - Some("trng-test") => build_hw_image(false, env::args().nth(2), &hw_pkgs, - Some(&["--features", "ringosctest", "--features", "avalanchetest"]))?, - Some("ro-test") => build_hw_image(false, env::args().nth(2), &hw_pkgs, - Some(&["--features", "ringosctest"]))?, - Some("av-test") => build_hw_image(false, env::args().nth(2), &hw_pkgs, - Some(&["--features", "avalanchetest"]))?, + Some("trng-test") => build_hw_image( + false, + env::args().nth(2), + &hw_pkgs, + Some(&["--features", "ringosctest", "--features", "avalanchetest"]), + )?, + Some("ro-test") => build_hw_image( + false, + env::args().nth(2), + &hw_pkgs, + Some(&["--features", "ringosctest"]), + )?, + Some("av-test") => build_hw_image( + false, + env::args().nth(2), + &hw_pkgs, + Some(&["--features", "avalanchetest"]), + )?, Some("sr-test") => build_hw_image(false, env::args().nth(2), &sr_pkgs, None)?, Some("debug") => run(true, &hw_pkgs)?, Some("burn-kernel") => update_usb(true, false, false)?, @@ -209,7 +218,12 @@ fn update_usb(do_kernel: bool, do_loader: bool, do_soc: bool) -> Result<(), DynE Ok(()) } -fn build_hw_image(debug: bool, svd: Option, packages: &[&str], extra_args: Option<&[&str]>) -> Result<(), DynError> { +fn build_hw_image( + debug: bool, + svd: Option, + packages: &[&str], + extra_args: Option<&[&str]>, +) -> Result<(), DynError> { let svd_file = match svd { Some(s) => s, None => return Err("svd file not specified".into()), @@ -233,7 +247,13 @@ fn build_hw_image(debug: bool, svd: Option, packages: &[&str], extra_arg pkg_path.push(pkg); init.push(pkg_path); } - let mut loader = build(&["loader"], debug, Some(TARGET), Some("loader".into()), None)?; + let mut loader = build( + &["loader"], + debug, + Some(TARGET), + Some("loader".into()), + None, + )?; loader.push(PathBuf::from("loader")); let output_bundle = create_image(&kernel, &init, debug, MemorySpec::SvdFile(svd_file))?; @@ -256,7 +276,8 @@ fn build_hw_image(debug: bool, svd: Option, packages: &[&str], extra_arg "--", loader.as_os_str().to_str().unwrap(), loader_bin.as_os_str().to_str().unwrap(), - ]).status()?; + ]) + .status()?; if !status.success() { return Err("cargo build failed".into()); } @@ -290,7 +311,13 @@ fn renode_image(debug: bool, packages: &[&str]) -> Result<(), DynError> { pkg_path.push(pkg); init.push(pkg_path); } - build(&["loader"], debug, Some(TARGET), Some("loader".into()), None)?; + build( + &["loader"], + debug, + Some(TARGET), + Some("loader".into()), + None, + )?; create_image( &kernel, @@ -299,6 +326,24 @@ fn renode_image(debug: bool, packages: &[&str]) -> Result<(), DynError> { MemorySpec::SvdFile("emulation/soc/renode.svd".into()), )?; + // Regenerate the Platform file + let status = Command::new(cargo()) + .current_dir(project_root()) + .args(&[ + "run", + "-p", + "svd2repl", + "--", + "-i", + "emulation/soc/renode.svd", + "-o", + "emulation/soc/betrusted-soc.repl", + ]) + .status()?; + if !status.success() { + Err("Unable to regenerate Renode platform file")?; + } + Ok(()) } @@ -346,7 +391,13 @@ fn run(debug: bool, init: &[&str]) -> Result<(), DynError> { } fn build_kernel(debug: bool) -> Result { - let mut path = build(&["kernel"], debug, Some(TARGET), Some("kernel".into()), None)?; + let mut path = build( + &["kernel"], + debug, + Some(TARGET), + Some("kernel".into()), + None, + )?; path.push("kernel"); Ok(path) }