Merge pull request #1 from betrusted-io/apploader

Apploader
This commit is contained in:
vihaanjim 2023-10-30 17:11:20 -04:00 committed by GitHub
commit c904b47f82
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 530 additions and 298 deletions

View file

@ -187,7 +187,7 @@ path = "./svd2utra"
# path = "./api/xous-api-names"
# [patch.crates-io.xous-api-susres]
# path = "./api/xous-api-susres"
[patch.crates-io.xous-api-log]
path = "./api/xous-api-log"
# [patch.crates-io.xous-api-log]
# path = "./api/xous-api-log"
# [patch.crates-io.xous-api-ticktimer]
# path = "./api/xous-api-ticktimer"

View file

@ -9,7 +9,7 @@ Note that at the moment you can only load apps once each time the device runs si
First, add the app loader to your device's image as you would with any other app:
```
$ cargo xtask app-image-xip --app app-loader
$ cargo xtask app-image-xip --app app-loader --feature unsafe-app-loading
$ sudo python3 tools/usb_update.py -k target/riscv32imac-unknown-xous-elf/release/xous.img -l target/riscv32imac-unknown-xous-elf/release/loader.bin
```
Then, compile the apps you would like on your device and start the app server. For example, if you would like to serve the apps `hello`, `ball`, and `vault` on port 8000, run:

View file

@ -20,7 +20,7 @@ impl From<xous::MessageId> for StartupCommand {
#[panic_handler]
fn handle_panic(arg: &core::panic::PanicInfo) -> ! {
log::info!("{arg}");
loop {}
xous::terminate_process(1);
}
#[no_mangle]
@ -33,13 +33,22 @@ pub extern "C" fn init(server1: u32, server2: u32, server3: u32, server4: u32) -
None,
core::num::NonZeroUsize::new(0x40000000),
0x1000,
xous::MemoryFlags::R | xous::MemoryFlags::W
).unwrap();
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.unwrap();
let connection = core::sync::atomic::AtomicU32::new(0);
let slice = unsafe { core::slice::from_raw_parts(&connection as *const _ as *const u8, core::mem::size_of::<core::sync::atomic::AtomicU32>()) };
let slice = unsafe {
core::slice::from_raw_parts(
&connection as *const _ as *const u8,
core::mem::size_of::<core::sync::atomic::AtomicU32>(),
)
};
// safety: memory is freshly allocated by map_memory, should be aligned and init'd to 0
unsafe {
for (dest, src) in memory.as_slice_mut::<u8>().iter_mut().skip(8).zip(slice) {
*dest = *src;
}
}
// everything should drop now
}
@ -57,7 +66,7 @@ pub extern "C" fn init(server1: u32, server2: u32, server3: u32, server4: u32) -
// destroy the server
xous::destroy_server(server).expect("Couldn't destroy spawn server");
jump(entry_point);
},
}
StartupCommand::PingResponse => ping_response(envelope),
_ => panic!("Unsupported"),
}
@ -80,7 +89,8 @@ fn read_elf(memory: Option<&mut xous::MemoryMessage>) -> usize {
};
// get the elf binary from the message
let mut bin = memory.buf.as_slice::<u8>();
// safety: buf should be aligned and correctly sized inside the MemoryMessage
let mut bin = unsafe {memory.buf.as_slice::<u8>()};
// go to the beginning of the ELF file using the provided offset
bin = &bin[memory.offset.and_then(|n| Some(n.get())).unwrap_or(0)..];
@ -122,12 +132,22 @@ fn read_elf(memory: Option<&mut xous::MemoryMessage>) -> usize {
let file_size = to_usize(start + 0x10, 4);
let mem_size = to_usize(start + 0x14, 4);
let mem_size = mem_size + padding;
let mem_size = mem_size + if mem_size & 0xFFF == 0 { 0 } else { 0x1000 - (mem_size & 0xFFF) };
let mem_size = mem_size
+ if mem_size & 0xFFF == 0 {
0
} else {
0x1000 - (mem_size & 0xFFF)
};
assert_eq!(0, mem_size & 0xFFF);
assert_eq!(0, (vaddr - padding) & 0xFFF);
log::info!("Loading offset {} to virtual address {} with memory size {}", src_addr, vaddr, mem_size);
log::info!(
"Loading offset {} to virtual address {} with memory size {}",
src_addr,
vaddr,
mem_size
);
let mut target_memory = xous::map_memory(
None,
core::num::NonZeroUsize::new(vaddr - padding),
@ -136,18 +156,27 @@ fn read_elf(memory: Option<&mut xous::MemoryMessage>) -> usize {
)
.unwrap();
for (dest, src) in target_memory.as_slice_mut().iter_mut().skip(padding)
// TODO: rationalize why this is safe
unsafe {
for (dest, src) in target_memory
.as_slice_mut()
.iter_mut()
.skip(padding)
.zip(bin[src_addr..core::cmp::min(max, src_addr + file_size)].iter())
{
*dest = *src;
}
for dest in target_memory.as_slice_mut().iter_mut().skip(padding+file_size)
for dest in target_memory
.as_slice_mut()
.iter_mut()
.skip(padding + file_size)
.take(mem_size - file_size - padding)
{
*dest = 0;
}
}
}
}
memory.offset = None;
log::info!("Finished writing");

View file

@ -1,9 +1,12 @@
use std::io::Read;
use gam::{Gam, MenuItem, UxRegistration, menu_matic, APP_NAME_APP_LOADER, APP_MENU_0_APP_LOADER, APP_MENU_1_APP_LOADER, MenuMatic, TextEntryPayload};
use crate::SERVER_NAME_APP_LOADER;
use gam::{
menu_matic, Gam, MenuItem, MenuMatic, TextEntryPayload, UxRegistration, APP_MENU_0_APP_LOADER,
APP_MENU_1_APP_LOADER, APP_NAME_APP_LOADER,
};
use locales::t;
use modals::Modals;
use num_traits::ToPrimitive;
use locales::t;
use crate::SERVER_NAME_APP_LOADER;
use std::io::Read;
pub(crate) struct AppLoader {
gam: Gam,
@ -25,7 +28,8 @@ impl AppLoader {
let gam = Gam::new(xns).expect("can't connect to GAM");
// the gam token
let auth = gam.register_ux(UxRegistration {
let auth = gam
.register_ux(UxRegistration {
app_name: xous_ipc::String::from_str(APP_NAME_APP_LOADER),
ux_type: gam::UxType::Modal,
predictor: None,
@ -34,92 +38,177 @@ impl AppLoader {
gotinput_id: None,
audioframe_id: None,
focuschange_id: None,
rawkeys_id: None
}).expect("Couldn't register").expect("Didn't get an auth token");
rawkeys_id: None,
})
.expect("Couldn't register")
.expect("Didn't get an auth token");
let modals = Modals::new(xns).expect("Couldn't get modals");
// a connection to the server
let conn = xns.request_connection_blocking(SERVER_NAME_APP_LOADER).expect("Couldn't connect to server");
let conn = xns
.request_connection_blocking(SERVER_NAME_APP_LOADER)
.expect("Couldn't connect to server");
// the ticktimer
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer");
// the menu
let set_server_item = MenuItem{ name: xous_ipc::String::from_str(t!("apploader.menu.setserver", locales::LANG)),
let set_server_item = MenuItem {
name: xous_ipc::String::from_str(t!("apploader.menu.setserver", locales::LANG)),
action_conn: Some(conn),
action_opcode: Opcode::SetServer.to_u32().unwrap(),
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true };
let close_item = MenuItem{ name: xous_ipc::String::from_str(t!("apploader.close", locales::LANG)),
close_on_select: true,
};
let close_item = MenuItem {
name: xous_ipc::String::from_str(t!("apploader.close", locales::LANG)),
action_conn: None,
action_opcode: 0,
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true };
let menu = menu_matic(vec![set_server_item, close_item.clone()], APP_MENU_0_APP_LOADER, Some(xous::create_server().unwrap())).expect("Couldn't create menu");
let load_menu = menu_matic(vec![close_item.clone()], APP_MENU_1_APP_LOADER, Some(xous::create_server().unwrap())).expect("Couldn't create menu");
close_on_select: true,
};
let menu = menu_matic(
vec![set_server_item, close_item.clone()],
APP_MENU_0_APP_LOADER,
Some(xous::create_server().unwrap()),
)
.expect("Couldn't create menu");
let load_menu = menu_matic(
vec![close_item.clone()],
APP_MENU_1_APP_LOADER,
Some(xous::create_server().unwrap()),
)
.expect("Couldn't create menu");
AppLoader{ gam, modals, auth, conn, ticktimer, menu, load_menu, apps: Vec::new(), possible_apps: Vec::new(), server: None, current_menu: APP_MENU_0_APP_LOADER.to_string() }
AppLoader {
gam,
modals,
auth,
conn,
ticktimer,
menu,
load_menu,
apps: Vec::new(),
possible_apps: Vec::new(),
server: None,
current_menu: APP_MENU_0_APP_LOADER.to_string(),
}
}
pub(crate) fn add_app(&mut self, index: usize) {
let (name, menus) = self.possible_apps[index];
self.modals.start_progress(t!("apploader.addapp.loading", locales::LANG), 0, 3, 0).expect("Couldn't set up progress bar");
self.modals
.start_progress(t!("apploader.addapp.loading", locales::LANG), 0, 3, 0)
.expect("Couldn't set up progress bar");
//////////////////////////
// The downloading part //
//////////////////////////
let response = match ureq::get(&format!("{}/{}", self.server.as_ref().expect("AddApp was somehow called without a server!"), name)).call() {
let response = match ureq::get(&format!(
"{}/{}",
self.server
.as_ref()
.expect("AddApp was somehow called without a server!"),
name
))
.call()
{
Ok(response) => response,
Err(e) => {
self.modals.show_notification(&format!("{}{}", t!("apploader.addapp.server_error", locales::LANG), e), None).expect("Couldn't show modal");
self.modals
.show_notification(
&format!(
"{}{}",
t!("apploader.addapp.server_error", locales::LANG),
e
),
None,
)
.expect("Couldn't show modal");
return;
}
};
let len = match response.header("Content-Length") {
Some(len) => len.parse::<usize>().expect("Couldn't parse Content-Length header"),
Some(len) => len
.parse::<usize>()
.expect("Couldn't parse Content-Length header"),
None => {
self.modals.show_notification(t!("apploader.addapp.content_length_error", locales::LANG), None).expect("Couldn't show modal");
self.modals
.show_notification(
t!("apploader.addapp.content_length_error", locales::LANG),
None,
)
.expect("Couldn't show modal");
return;
}
};
let mut memory = xous::map_memory(
None,
None,
len + if len & 0xFFF == 0 {
0
} else {
0x1000 - (len & 0xFFF)
},
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("Couldn't map memory");
response
.into_reader()
.read_exact(&mut unsafe { memory.as_slice_mut() }[..len])
.expect("Couldn't read");
let mut memory = xous::map_memory(None, None, len + if len & 0xFFF == 0 { 0 } else { 0x1000 - (len & 0xFFF) }, xous::MemoryFlags::R | xous::MemoryFlags::W).expect("Couldn't map memory");
response.into_reader().read_exact(&mut unsafe{ memory.as_slice_mut() }[..len]).expect("Couldn't read");
self.modals.update_progress(1).expect("Couldn't update progress");
self.modals
.update_progress(1)
.expect("Couldn't update progress");
//////////////////////
// The loading part //
//////////////////////
// create the spawn process
let stub = include_bytes!("spawn.bin");
let args = xous::ProcessArgs::new(stub, xous::MemoryAddress::new(0x2050_1000).unwrap(), xous::MemoryAddress::new(0x2050_1000).unwrap());
let args = xous::ProcessArgs::new(
stub,
xous::MemoryAddress::new(0x2050_1000).unwrap(),
xous::MemoryAddress::new(0x2050_1000).unwrap(),
);
let spawn = xous::create_process(args).expect("Couldn't create spawn process");
log::info!("Spawn PID: {}, Spawn CID: {}", spawn.pid, spawn.cid);
// perform a ping to make sure that spawn is running
let result = xous::send_message(
spawn.cid,
xous::Message::new_blocking_scalar(2, 1, 2, 3, 4),
)
let result =
xous::send_message(spawn.cid, xous::Message::new_blocking_scalar(2, 1, 2, 3, 4))
.unwrap();
assert_eq!(xous::Result::Scalar1(2), result);
self.modals.update_progress(2).expect("Couldn't update progress");
self.modals
.update_progress(2)
.expect("Couldn't update progress");
// load the app from the binary file
let res = xous::send_message(spawn.cid, xous::Message::new_lend_mut(1, memory, None, None)).expect("Couldn't send a message to spawn");
let res = xous::send_message(
spawn.cid,
xous::Message::new_lend_mut(1, memory, None, None),
)
.expect("Couldn't send a message to spawn");
// we are just going to do some very basic error handling: if the "offset" is None, we are good, otherwise there was a problem
// TODO: make this better. Perhaps Buffer::from_raw_parts?
match res {
xous::Result::MemoryReturned(None, _) => self.modals.update_progress(3).expect("Couldn't update progress"),
xous::Result::MemoryReturned(None, _) => self
.modals
.update_progress(3)
.expect("Couldn't update progress"),
_ => {
self.modals.finish_progress().expect("Couldn't close progressbar");
self.modals.show_notification(t!("apploader.addapp.error", locales::LANG), None).expect("Couldn't show modal");
self.modals
.finish_progress()
.expect("Couldn't close progressbar");
self.modals
.show_notification(t!("apploader.addapp.error", locales::LANG), None)
.expect("Couldn't show modal");
return;
}
}
@ -129,45 +218,85 @@ impl AppLoader {
//////////////////////
// add its name to GAM
self.gam.register_name(name.to_str(), self.auth).expect("Couldn't register name");
self.gam
.register_name(name.to_str(), self.auth)
.expect("Couldn't register name");
for menu in 0..menus {
self.gam.register_name(&format!("{} Submenu {}", name, menu), self.auth).expect("Couldn't register name");
self.gam
.register_name(&format!("{} Submenu {}", name, menu), self.auth)
.expect("Couldn't register name");
}
// add it to the menu
self.menu.insert_item(MenuItem { name,
self.menu.insert_item(
MenuItem {
name,
action_conn: Some(self.conn),
action_opcode: Opcode::DispatchApp.to_u32().unwrap(),
action_payload: gam::MenuPayload::Scalar([self.apps.len().try_into().unwrap(), 0, 0, 0]),
close_on_select: true }, 0);
action_payload: gam::MenuPayload::Scalar([
self.apps.len().try_into().unwrap(),
0,
0,
0,
]),
close_on_select: true,
},
0,
);
self.apps.push(name);
log::info!("Added app `{}'!", name);
self.modals.finish_progress().expect("Couldn't close progressbar");
self.modals
.finish_progress()
.expect("Couldn't close progressbar");
let _ = self.gam.switch_to_app(APP_NAME_APP_LOADER, self.auth); // try to switch back to the menu
}
pub(crate) fn set_server(&mut self) {
let payload = self.modals.alert_builder("Server Address")
.field(Some("e.g. http://ip:port".to_string()), Some(|payload: TextEntryPayload| match url::Url::parse(payload.as_str()) {
let payload = self
.modals
.alert_builder("Server Address")
.field(
Some("e.g. http://ip:port".to_string()),
Some(
|payload: TextEntryPayload| match url::Url::parse(payload.as_str()) {
Ok(_) => None,
Err(e) => Some(xous_ipc::String::from_str(&format!("{}{}", t!("apploader.setserver.error", locales::LANG), e))),
}))
Err(e) => Some(xous_ipc::String::from_str(&format!(
"{}{}",
t!("apploader.setserver.error", locales::LANG),
e
))),
},
),
)
.build()
.ok();
if self.server.is_none() && payload.is_some() {
self.menu.insert_item(MenuItem { name: xous_ipc::String::from_str(t!("apploader.menu.reloadapplist", locales::LANG)),
self.menu.insert_item(
MenuItem {
name: xous_ipc::String::from_str(t!(
"apploader.menu.reloadapplist",
locales::LANG
)),
action_conn: Some(self.conn),
action_opcode: Opcode::ReloadAppList.to_u32().unwrap(),
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true }, 0);
self.menu.insert_item(MenuItem { name: xous_ipc::String::from_str(t!("apploader.menu.addapp", locales::LANG)),
close_on_select: true,
},
0,
);
self.menu.insert_item(
MenuItem {
name: xous_ipc::String::from_str(t!("apploader.menu.addapp", locales::LANG)),
action_conn: Some(self.conn),
action_opcode: Opcode::AddAppMenu.to_u32().unwrap(),
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true }, 0);
close_on_select: true,
},
0,
);
}
self.server = payload.and_then(|p| Some(p.first().as_str().to_string()));
@ -181,24 +310,65 @@ impl AppLoader {
pub(crate) fn reload_app_list(&mut self) {
// without a path, the server responds with a JSON list of strings representing the list of app names
self.modals.start_progress(t!("apploader.reloadapplist.loading", locales::LANG), 0, 3, 0).expect("Couldn't start progressbar");
self.modals
.start_progress(
t!("apploader.reloadapplist.loading", locales::LANG),
0,
3,
0,
)
.expect("Couldn't start progressbar");
let old = self.possible_apps.clone();
// this... disgusting error handling is so that if there is an error on the server side there isn't a panic
self.possible_apps = match
match ureq::get(&self.server.as_ref().expect("ReloadAppList was somehow called without a server!")).call() {
Ok(c) => { self.modals.update_progress(1).expect("Couldn't update progress"); c },
self.possible_apps = match match ureq::get(
&self
.server
.as_ref()
.expect("ReloadAppList was somehow called without a server!"),
)
.call()
{
Ok(c) => {
self.modals
.update_progress(1)
.expect("Couldn't update progress");
c
}
Err(e) => {
self.modals.show_notification(&format!("{}{}", t!("apploader.reloadapplist.connection_error", locales::LANG), e), None).expect("Couldn't show modal");
self.modals
.show_notification(
&format!(
"{}{}",
t!("apploader.reloadapplist.connection_error", locales::LANG),
e
),
None,
)
.expect("Couldn't show modal");
return;
}
}
.into_json::<Vec<(String, usize)>>()
{
Ok(json) => { self.modals.update_progress(2).expect("Couldn't update progress"); json },
Ok(json) => {
self.modals
.update_progress(2)
.expect("Couldn't update progress");
json
}
Err(e) => {
self.modals.show_notification(&format!("{}{}", t!("apploader.reloadapplist.json_error", locales::LANG), e), None).expect("Couldn't show modal");
self.modals
.show_notification(
&format!(
"{}{}",
t!("apploader.reloadapplist.json_error", locales::LANG),
e
),
None,
)
.expect("Couldn't show modal");
return;
}
}
@ -211,13 +381,20 @@ impl AppLoader {
}
for (i, (app, _)) in self.possible_apps.iter().enumerate() {
self.load_menu.insert_item(MenuItem { name: xous_ipc::String::from_str(app.to_str()),
self.load_menu.insert_item(
MenuItem {
name: xous_ipc::String::from_str(app.to_str()),
action_conn: Some(self.conn),
action_opcode: Opcode::AddApp.to_u32().unwrap(),
action_payload: gam::MenuPayload::Scalar([i.try_into().unwrap(), 0, 0, 0]),
close_on_select: true }, 0);
close_on_select: true,
},
0,
);
}
self.modals.finish_progress().expect("Couldn't close progress bar");
self.modals
.finish_progress()
.expect("Couldn't close progress bar");
let _ = self.gam.switch_to_app(APP_NAME_APP_LOADER, self.auth); // try to switch back to the menu
}
@ -226,7 +403,9 @@ impl AppLoader {
if index < self.apps.len() {
let name: xous_ipc::String<64> = self.apps[index];
log::info!("Switching to app `{}'", name);
self.gam.switch_to_app(name.as_ref(), self.auth).expect(&format!("Could not dispatch app `{}'", name));
self.gam
.switch_to_app(name.as_ref(), self.auth)
.expect(&format!("Could not dispatch app `{}'", name));
} else {
panic!("Unrecognized app index");
}
@ -265,5 +444,5 @@ pub(crate) enum Opcode {
DispatchApp,
/// Redraw the UI
Redraw
Redraw,
}

View file

@ -10,7 +10,9 @@ fn main() -> ! {
log::info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap();
let sid = xns.register_name(SERVER_NAME_APP_LOADER, None).expect("Couldn't create server");
let sid = xns
.register_name(SERVER_NAME_APP_LOADER, None)
.expect("Couldn't create server");
// start off by adding hello world
let mut app_loader = AppLoader::new(&xns, &sid);
@ -20,24 +22,24 @@ fn main() -> ! {
match FromPrimitive::from_usize(msg.body.id()).expect("Couldn't load message") {
Opcode::SetServer => {
app_loader.set_server();
},
}
Opcode::ReloadAppList => {
app_loader.reload_app_list();
},
}
Opcode::AddAppMenu => {
app_loader.open_load_menu();
},
}
Opcode::AddApp => {
let index = msg.body.scalar_message().expect("Not a scalar").arg1;
app_loader.add_app(index);
},
}
Opcode::DispatchApp => {
let index = msg.body.scalar_message().expect("Not a scalar").arg1;
app_loader.dispatch_app(index);
},
}
Opcode::Redraw => {
app_loader.redraw();
},
}
}
}
}

Binary file not shown.

View file

@ -52,3 +52,4 @@ tts = []
# default = ["debugprint"] # "debugprint"
default = []
ditherpunk = []
unsafe-app-loading = [] # allow new contexts to be registered dynamically - this is unsafe and should not be set for release builds.

View file

@ -110,6 +110,7 @@ pub struct UxRegistration {
/// If the LayoutType is not an App, this field is ignored and does nothing
pub focuschange_id: Option<u32>,
}
#[cfg(feature="unsafe-app-loading")]
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct NameRegistration {
pub name: String::<128>,
@ -217,7 +218,8 @@ pub(crate) enum Opcode {
/// This resolves race conditions that depend upon the PDDB configurations.
AllowMainMenu = 33,
/// Register a name that can aquire a token. This is only intended to be used with pre-registered apps
/// Register a name that can acquire a token. This is only intended to be used with pre-registered apps
#[cfg(feature="unsafe-app-loading")]
RegisterName = 34,
}

View file

@ -130,6 +130,7 @@ impl ContextManager {
pub(crate) fn claim_token(&mut self, name: &str) -> Option<[u32; 4]> {
self.tm.claim_token(name)
}
#[cfg(feature="unsafe-app-loading")]
pub(crate) fn register_name(&mut self, name: &str, auth_token: &[u32; 4]) {
self.tm.register_name(name, auth_token);
}

View file

@ -311,6 +311,7 @@ impl Gam {
Ok(returned_claim.token)
}
#[cfg(feature="unsafe-app-loading")]
pub fn register_name(&self, name: &str, auth_token: [u32; 4]) -> Result<(), xous::Error> {
let name_registration = NameRegistration {
name: String::<128>::from_str(name),

View file

@ -567,6 +567,9 @@ fn wrapped_main() -> ! {
// set before the leaving state due to interior-mutability issues (see the block under the debug statement
// titled "resolving visibility rules"). The fix is to simply not issue a context switch if it's the same app.
// It saves CPU thrashing and also works around this problem. (see issue #145)
#[cfg(not(feature="unsafe-app-loading"))]
let authorized_switchers = vec![MAIN_MENU_NAME, ROOTKEY_MODAL_NAME, gam::STATUS_BAR_NAME];
#[cfg(feature="unsafe-app-loading")]
let authorized_switchers = [&[MAIN_MENU_NAME, ROOTKEY_MODAL_NAME, gam::STATUS_BAR_NAME], gam::EXPECTED_APP_CONTEXTS].concat().to_vec();
for switchers in authorized_switchers {
if let Some(auth_token) = context_mgr.find_app_token_by_name(switchers) {
@ -670,9 +673,11 @@ fn wrapped_main() -> ! {
context_mgr.allow_mainmenu();
xous::return_scalar(msg.sender, 0).ok();
}
#[cfg(feature="unsafe-app-loading")]
Some(Opcode::RegisterName) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let registration = buffer.to_original::<NameRegistration, _>().unwrap();
gfx.set_devboot(); // indicate to users that we are no longer in a codebase that is exclusively trusted code
context_mgr.register_name(registration.name.to_str(), &registration.auth_token);
}
Some(Opcode::Quit) => break,

View file

@ -18,6 +18,7 @@ pub(crate) struct NamedToken {
}
pub(crate) struct TokenManager {
tokens: Vec::<NamedToken>,
#[cfg(feature="unsafe-app-loading")]
extra_names: Vec<String>,
trng: trng::Trng,
}
@ -25,13 +26,18 @@ impl<'a> TokenManager {
pub(crate) fn new(xns: &xous_names::XousNames) -> TokenManager {
TokenManager {
tokens: Vec::new(),
#[cfg(feature="unsafe-app-loading")]
extra_names: Vec::new(),
trng: trng::Trng::new(&xns).unwrap(),
}
}
/// checks to see if all the slots have been occupied. We can't allow untrusted code to run until all slots have checked in
pub(crate) fn allow_untrusted_code(&self) -> bool {
if self.tokens.len() == (EXPECTED_BOOT_CONTEXTS.len() + EXPECTED_APP_CONTEXTS.len() + self.extra_names.len()) {
#[cfg(feature="unsafe-app-loading")]
let expected_len = EXPECTED_BOOT_CONTEXTS.len() + EXPECTED_APP_CONTEXTS.len() + self.extra_names.len();
#[cfg(not(feature="unsafe-app-loading"))]
let expected_len = EXPECTED_BOOT_CONTEXTS.len() + EXPECTED_APP_CONTEXTS.len();
if self.tokens.len() == expected_len {
true
} else {
// throw a bone to the dev who has to debug this error. This typically only triggers after a major
@ -53,6 +59,7 @@ impl<'a> TokenManager {
if EXPECTED_APP_CONTEXTS.iter().find(|&&context| context == name).is_some() {
found = true;
}
#[cfg(feature="unsafe-app-loading")]
if self.extra_names.iter().find(|&context| context == name).is_some() {
found = true;
}
@ -96,9 +103,14 @@ impl<'a> TokenManager {
None
}
/// Register a new name that can then claim a token. Note that only pre-registered applications are allowed to do this.
#[cfg(feature="unsafe-app-loading")]
pub(crate) fn register_name(&mut self, name: &str, auth_token: &[u32; 4]) {
if let Some(registrant) = self.lookup_name(auth_token) {
if EXPECTED_BOOT_CONTEXTS.iter().find(|&&context| context == registrant).is_some() || EXPECTED_APP_CONTEXTS.iter().find(|&&context| context == registrant).is_some() {
if EXPECTED_BOOT_CONTEXTS.iter()
.find(
|&&context| context == registrant).is_some()
|| EXPECTED_APP_CONTEXTS.iter()
.find(|&&context| context == registrant).is_some() {
self.extra_names.push(name.to_string());
} else {
log::error!("`{}' does not have permission to register a new name because it is not pre-registered", registrant);