diff --git a/emulation/peripherals/WF200.cs b/emulation/peripherals/WF200.cs index 0857b4b51..6b6c62e40 100644 --- a/emulation/peripherals/WF200.cs +++ b/emulation/peripherals/WF200.cs @@ -623,7 +623,7 @@ namespace Antmicro.Renode.Peripherals.Network.Betrusted return; } - var req = (WfxMessage.Requests)(request.Id); + var req = (WfxMessage.Requests)request.Id; if (req == WfxMessage.Requests.Configuration) { var message = new WfxMessage(WfxMessage.Confirmations.Configuration, okayResponse, configurationOffset); @@ -748,8 +748,8 @@ namespace Antmicro.Renode.Peripherals.Network.Betrusted sendFrameResponse[3] = 0; // uint16_t packet_id (from request) - sendFrameResponse[4] = (byte)(payload[2]); - sendFrameResponse[5] = (byte)(payload[3]); + sendFrameResponse[4] = payload[2]; + sendFrameResponse[5] = payload[3]; sendFrameResponse[6] = 0; // uint16_t reserved @@ -759,11 +759,14 @@ namespace Antmicro.Renode.Peripherals.Network.Betrusted sendFrameResponse[8] = 0; sendFrameResponse[9] = 0x30; - var frame_data = payload.GetRange(8, payload.Count - 8).ToArray(); + // Our bus is 16-bits, but sometimes we want to transmit an odd number of bytes. + // Support omitting the last byte if necessary. + var roundingError = payload[4] & 1; + var frame_data = payload.GetRange(8, payload.Count - 8 - roundingError).ToArray(); var packet_data_length = (payload[4] << 0) | (payload[5] << 8) | (payload[6] << 16) | (payload[7] << 24); if (frame_data.Length != packet_data_length) { - this.Log(LogLevel.Error, "Warning: host reported payload length of {0}, but transmitted a payload length of {1}", packet_data_length, frame_data.Length); + this.Log(LogLevel.Warning, "host reported payload length of {0}, but transmitted a payload length of {1}", packet_data_length, frame_data.Length); } if (!Misc.TryCreateFrameOrLogWarning(this, frame_data, out var frame, addCrc: true)) { diff --git a/kernel/src/arch/mod.rs b/kernel/src/arch/mod.rs index 750a5ecfd..21590b5b7 100644 --- a/kernel/src/arch/mod.rs +++ b/kernel/src/arch/mod.rs @@ -16,9 +16,9 @@ mod riscv; #[cfg(target_arch = "riscv32")] pub use crate::arch::riscv::*; -#[cfg(all(target_arch = "riscv64", not(target_os = "xous")))] +#[cfg(all(target_arch = "riscv64", not(baremetal)))] mod riscv; -#[cfg(all(target_arch = "riscv64", not(target_os = "xous")))] +#[cfg(all(target_arch = "riscv64", not(baremetal)))] pub use riscv::*; #[cfg(all(target_arch = "x86_64", not(any(windows, unix))))] diff --git a/kernel/src/main.rs b/kernel/src/main.rs index eff27e065..0043492fb 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -87,7 +87,7 @@ pub extern "C" fn kmain() { // Note that at this point, no new direct children of INIT may be created. let mut pid = None; - #[cfg(not(any(target_os = "none", target_os = "xous", all(ci, test))))] + #[cfg(not(any(baremetal, all(ci, test))))] { use std::panic; panic::set_hook(Box::new(|arg| { diff --git a/kernel/src/mem.rs b/kernel/src/mem.rs index bf9c27e28..32b9764fd 100644 --- a/kernel/src/mem.rs +++ b/kernel/src/mem.rs @@ -501,23 +501,6 @@ impl MemoryManager { ) } - // /// Transfer ownership of a page without moving it. This is a very - // /// specialized function which should only be used when creating a - // /// brand-new process. - // pub fn move_page_ownership( - // &mut self, - // src_addr: *mut u8, - // src_pid: PID, - // dest_pid: PID, - // ) -> Result<(), xous_kernel::Error> { - // let phys_addr = crate::arch::mem::virt_to_phys(src_addr as usize)?; - // self.claim_release_move( - // phys_addr as *mut usize, - // dest_pid, - // ClaimReleaseMove::Move(src_pid), - // ) - // } - /// Mark the page in the current process as being lent. If the borrow is /// read-only, then additionally remove the "write" bit on it. If the page /// is writable, then remove it from the current process until the borrow is diff --git a/kernel/src/services.rs b/kernel/src/services.rs index 7e1ddfa57..ceaf8947c 100644 --- a/kernel/src/services.rs +++ b/kernel/src/services.rs @@ -568,17 +568,6 @@ impl SystemServices { Ok(()) } - // #[cfg(not(baremetal))] - // pub fn make_callback_to( - // &mut self, - // _pid: PID, - // _pc: *const usize, - // _irq_no: usize, - // _arg: *mut usize, - // ) -> Result<(), xous_kernel::Error> { - // Err(xous_kernel::Error::UnhandledSyscall) - // } - /// Create a stack frame in the specified process and jump to it. /// 1. Pause the current process and switch to the new one /// 2. Save the process state, if it hasn't already been saved @@ -876,7 +865,7 @@ impl SystemServices { } // Activate this process on this CPU - #[cfg(not(target_os = "xous"))] + #[cfg(not(baremetal))] process.activate()?; ArchProcess::current().set_tid(new_thread)?; process.current_thread = new_thread as _; @@ -934,11 +923,6 @@ impl SystemServices { panic!("PID {} TID {} was not in a state to be switched from: {:?}", pid, tid, other); } }; - // log_process_update(file!(), line!(), process, old_state); - // klog!( - // "unschedule_thread({}:{}): New state is {:?}", - // pid, tid, process.state - // ); Ok(()) } @@ -950,14 +934,6 @@ impl SystemServices { } } panic!("PID {} TID {} not running: {:?}", pid, tid, process.state); - // match &process.state { - // &ProcessState::Sleeping => false, - // &ProcessState::Ready(_x) => false, - // &ProcessState::Free => false, - // &ProcessState::Running(x) if x & (1 << tid) != 0 => false, - // &ProcessState::Setup(_) => false, - // &ProcessState::Running(_) => true, - // } } pub fn set_thread_result( diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 9f9c51d8d..d4791cdcf 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -175,7 +175,7 @@ fn send_message(pid: PID, tid: TID, cid: CID, message: Message) -> SysCallResult // Mark the server's context as "Ready". If this fails, return the context // to the blocking list. - #[cfg(target_os = "xous")] + #[cfg(baremetal)] ss.ready_thread(server_pid, server_tid).map_err(|e| { ss.server_from_sidx_mut(sidx) .expect("server couldn't be located") @@ -709,27 +709,6 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR let range = mm.map_range(phys_ptr, virt_ptr, size.get(), pid, req_flags, MemoryType::Default)?; - // If we're handing back an address in main RAM, zero it out. If - // phys is 0, then the page will be lazily allocated, so we - // don't need to do this. - // if !phys_ptr.is_null() { - // for (phys, virt) in (phys_ptr as usize..range.len()).step_by(PAGE_SIZE).zip( - // (range.as_ptr() as usize..(range.as_ptr() as usize + range.len())) - // .step_by(PAGE_SIZE), - // ) { - // // Zero out the virtual page if it's in main memory - // if mm.is_main_memory(phys as *mut u8) { - // let start = virt as *mut usize; - // for offset in 0..(PAGE_SIZE / core::mem::size_of::()) { - // unsafe { start.add(offset).write_volatile(0) }; - // } - // } - - // // Hand the virtual page to the process - // crate::arch::mem::hand_page_to_user(virt as *mut u8) - // .expect("couldn't hand page to user"); - // } - if !phys_ptr.is_null() { if mm.is_main_memory(phys_ptr) { let range_start = range.as_mut_ptr() as *mut usize; @@ -883,7 +862,7 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR SysCall::CreateThread(thread_init) => SystemServices::with_mut(|ss| { ss.create_thread(pid, thread_init).map(|new_tid| { // Set the return value of the existing thread to be the new thread ID - if cfg!(target_os = "xous") { + if cfg!(baremetal) { // Immediately switch to the new thread ss.switch_to_thread(pid, Some(new_tid)).expect("couldn't activate new thread"); ss.set_thread_result(pid, tid, xous_kernel::Result::ThreadID(new_tid)) diff --git a/xous-rs/src/arch/mod.rs b/xous-rs/src/arch/mod.rs index c283fa3f0..d6368d389 100644 --- a/xous-rs/src/arch/mod.rs +++ b/xous-rs/src/arch/mod.rs @@ -1,16 +1,24 @@ -#[cfg(all(target_os = "xous", target_arch = "arm"))] +#[cfg(all(any(target_os = "none", target_os = "xous"), target_arch = "arm"))] mod arm; -#[cfg(all(target_os = "xous", target_arch = "arm"))] +#[cfg(all(any(target_os = "none", target_os = "xous"), target_arch = "arm"))] pub use arm::*; -#[cfg(all(target_os = "xous", target_arch = "riscv32"))] +#[cfg(all(any(target_os = "xous", target_os = "none"), target_arch = "riscv32"))] pub mod riscv; -#[cfg(all(target_os = "xous", target_arch = "riscv32"))] +#[cfg(all(any(target_os = "xous", target_os = "none"), target_arch = "riscv32"))] pub use riscv::*; -#[cfg(all(not(feature = "processes-as-threads"), not(target_os = "xous"), not(target_arch = "arm"),))] +#[cfg(all( + not(feature = "processes-as-threads"), + not(any(target_os = "xous", target_os = "none")), + not(target_arch = "arm"), +))] pub mod hosted; -#[cfg(all(not(feature = "processes-as-threads"), not(target_os = "xous"), not(target_arch = "arm"),))] +#[cfg(all( + not(feature = "processes-as-threads"), + not(any(target_os = "xous", target_os = "none")), + not(target_arch = "arm"), +))] pub use hosted::*; #[cfg(feature = "processes-as-threads")] diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index 5c0957950..75f755ab2 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -55,7 +55,7 @@ pub const BASE_QUANTA_MS: u32 = 10; pub const BOOKEND_START: &str = "_|TT|_"; pub const BOOKEND_END: &str = "_|TE|_"; -#[cfg(not(target_os = "xous"))] +#[cfg(not(any(target_os = "xous", target_os = "none")))] use core::sync::atomic::AtomicU64; // Secretly, you can change this by setting the XOUS_SEED environment variable. @@ -64,7 +64,7 @@ use core::sync::atomic::AtomicU64; // The code that reads the varable this is all the way over in xous-rs\src\arch\hosted\mod.rs#29, and // it's glommed onto some other static process initialization code because I don't fully understand // what's going on over there. -#[cfg(not(target_os = "xous"))] +#[cfg(not(any(target_os = "xous", target_os = "none")))] pub static TESTING_RNG_SEED: AtomicU64 = AtomicU64::new(0); pub mod exceptions; diff --git a/xtask/src/builder.rs b/xtask/src/builder.rs index 8bcdf2723..72c130ead 100644 --- a/xtask/src/builder.rs +++ b/xtask/src/builder.rs @@ -126,6 +126,8 @@ pub(crate) struct Builder { stream: BuildStream, min_ver: String, target: Option, + /// The kernel might require a different target than the rest of the programs. + target_kernel: Option, utra_target: String, run_svd2repl: bool, locale_override: Option, @@ -154,6 +156,7 @@ impl Builder { stream: BuildStream::Release, min_ver: crate::MIN_XOUS_VERSION.to_string(), target: Some(crate::TARGET_TRIPLE_RISCV32.to_string()), + target_kernel: Some(crate::TARGET_TRIPLE_RISCV32_KERNEL.to_string()), utra_target: format!("precursor-{}", crate::PRECURSOR_SOC_VERSION).to_string(), run_svd2repl: false, locale_override: None, @@ -236,6 +239,7 @@ impl Builder { /// Configure for renode targets pub fn target_renode<'a>(&'a mut self) -> &'a mut Builder { self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); + self.target_kernel = Some(crate::TARGET_TRIPLE_RISCV32_KERNEL.to_string()); self.stream = BuildStream::Release; self.run_svd2repl = true; self.utra_target = "renode".to_string(); @@ -249,6 +253,7 @@ impl Builder { /// be just the gitrev of the soc version, not the entire feature name. pub fn target_precursor<'a>(&'a mut self, soc_version: &str) -> &'a mut Builder { self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); + self.target_kernel = Some(crate::TARGET_TRIPLE_RISCV32_KERNEL.to_string()); self.stream = BuildStream::Release; self.utra_target = format!("precursor-{}", soc_version).to_string(); self.run_svd2repl = false; @@ -259,6 +264,7 @@ impl Builder { pub fn target_precursor_no_image<'a>(&'a mut self, soc_version: &str) -> &'a mut Builder { self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); + self.target_kernel = Some(crate::TARGET_TRIPLE_RISCV32_KERNEL.to_string()); self.stream = BuildStream::Release; self.utra_target = format!("precursor-{}", soc_version).to_string(); self.run_svd2repl = false; @@ -269,6 +275,7 @@ impl Builder { /// Configure for ARM targets pub fn target_arm(&mut self) -> &mut Builder { self.target = Some(crate::TARGET_TRIPLE_ARM.to_string()); + self.target_kernel = Some(crate::TARGET_TRIPLE_ARM_KERNEL.to_string()); self.stream = BuildStream::Debug; self.utra_target = "atsama5d27".to_string(); self.run_svd2repl = false; @@ -280,6 +287,7 @@ impl Builder { /// Configure various Cramium targets pub fn target_cramium_fpga<'a>(&'a mut self) -> &'a mut Builder { self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); + self.target_kernel = Some(crate::TARGET_TRIPLE_RISCV32_KERNEL.to_string()); self.stream = BuildStream::Release; self.utra_target = "cramium-fpga".to_string(); self.run_svd2repl = false; @@ -290,6 +298,7 @@ impl Builder { pub fn target_cramium_soc<'a>(&'a mut self) -> &'a mut Builder { self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); + self.target_kernel = Some(crate::TARGET_TRIPLE_RISCV32_KERNEL.to_string()); self.stream = BuildStream::Release; self.utra_target = "cramium-soc".to_string(); self.run_svd2repl = false; @@ -591,16 +600,14 @@ impl Builder { } // ------ configure target generation feature flags ------ - let target = if self.utra_target.contains("renode") { + if self.utra_target.contains("renode") { self.features.push("renode".into()); self.loader_features.push("renode".into()); self.kernel_features.push("renode".into()); - Some(crate::TARGET_TRIPLE_RISCV32) } else if self.utra_target.contains("hosted") { self.features.push("hosted".into()); // there is no loader in hosed mode self.kernel_features.push("hosted".into()); - None } else if self.utra_target.contains("precursor") { self.features.push("precursor".into()); self.features.push(format!("utralib/{}", &self.utra_target)); @@ -608,11 +615,9 @@ impl Builder { self.kernel_features.push(format!("utralib/{}", &self.utra_target)); self.loader_features.push("precursor".into()); self.loader_features.push(format!("utralib/{}", &self.utra_target)); - Some(crate::TARGET_TRIPLE_RISCV32) } else if self.utra_target.contains("atsama5d2") { self.kernel_features.push("atsama5d27".into()); self.loader_features.push("atsama5d27".into()); - Some(crate::TARGET_TRIPLE_ARM) } else if self.utra_target.contains("cramium-fpga") { self.features.push("cramium-fpga".into()); self.features.push(format!("utralib/{}", &self.utra_target)); @@ -620,7 +625,6 @@ impl Builder { self.kernel_features.push(format!("utralib/{}", &self.utra_target)); self.loader_features.push("cramium-fpga".into()); self.loader_features.push(format!("utralib/{}", &self.utra_target)); - Some(crate::TARGET_TRIPLE_RISCV32) } else if self.utra_target.contains("cramium-soc") { self.features.push("cramium-soc".into()); self.features.push(format!("utralib/{}", &self.utra_target)); @@ -628,12 +632,12 @@ impl Builder { self.kernel_features.push(format!("utralib/{}", &self.utra_target)); self.loader_features.push("cramium-soc".into()); self.loader_features.push(format!("utralib/{}", &self.utra_target)); - Some(crate::TARGET_TRIPLE_RISCV32) } else { return Err("Target unknown: please check your UTRA target".into()); - }; + } crate::utils::ensure_compiler(&self.target.as_ref().map(|s| s.as_str()), false, false)?; + crate::utils::ensure_kernel_compiler(&self.target_kernel.as_ref().map(|s| s.as_str()), false)?; self.locale_override(); // apply the locale override // ------ build the services & apps ------ @@ -656,7 +660,7 @@ impl Builder { let mut services_path = self.builder( &[&self.services[..], &self.apps[..]].concat(), &self.features, - &target, + &self.target.as_deref(), self.stream, &vec![], false, @@ -735,7 +739,7 @@ impl Builder { let _ = self.builder( &vec![CrateSpec::Local("xous-kernel".into(), false)], &self.kernel_features, - &target, + &self.target_kernel.as_deref(), self.stream, &vec![], false, @@ -751,7 +755,7 @@ impl Builder { let kernel_path = self.builder( &vec![self.kernel.clone()], &self.kernel_features, - &target, + &self.target_kernel.as_deref(), self.stream, &kernel_extra, false, @@ -773,7 +777,7 @@ impl Builder { let loader = self.builder( &vec![self.loader.clone()], &self.loader_features, - &target, + &self.target_kernel.as_deref(), BuildStream::Release, // loader doesn't fit if you build with Debug &loader_extra, true, // loader builds without any default features diff --git a/xtask/src/main.rs b/xtask/src/main.rs index a68a3e815..f812cad08 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -42,8 +42,10 @@ const MIN_XOUS_VERSION: &str = "v0.9.8-791"; /// target triple for precursor builds pub(crate) const TARGET_TRIPLE_RISCV32: &str = "riscv32imac-unknown-xous-elf"; +pub(crate) const TARGET_TRIPLE_RISCV32_KERNEL: &str = "riscv32imac-unknown-none-elf"; /// target triple for ARM builds pub(crate) const TARGET_TRIPLE_ARM: &str = "armv7a-unknown-xous-elf"; +pub(crate) const TARGET_TRIPLE_ARM_KERNEL: &str = "armv7a-unknown-none-elf"; // because I have nowhere else to note this. The commit that contains the rkyv-enum derive // refactor to work around warnings thrown by Rust 1.64.0 is: f815ed85b58b671178fbf53b4cea34186fc406eb @@ -164,7 +166,12 @@ fn main() -> Result<(), Box> { match task.as_deref() { Some("install-toolkit") | Some("install-toolchain") => { let arg = env::args().nth(2); - ensure_compiler(&Some(TARGET_TRIPLE_RISCV32), true, arg.map(|x| x == "--force").unwrap_or(false))? + ensure_compiler( + &Some(TARGET_TRIPLE_RISCV32), + true, + arg.map(|x| x == "--force").unwrap_or(false), + )?; + ensure_kernel_compiler(&Some(TARGET_TRIPLE_RISCV32_KERNEL), true)?; } // ----- renode configs -------- Some("renode-image") => { diff --git a/xtask/src/utils.rs b/xtask/src/utils.rs index fc0cfe25a..f7c936702 100644 --- a/xtask/src/utils.rs +++ b/xtask/src/utils.rs @@ -3,7 +3,7 @@ use std::{ fs::{File, OpenOptions}, io::{Read, Write}, path::{Path, PathBuf}, - process::Command, + process::{Command, Stdio}, }; use lazy_static::lazy_static; @@ -25,49 +25,60 @@ lazy_static! { /// cache it inside an atomic boolean. If this is `true` then /// it means we can assume the check passed already. static DONE_COMPILER_CHECK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static DONE_KERNEL_COMPILER_CHECK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// Ensure we have a compatible compiler toolchain. We use a new Target, -/// and we want to give the user a friendly way of installing the latest -/// Rust toolchain. -pub(crate) fn ensure_compiler( - target: &Option<&str>, - force_install: bool, - remove_existing: bool, -) -> Result<(), String> { - use std::process::Stdio; - if DONE_COMPILER_CHECK.load(std::sync::atomic::Ordering::SeqCst) { - return Ok(()); - } +fn ask_to_install() -> bool { + let mut buffer = String::new(); + let stdin = std::io::stdin(); + let mut stdout = std::io::stdout(); + loop { + stdout.flush().unwrap(); + buffer.clear(); + stdin.read_line(&mut buffer).unwrap(); - /// Return the sysroot for the given target. If the target does not exist, - /// return None. - fn get_sysroot(target: Option<&str>) -> Result, String> { - let mut args = vec!["--print", "sysroot"]; - if let Some(target) = target { - args.push("--target"); - args.push(target); + let trimmed = buffer.trim(); + + if trimmed == "n" || trimmed == "N" { + return false; } - let sysroot_cmd = Command::new("rustc") - .stderr(Stdio::null()) - .stdout(Stdio::piped()) - .args(&args) - .spawn() - .expect("could not run rustc"); - let sysroot_output = sysroot_cmd.wait_with_output().unwrap(); - let have_toolchain = sysroot_output.status.success(); + if trimmed == "y" || trimmed == "Y" || trimmed.is_empty() { + return true; + } + println!(); + println!("Please answer 'y' or 'n'"); + } +} +/// Return the sysroot for the given target. If the target does not exist, +/// return None. +fn get_sysroot(target: Option<&str>, check_version: bool) -> Result, String> { + let mut args = vec!["--print", "sysroot"]; + if let Some(target) = target { + args.push("--target"); + args.push(target); + } - let toolchain_path = String::from_utf8(sysroot_output.stdout) - .map_err(|_| "Unable to find Rust sysroot".to_owned())? - .trim() - .to_owned(); + let sysroot_cmd = Command::new("rustc") + .stderr(Stdio::null()) + .stdout(Stdio::piped()) + .args(&args) + .spawn() + .expect("could not run rustc"); + let sysroot_output = sysroot_cmd.wait_with_output().unwrap(); + let have_toolchain = sysroot_output.status.success(); - // Look for the "RUST_VERSION" file to ensure it's compatible with this version. - if let Some(target) = target { - let mut version_path = PathBuf::from(&toolchain_path); - version_path.push("lib"); - version_path.push("rustlib"); - version_path.push(target); + let toolchain_path = String::from_utf8(sysroot_output.stdout) + .map_err(|_| "Unable to find Rust sysroot".to_owned())? + .trim() + .to_owned(); + + // Look for the "RUST_VERSION" file to ensure it's compatible with this version. + if let Some(target) = target { + let mut version_path = PathBuf::from(&toolchain_path); + version_path.push("lib"); + version_path.push("rustlib"); + version_path.push(target); + if check_version { version_path.push("RUST_VERSION"); if let Ok(mut vp) = File::open(&version_path) { let mut version_str = String::new(); @@ -91,14 +102,81 @@ pub(crate) fn ensure_compiler( // return Err("Outdated toolchain installed".to_owned()); return Ok(None); } + } else { + if !std::path::Path::new(&version_path).exists() { + return Ok(None); + } } + } - if have_toolchain { Ok(Some(toolchain_path)) } else { Ok(None) } + if have_toolchain { Ok(Some(toolchain_path)) } else { Ok(None) } +} + +pub(crate) fn ensure_kernel_compiler(target: &Option<&str>, force_install: bool) -> Result<(), String> { + if DONE_KERNEL_COMPILER_CHECK.load(std::sync::atomic::Ordering::SeqCst) { + return Ok(()); } // If the sysroot exists, then we're good. let target = target.unwrap_or(TARGET_TRIPLE_RISCV32); - if let Some(path) = get_sysroot(Some(target))? { + if get_sysroot(Some(target), false)?.is_some() { + DONE_COMPILER_CHECK.store(true, std::sync::atomic::Ordering::SeqCst); + return Ok(()); + } + + // If the terminal is a tty, or if toolchain installation is forced, + // download the latest toolchain. + if !atty::is(atty::Stream::Stdin) && !force_install { + return Err(format!("Toolchain for {} not found", target)); + } + + if force_install { + println!("Downloading toolchain"); + } else { + println!("Error: {} target was not found on this system!", target); + print!("Would you like this program to attempt to download and install it using rustup? [Y/n] "); + if ask_to_install() { + println!("Installing toolchain for {} via rustup", target); + } else { + return Err(format!("Please install the {} toolchain", target)); + } + } + + let rustup_command = Command::new("rustup") + .stderr(Stdio::null()) + .stdout(Stdio::piped()) + .args(&["target", "add", target]) + .spawn() + .map_err(|e| format!("could not run rustup: {}", e))?; + + let rustup_output = rustup_command.wait_with_output().unwrap(); + if !rustup_output.status.success() { + return Err(format!( + "could not add target {}: {}", + target, + String::from_utf8_lossy(&rustup_output.stdout) + )); + } + + DONE_COMPILER_CHECK.store(true, std::sync::atomic::Ordering::SeqCst); + Ok(()) +} + +/// Ensure we have a compatible compiler toolchain. We use a new Target, +/// and we want to give the user a friendly way of installing the latest +/// Rust toolchain. +pub(crate) fn ensure_compiler( + target: &Option<&str>, + force_install: bool, + remove_existing: bool, +) -> Result<(), String> { + if DONE_COMPILER_CHECK.load(std::sync::atomic::Ordering::SeqCst) { + return Ok(()); + } + + // If the sysroot exists, then we're good. + let target = target.unwrap_or(TARGET_TRIPLE_RISCV32); + if let Some(path) = get_sysroot(Some(target), true)? { let mut version_path = PathBuf::from(&path); version_path.push("lib"); version_path.push("rustlib"); @@ -125,7 +203,8 @@ pub(crate) fn ensure_compiler( } // Since no sysroot exists, we must download a new one. - let toolchain_path = get_sysroot(None)?.ok_or_else(|| "default toolchain not installed".to_owned())?; + let toolchain_path = + get_sysroot(None, true)?.ok_or_else(|| "default toolchain not installed".to_owned())?; // If the terminal is a tty, or if toolchain installation is forced, // download the latest toolchain. if !atty::is(atty::Stream::Stdin) && !force_install { @@ -139,34 +218,16 @@ pub(crate) fn ensure_compiler( } // Ask the user if they want to install the toolchain. - let mut buffer = String::new(); - let stdin = std::io::stdin(); - let mut stdout = std::io::stdout(); if force_install { println!("Downloading toolchain"); } else { println!("Error: Toolchain for {} was not found on this system!", target); - } - loop { - if force_install { - break; - } - print!("Would you like this program to attempt to download and install it? [Y/n] "); - stdout.flush().unwrap(); - buffer.clear(); - stdin.read_line(&mut buffer).unwrap(); - - let trimmed = buffer.trim(); - - if trimmed == "n" || trimmed == "N" { + if ask_to_install() { + println!("Installing toolchain for {} into {}", target, toolchain_path); + } else { return Err(format!("Please install the {} toolchain", target)); } - - if trimmed == "y" || trimmed == "Y" || trimmed.is_empty() { - break; - } - println!(); } fn get_toolchain_url(target: &str, major: u64, minor: u64, patch: u64) -> Result { @@ -239,31 +300,13 @@ pub(crate) fn ensure_compiler( println!("Downloading toolchain from {}...", toolchain_url); print!("Download in progress..."); - stdout.flush().unwrap(); + std::io::stdout().flush().ok(); let mut zip_data = vec![]; { - let agent = ureq::builder() - // .middleware(CounterMiddleware(shared_state.clone())) - .build(); + let agent = ureq::builder().build(); let mut freader = agent.get(&toolchain_url).call().map_err(|e| format!("{}", e))?.into_reader(); freader.read_to_end(&mut zip_data).map_err(|e| format!("{}", e))?; - // |total_bytes, bytes_so_far, _total_uploaded, _uploaded_so_far| { - // // If either number is infinite, don't print anything and just continue. - // if total_bytes.is_infinite() || bytes_so_far.is_infinite() { - // return true; - // } - - // // Display progress. - // print!( - // "\rDownload progress: {:3.02}% ", - // bytes_so_far / total_bytes * 100.0 - // ); - // stdout.flush().unwrap(); - - // // Return `true` to continue the transfer. - // true - // }, println!(); } println!("Download successful. Total data size is {} bytes", zip_data.len());