Merge pull request #500 from betrusted-io/rust-1.76.0-fixes

Build kernel and loader using `riscv32imac-unknown-none-elf` -- fixes 1.76.0
This commit is contained in:
bunnie 2024-02-06 14:36:01 +08:00 committed by GitHub
commit 21cf76855a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 179 additions and 176 deletions

View file

@ -623,7 +623,7 @@ namespace Antmicro.Renode.Peripherals.Network.Betrusted
return; return;
} }
var req = (WfxMessage.Requests)(request.Id); var req = (WfxMessage.Requests)request.Id;
if (req == WfxMessage.Requests.Configuration) if (req == WfxMessage.Requests.Configuration)
{ {
var message = new WfxMessage(WfxMessage.Confirmations.Configuration, okayResponse, configurationOffset); var message = new WfxMessage(WfxMessage.Confirmations.Configuration, okayResponse, configurationOffset);
@ -748,8 +748,8 @@ namespace Antmicro.Renode.Peripherals.Network.Betrusted
sendFrameResponse[3] = 0; sendFrameResponse[3] = 0;
// uint16_t packet_id (from request) // uint16_t packet_id (from request)
sendFrameResponse[4] = (byte)(payload[2]); sendFrameResponse[4] = payload[2];
sendFrameResponse[5] = (byte)(payload[3]); sendFrameResponse[5] = payload[3];
sendFrameResponse[6] = 0; sendFrameResponse[6] = 0;
// uint16_t reserved // uint16_t reserved
@ -759,11 +759,14 @@ namespace Antmicro.Renode.Peripherals.Network.Betrusted
sendFrameResponse[8] = 0; sendFrameResponse[8] = 0;
sendFrameResponse[9] = 0x30; 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); var packet_data_length = (payload[4] << 0) | (payload[5] << 8) | (payload[6] << 16) | (payload[7] << 24);
if (frame_data.Length != packet_data_length) 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)) if (!Misc.TryCreateFrameOrLogWarning(this, frame_data, out var frame, addCrc: true))
{ {

View file

@ -16,9 +16,9 @@ mod riscv;
#[cfg(target_arch = "riscv32")] #[cfg(target_arch = "riscv32")]
pub use crate::arch::riscv::*; pub use crate::arch::riscv::*;
#[cfg(all(target_arch = "riscv64", not(target_os = "xous")))] #[cfg(all(target_arch = "riscv64", not(baremetal)))]
mod riscv; mod riscv;
#[cfg(all(target_arch = "riscv64", not(target_os = "xous")))] #[cfg(all(target_arch = "riscv64", not(baremetal)))]
pub use riscv::*; pub use riscv::*;
#[cfg(all(target_arch = "x86_64", not(any(windows, unix))))] #[cfg(all(target_arch = "x86_64", not(any(windows, unix))))]

View file

@ -87,7 +87,7 @@ pub extern "C" fn kmain() {
// Note that at this point, no new direct children of INIT may be created. // Note that at this point, no new direct children of INIT may be created.
let mut pid = None; 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; use std::panic;
panic::set_hook(Box::new(|arg| { panic::set_hook(Box::new(|arg| {

View file

@ -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 /// 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 /// 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 /// is writable, then remove it from the current process until the borrow is

View file

@ -568,17 +568,6 @@ impl SystemServices {
Ok(()) 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. /// Create a stack frame in the specified process and jump to it.
/// 1. Pause the current process and switch to the new one /// 1. Pause the current process and switch to the new one
/// 2. Save the process state, if it hasn't already been saved /// 2. Save the process state, if it hasn't already been saved
@ -876,7 +865,7 @@ impl SystemServices {
} }
// Activate this process on this CPU // Activate this process on this CPU
#[cfg(not(target_os = "xous"))] #[cfg(not(baremetal))]
process.activate()?; process.activate()?;
ArchProcess::current().set_tid(new_thread)?; ArchProcess::current().set_tid(new_thread)?;
process.current_thread = new_thread as _; 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); 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(()) Ok(())
} }
@ -950,14 +934,6 @@ impl SystemServices {
} }
} }
panic!("PID {} TID {} not running: {:?}", pid, tid, process.state); 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( pub fn set_thread_result(

View file

@ -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 // Mark the server's context as "Ready". If this fails, return the context
// to the blocking list. // to the blocking list.
#[cfg(target_os = "xous")] #[cfg(baremetal)]
ss.ready_thread(server_pid, server_tid).map_err(|e| { ss.ready_thread(server_pid, server_tid).map_err(|e| {
ss.server_from_sidx_mut(sidx) ss.server_from_sidx_mut(sidx)
.expect("server couldn't be located") .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 = let range =
mm.map_range(phys_ptr, virt_ptr, size.get(), pid, req_flags, MemoryType::Default)?; 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::<usize>()) {
// 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 !phys_ptr.is_null() {
if mm.is_main_memory(phys_ptr) { if mm.is_main_memory(phys_ptr) {
let range_start = range.as_mut_ptr() as *mut usize; 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| { SysCall::CreateThread(thread_init) => SystemServices::with_mut(|ss| {
ss.create_thread(pid, thread_init).map(|new_tid| { ss.create_thread(pid, thread_init).map(|new_tid| {
// Set the return value of the existing thread to be the new thread ID // 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 // Immediately switch to the new thread
ss.switch_to_thread(pid, Some(new_tid)).expect("couldn't activate 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)) ss.set_thread_result(pid, tid, xous_kernel::Result::ThreadID(new_tid))

View file

@ -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; 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::*; 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; 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::*; 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; 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::*; pub use hosted::*;
#[cfg(feature = "processes-as-threads")] #[cfg(feature = "processes-as-threads")]

View file

@ -55,7 +55,7 @@ pub const BASE_QUANTA_MS: u32 = 10;
pub const BOOKEND_START: &str = "_|TT|_"; pub const BOOKEND_START: &str = "_|TT|_";
pub const BOOKEND_END: &str = "_|TE|_"; 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; use core::sync::atomic::AtomicU64;
// Secretly, you can change this by setting the XOUS_SEED environment variable. // 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 // 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 // it's glommed onto some other static process initialization code because I don't fully understand
// what's going on over there. // 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 static TESTING_RNG_SEED: AtomicU64 = AtomicU64::new(0);
pub mod exceptions; pub mod exceptions;

View file

@ -126,6 +126,8 @@ pub(crate) struct Builder {
stream: BuildStream, stream: BuildStream,
min_ver: String, min_ver: String,
target: Option<String>, target: Option<String>,
/// The kernel might require a different target than the rest of the programs.
target_kernel: Option<String>,
utra_target: String, utra_target: String,
run_svd2repl: bool, run_svd2repl: bool,
locale_override: Option<String>, locale_override: Option<String>,
@ -154,6 +156,7 @@ impl Builder {
stream: BuildStream::Release, stream: BuildStream::Release,
min_ver: crate::MIN_XOUS_VERSION.to_string(), min_ver: crate::MIN_XOUS_VERSION.to_string(),
target: Some(crate::TARGET_TRIPLE_RISCV32.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(), utra_target: format!("precursor-{}", crate::PRECURSOR_SOC_VERSION).to_string(),
run_svd2repl: false, run_svd2repl: false,
locale_override: None, locale_override: None,
@ -236,6 +239,7 @@ impl Builder {
/// Configure for renode targets /// Configure for renode targets
pub fn target_renode<'a>(&'a mut self) -> &'a mut Builder { pub fn target_renode<'a>(&'a mut self) -> &'a mut Builder {
self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); 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.stream = BuildStream::Release;
self.run_svd2repl = true; self.run_svd2repl = true;
self.utra_target = "renode".to_string(); 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. /// 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 { 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 = Some(crate::TARGET_TRIPLE_RISCV32.to_string());
self.target_kernel = Some(crate::TARGET_TRIPLE_RISCV32_KERNEL.to_string());
self.stream = BuildStream::Release; self.stream = BuildStream::Release;
self.utra_target = format!("precursor-{}", soc_version).to_string(); self.utra_target = format!("precursor-{}", soc_version).to_string();
self.run_svd2repl = false; 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 { 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 = Some(crate::TARGET_TRIPLE_RISCV32.to_string());
self.target_kernel = Some(crate::TARGET_TRIPLE_RISCV32_KERNEL.to_string());
self.stream = BuildStream::Release; self.stream = BuildStream::Release;
self.utra_target = format!("precursor-{}", soc_version).to_string(); self.utra_target = format!("precursor-{}", soc_version).to_string();
self.run_svd2repl = false; self.run_svd2repl = false;
@ -269,6 +275,7 @@ impl Builder {
/// Configure for ARM targets /// Configure for ARM targets
pub fn target_arm(&mut self) -> &mut Builder { pub fn target_arm(&mut self) -> &mut Builder {
self.target = Some(crate::TARGET_TRIPLE_ARM.to_string()); 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.stream = BuildStream::Debug;
self.utra_target = "atsama5d27".to_string(); self.utra_target = "atsama5d27".to_string();
self.run_svd2repl = false; self.run_svd2repl = false;
@ -280,6 +287,7 @@ impl Builder {
/// Configure various Cramium targets /// Configure various Cramium targets
pub fn target_cramium_fpga<'a>(&'a mut self) -> &'a mut Builder { pub fn target_cramium_fpga<'a>(&'a mut self) -> &'a mut Builder {
self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); 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.stream = BuildStream::Release;
self.utra_target = "cramium-fpga".to_string(); self.utra_target = "cramium-fpga".to_string();
self.run_svd2repl = false; self.run_svd2repl = false;
@ -290,6 +298,7 @@ impl Builder {
pub fn target_cramium_soc<'a>(&'a mut self) -> &'a mut Builder { pub fn target_cramium_soc<'a>(&'a mut self) -> &'a mut Builder {
self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); 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.stream = BuildStream::Release;
self.utra_target = "cramium-soc".to_string(); self.utra_target = "cramium-soc".to_string();
self.run_svd2repl = false; self.run_svd2repl = false;
@ -591,16 +600,14 @@ impl Builder {
} }
// ------ configure target generation feature flags ------ // ------ 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.features.push("renode".into());
self.loader_features.push("renode".into()); self.loader_features.push("renode".into());
self.kernel_features.push("renode".into()); self.kernel_features.push("renode".into());
Some(crate::TARGET_TRIPLE_RISCV32)
} else if self.utra_target.contains("hosted") { } else if self.utra_target.contains("hosted") {
self.features.push("hosted".into()); self.features.push("hosted".into());
// there is no loader in hosed mode // there is no loader in hosed mode
self.kernel_features.push("hosted".into()); self.kernel_features.push("hosted".into());
None
} else if self.utra_target.contains("precursor") { } else if self.utra_target.contains("precursor") {
self.features.push("precursor".into()); self.features.push("precursor".into());
self.features.push(format!("utralib/{}", &self.utra_target)); self.features.push(format!("utralib/{}", &self.utra_target));
@ -608,11 +615,9 @@ impl Builder {
self.kernel_features.push(format!("utralib/{}", &self.utra_target)); self.kernel_features.push(format!("utralib/{}", &self.utra_target));
self.loader_features.push("precursor".into()); self.loader_features.push("precursor".into());
self.loader_features.push(format!("utralib/{}", &self.utra_target)); self.loader_features.push(format!("utralib/{}", &self.utra_target));
Some(crate::TARGET_TRIPLE_RISCV32)
} else if self.utra_target.contains("atsama5d2") { } else if self.utra_target.contains("atsama5d2") {
self.kernel_features.push("atsama5d27".into()); self.kernel_features.push("atsama5d27".into());
self.loader_features.push("atsama5d27".into()); self.loader_features.push("atsama5d27".into());
Some(crate::TARGET_TRIPLE_ARM)
} else if self.utra_target.contains("cramium-fpga") { } else if self.utra_target.contains("cramium-fpga") {
self.features.push("cramium-fpga".into()); self.features.push("cramium-fpga".into());
self.features.push(format!("utralib/{}", &self.utra_target)); self.features.push(format!("utralib/{}", &self.utra_target));
@ -620,7 +625,6 @@ impl Builder {
self.kernel_features.push(format!("utralib/{}", &self.utra_target)); self.kernel_features.push(format!("utralib/{}", &self.utra_target));
self.loader_features.push("cramium-fpga".into()); self.loader_features.push("cramium-fpga".into());
self.loader_features.push(format!("utralib/{}", &self.utra_target)); self.loader_features.push(format!("utralib/{}", &self.utra_target));
Some(crate::TARGET_TRIPLE_RISCV32)
} else if self.utra_target.contains("cramium-soc") { } else if self.utra_target.contains("cramium-soc") {
self.features.push("cramium-soc".into()); self.features.push("cramium-soc".into());
self.features.push(format!("utralib/{}", &self.utra_target)); self.features.push(format!("utralib/{}", &self.utra_target));
@ -628,12 +632,12 @@ impl Builder {
self.kernel_features.push(format!("utralib/{}", &self.utra_target)); self.kernel_features.push(format!("utralib/{}", &self.utra_target));
self.loader_features.push("cramium-soc".into()); self.loader_features.push("cramium-soc".into());
self.loader_features.push(format!("utralib/{}", &self.utra_target)); self.loader_features.push(format!("utralib/{}", &self.utra_target));
Some(crate::TARGET_TRIPLE_RISCV32)
} else { } else {
return Err("Target unknown: please check your UTRA target".into()); 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_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 self.locale_override(); // apply the locale override
// ------ build the services & apps ------ // ------ build the services & apps ------
@ -656,7 +660,7 @@ impl Builder {
let mut services_path = self.builder( let mut services_path = self.builder(
&[&self.services[..], &self.apps[..]].concat(), &[&self.services[..], &self.apps[..]].concat(),
&self.features, &self.features,
&target, &self.target.as_deref(),
self.stream, self.stream,
&vec![], &vec![],
false, false,
@ -735,7 +739,7 @@ impl Builder {
let _ = self.builder( let _ = self.builder(
&vec![CrateSpec::Local("xous-kernel".into(), false)], &vec![CrateSpec::Local("xous-kernel".into(), false)],
&self.kernel_features, &self.kernel_features,
&target, &self.target_kernel.as_deref(),
self.stream, self.stream,
&vec![], &vec![],
false, false,
@ -751,7 +755,7 @@ impl Builder {
let kernel_path = self.builder( let kernel_path = self.builder(
&vec![self.kernel.clone()], &vec![self.kernel.clone()],
&self.kernel_features, &self.kernel_features,
&target, &self.target_kernel.as_deref(),
self.stream, self.stream,
&kernel_extra, &kernel_extra,
false, false,
@ -773,7 +777,7 @@ impl Builder {
let loader = self.builder( let loader = self.builder(
&vec![self.loader.clone()], &vec![self.loader.clone()],
&self.loader_features, &self.loader_features,
&target, &self.target_kernel.as_deref(),
BuildStream::Release, // loader doesn't fit if you build with Debug BuildStream::Release, // loader doesn't fit if you build with Debug
&loader_extra, &loader_extra,
true, // loader builds without any default features true, // loader builds without any default features

View file

@ -42,8 +42,10 @@ const MIN_XOUS_VERSION: &str = "v0.9.8-791";
/// target triple for precursor builds /// target triple for precursor builds
pub(crate) const TARGET_TRIPLE_RISCV32: &str = "riscv32imac-unknown-xous-elf"; 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 /// target triple for ARM builds
pub(crate) const TARGET_TRIPLE_ARM: &str = "armv7a-unknown-xous-elf"; 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 // 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 // refactor to work around warnings thrown by Rust 1.64.0 is: f815ed85b58b671178fbf53b4cea34186fc406eb
@ -164,7 +166,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
match task.as_deref() { match task.as_deref() {
Some("install-toolkit") | Some("install-toolchain") => { Some("install-toolkit") | Some("install-toolchain") => {
let arg = env::args().nth(2); 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 -------- // ----- renode configs --------
Some("renode-image") => { Some("renode-image") => {

View file

@ -3,7 +3,7 @@ use std::{
fs::{File, OpenOptions}, fs::{File, OpenOptions},
io::{Read, Write}, io::{Read, Write},
path::{Path, PathBuf}, path::{Path, PathBuf},
process::Command, process::{Command, Stdio},
}; };
use lazy_static::lazy_static; use lazy_static::lazy_static;
@ -25,49 +25,60 @@ lazy_static! {
/// cache it inside an atomic boolean. If this is `true` then /// cache it inside an atomic boolean. If this is `true` then
/// it means we can assume the check passed already. /// 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_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, fn ask_to_install() -> bool {
/// and we want to give the user a friendly way of installing the latest let mut buffer = String::new();
/// Rust toolchain. let stdin = std::io::stdin();
pub(crate) fn ensure_compiler( let mut stdout = std::io::stdout();
target: &Option<&str>, loop {
force_install: bool, stdout.flush().unwrap();
remove_existing: bool, buffer.clear();
) -> Result<(), String> { stdin.read_line(&mut buffer).unwrap();
use std::process::Stdio;
if DONE_COMPILER_CHECK.load(std::sync::atomic::Ordering::SeqCst) {
return Ok(());
}
/// Return the sysroot for the given target. If the target does not exist, let trimmed = buffer.trim();
/// return None.
fn get_sysroot(target: Option<&str>) -> Result<Option<String>, String> { if trimmed == "n" || trimmed == "N" {
let mut args = vec!["--print", "sysroot"]; return false;
if let Some(target) = target {
args.push("--target");
args.push(target);
} }
let sysroot_cmd = Command::new("rustc") if trimmed == "y" || trimmed == "Y" || trimmed.is_empty() {
.stderr(Stdio::null()) return true;
.stdout(Stdio::piped()) }
.args(&args) println!();
.spawn() println!("Please answer 'y' or 'n'");
.expect("could not run rustc"); }
let sysroot_output = sysroot_cmd.wait_with_output().unwrap(); }
let have_toolchain = sysroot_output.status.success(); /// 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<Option<String>, 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) let sysroot_cmd = Command::new("rustc")
.map_err(|_| "Unable to find Rust sysroot".to_owned())? .stderr(Stdio::null())
.trim() .stdout(Stdio::piped())
.to_owned(); .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. let toolchain_path = String::from_utf8(sysroot_output.stdout)
if let Some(target) = target { .map_err(|_| "Unable to find Rust sysroot".to_owned())?
let mut version_path = PathBuf::from(&toolchain_path); .trim()
version_path.push("lib"); .to_owned();
version_path.push("rustlib");
version_path.push(target); // 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"); version_path.push("RUST_VERSION");
if let Ok(mut vp) = File::open(&version_path) { if let Ok(mut vp) = File::open(&version_path) {
let mut version_str = String::new(); let mut version_str = String::new();
@ -91,14 +102,81 @@ pub(crate) fn ensure_compiler(
// return Err("Outdated toolchain installed".to_owned()); // return Err("Outdated toolchain installed".to_owned());
return Ok(None); 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. // If the sysroot exists, then we're good.
let target = target.unwrap_or(TARGET_TRIPLE_RISCV32); 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); let mut version_path = PathBuf::from(&path);
version_path.push("lib"); version_path.push("lib");
version_path.push("rustlib"); version_path.push("rustlib");
@ -125,7 +203,8 @@ pub(crate) fn ensure_compiler(
} }
// Since no sysroot exists, we must download a new one. // 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, // If the terminal is a tty, or if toolchain installation is forced,
// download the latest toolchain. // download the latest toolchain.
if !atty::is(atty::Stream::Stdin) && !force_install { 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. // 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 { if force_install {
println!("Downloading toolchain"); println!("Downloading toolchain");
} else { } else {
println!("Error: Toolchain for {} was not found on this system!", target); 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] "); print!("Would you like this program to attempt to download and install it? [Y/n] ");
stdout.flush().unwrap(); if ask_to_install() {
buffer.clear(); println!("Installing toolchain for {} into {}", target, toolchain_path);
stdin.read_line(&mut buffer).unwrap(); } else {
let trimmed = buffer.trim();
if trimmed == "n" || trimmed == "N" {
return Err(format!("Please install the {} toolchain", target)); 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<String, String> { fn get_toolchain_url(target: &str, major: u64, minor: u64, patch: u64) -> Result<String, String> {
@ -239,31 +300,13 @@ pub(crate) fn ensure_compiler(
println!("Downloading toolchain from {}...", toolchain_url); println!("Downloading toolchain from {}...", toolchain_url);
print!("Download in progress..."); print!("Download in progress...");
stdout.flush().unwrap(); std::io::stdout().flush().ok();
let mut zip_data = vec![]; let mut zip_data = vec![];
{ {
let agent = ureq::builder() let agent = ureq::builder().build();
// .middleware(CounterMiddleware(shared_state.clone()))
.build();
let mut freader = agent.get(&toolchain_url).call().map_err(|e| format!("{}", e))?.into_reader(); 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))?; 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!();
} }
println!("Download successful. Total data size is {} bytes", zip_data.len()); println!("Download successful. Total data size is {} bytes", zip_data.len());