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

@ -11,7 +11,7 @@ impl From<xous::MessageId> for StartupCommand {
fn from(src: xous::MessageId) -> StartupCommand {
match src {
1 => StartupCommand::LoadElf,
2 => StartupCommand::PingResponse,
2 => StartupCommand::PingResponse,
_ => StartupCommand::Unhandled,
}
}
@ -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]
@ -29,18 +29,27 @@ pub extern "C" fn init(server1: u32, server2: u32, server3: u32, server4: u32) -
// recreate the extra sections that were cut out of the stub
{
let mut memory = xous::map_memory(
None,
core::num::NonZeroUsize::new(0x40000000),
0x1000,
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>()) };
for (dest, src) in memory.as_slice_mut::<u8>().iter_mut().skip(8).zip(slice) {
*dest = *src;
}
// everything should drop now
let mut memory = xous::map_memory(
None,
core::num::NonZeroUsize::new(0x40000000),
0x1000,
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>(),
)
};
// 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
}
log_server::init_wait().unwrap();
@ -52,12 +61,12 @@ pub extern "C" fn init(server1: u32, server2: u32, server3: u32, server4: u32) -
{
match envelope.id().into() {
StartupCommand::LoadElf => {
let entry_point = read_elf(envelope.body.memory_message_mut());
drop(envelope); // we have to get rid of all messages to destroy the server
// destroy the server
xous::destroy_server(server).expect("Couldn't destroy spawn server");
jump(entry_point);
},
let entry_point = read_elf(envelope.body.memory_message_mut());
drop(envelope); // we have to get rid of all messages to destroy the server
// 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)..];
@ -92,17 +102,17 @@ fn read_elf(memory: Option<&mut xous::MemoryMessage>) -> usize {
// a helper function to get a region of the file as a usize
let to_usize = |start, size| {
if size == 1 {
return bin[start] as usize;
}
if size == 2 {
// assumes little endianness
return u16::from_le_bytes(bin[start..start+size].try_into().unwrap()) as usize;
}
if size == 4 {
return u32::from_le_bytes(bin[start..start+size].try_into().unwrap()) as usize;
}
panic!("Tried to get usize of invalid size!");
if size == 1 {
return bin[start] as usize;
}
if size == 2 {
// assumes little endianness
return u16::from_le_bytes(bin[start..start + size].try_into().unwrap()) as usize;
}
if size == 4 {
return u32::from_le_bytes(bin[start..start + size].try_into().unwrap()) as usize;
}
panic!("Tried to get usize of invalid size!");
};
// some basic stuff to know
@ -113,40 +123,59 @@ fn read_elf(memory: Option<&mut xous::MemoryMessage>) -> usize {
// add the segments we should load
for i in 0..ph_count {
let start = ph_start + i * ph_size;
// only load PT_LOAD segments
if to_usize(start, 4) == 0x00000001 {
let src_addr = to_usize(start+0x04, 4);
let vaddr = to_usize(start+0x08, 4);
let padding = if vaddr & 0xFFF == 0 { 0 } else { vaddr & 0xFFF };
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 start = ph_start + i * ph_size;
// only load PT_LOAD segments
if to_usize(start, 4) == 0x00000001 {
let src_addr = to_usize(start + 0x04, 4);
let vaddr = to_usize(start + 0x08, 4);
let padding = if vaddr & 0xFFF == 0 { 0 } else { vaddr & 0xFFF };
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)
};
assert_eq!(0, mem_size & 0xFFF);
assert_eq!(0, (vaddr - padding) & 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);
let mut target_memory = xous::map_memory(
None,
core::num::NonZeroUsize::new(vaddr-padding),
mem_size,
xous::MemoryFlags::R | xous::MemoryFlags::W | xous::MemoryFlags::X,
)
.unwrap();
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),
mem_size,
xous::MemoryFlags::R | xous::MemoryFlags::W | xous::MemoryFlags::X,
)
.unwrap();
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)
.take(mem_size-file_size-padding)
{
*dest = 0;
}
}
// 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)
.take(mem_size - file_size - padding)
{
*dest = 0;
}
}
}
}
memory.offset = None;

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,
@ -21,229 +24,405 @@ pub(crate) struct AppLoader {
impl AppLoader {
pub(crate) fn new(xns: &xous_names::XousNames, sid: &xous::SID) -> AppLoader {
// gam
let gam = Gam::new(xns).expect("can't connect to GAM");
// gam
let gam = Gam::new(xns).expect("can't connect to GAM");
// the gam token
let auth = gam.register_ux(UxRegistration {
app_name: xous_ipc::String::from_str(APP_NAME_APP_LOADER),
ux_type: gam::UxType::Modal,
predictor: None,
listener: sid.to_array(),
redraw_id: Opcode::Redraw.to_u32().unwrap(),
gotinput_id: None,
audioframe_id: None,
focuschange_id: None,
rawkeys_id: None
}).expect("Couldn't register").expect("Didn't get an auth token");
// the gam token
let auth = gam
.register_ux(UxRegistration {
app_name: xous_ipc::String::from_str(APP_NAME_APP_LOADER),
ux_type: gam::UxType::Modal,
predictor: None,
listener: sid.to_array(),
redraw_id: Opcode::Redraw.to_u32().unwrap(),
gotinput_id: None,
audioframe_id: None,
focuschange_id: None,
rawkeys_id: None,
})
.expect("Couldn't register")
.expect("Didn't get an auth token");
let modals = Modals::new(xns).expect("Couldn't get modals");
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");
// a connection to the 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 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)),
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)),
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");
// the menu
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)),
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");
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];
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() {
Ok(response) => response,
Err(e) => {
self.modals.show_notification(&format!("{}{}", t!("apploader.addapp.server_error", locales::LANG), e), None).expect("Couldn't show modal");
return;
}
};
//////////////////////////
// The downloading part //
//////////////////////////
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");
return;
}
};
let len = match response.header("Content-Length") {
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");
return;
}
};
let len = match response.header("Content-Length") {
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");
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");
//////////////////////
// The loading part //
//////////////////////
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 spawn = xous::create_process(args).expect("Couldn't create spawn process");
log::info!("Spawn PID: {}, Spawn CID: {}", spawn.pid, spawn.cid);
// 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 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))
.unwrap();
assert_eq!(xous::Result::Scalar1(2), result);
// 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),
)
.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");
// 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"),
_ => {
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;
}
}
// 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");
// 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"),
_ => {
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;
}
}
//////////////////////
// back to graphics //
//////////////////////
//////////////////////
// back to graphics //
//////////////////////
// add its name to GAM
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");
}
// add its name to GAM
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");
}
// add it to the menu
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,
);
self.apps.push(name);
// add it to the menu
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);
self.apps.push(name);
log::info!("Added app `{}'!", name);
log::info!("Added app `{}'!", name);
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
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()) {
Ok(_) => None,
Err(e) => Some(xous_ipc::String::from_str(&format!("{}{}", t!("apploader.setserver.error", locales::LANG), e))),
}))
.build()
.ok();
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
))),
},
),
)
.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)),
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)),
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);
}
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
)),
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)),
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,
);
}
self.server = payload.and_then(|p| Some(p.first().as_str().to_string()));
self.reload_app_list();
self.server = payload.and_then(|p| Some(p.first().as_str().to_string()));
self.reload_app_list();
}
pub(crate) fn open_load_menu(&mut self) {
self.current_menu = APP_MENU_1_APP_LOADER.to_string();
let _ = self.gam.switch_to_app(APP_NAME_APP_LOADER, self.auth);
self.current_menu = APP_MENU_1_APP_LOADER.to_string();
let _ = self.gam.switch_to_app(APP_NAME_APP_LOADER, self.auth);
}
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");
// 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");
let old = self.possible_apps.clone();
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 },
Err(e) => {
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 },
Err(e) => {
self.modals.show_notification(&format!("{}{}", t!("apploader.reloadapplist.json_error", locales::LANG), e), None).expect("Couldn't show modal");
return;
}
}
.iter()
.map(|(name, menus)| (xous_ipc::String::<64>::from_str(&name), *menus))
.collect();
// 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
}
Err(e) => {
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
}
Err(e) => {
self.modals
.show_notification(
&format!(
"{}{}",
t!("apploader.reloadapplist.json_error", locales::LANG),
e
),
None,
)
.expect("Couldn't show modal");
return;
}
}
.iter()
.map(|(name, menus)| (xous_ipc::String::<64>::from_str(&name), *menus))
.collect();
for (old_name, _) in old {
self.load_menu.delete_item(old_name.as_str().unwrap());
}
for (old_name, _) in old {
self.load_menu.delete_item(old_name.as_str().unwrap());
}
for (i, (app, _)) in self.possible_apps.iter().enumerate() {
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);
}
self.modals.finish_progress().expect("Couldn't close progress bar");
for (i, (app, _)) in self.possible_apps.iter().enumerate() {
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,
);
}
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
let _ = self.gam.switch_to_app(APP_NAME_APP_LOADER, self.auth); // try to switch back to the menu
}
pub(crate) fn dispatch_app(&self, index: usize) {
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));
} else {
panic!("Unrecognized app index");
}
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));
} else {
panic!("Unrecognized app index");
}
}
pub(crate) fn redraw(&mut self) {
// Properly close the app menu
// for anyone who needs this I found this in Menu::key_event
self.gam.relinquish_focus().unwrap();
xous::yield_slice();
// Properly close the app menu
// for anyone who needs this I found this in Menu::key_event
self.gam.relinquish_focus().unwrap();
xous::yield_slice();
self.ticktimer.sleep_ms(100).ok(); // yield for a moment to allow the previous menu to close
self.ticktimer.sleep_ms(100).ok(); // yield for a moment to allow the previous menu to close
// open the submenu if possible
let _ = self.gam.raise_menu(&self.current_menu);
// we only ever need the other menu for one thing
self.current_menu = APP_MENU_0_APP_LOADER.to_string();
// open the submenu if possible
let _ = self.gam.raise_menu(&self.current_menu);
// we only ever need the other menu for one thing
self.current_menu = APP_MENU_0_APP_LOADER.to_string();
}
}
@ -265,5 +444,5 @@ pub(crate) enum Opcode {
DispatchApp,
/// Redraw the UI
Redraw
Redraw,
}

View file

@ -10,34 +10,36 @@ 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);
loop {
let msg = xous::receive_message(sid).unwrap();
let msg = xous::receive_message(sid).unwrap();
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();
},
}
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,8 +130,9 @@ 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);
self.tm.register_name(name, auth_token);
}
pub(crate) fn allow_untrusted_code(&self) -> bool {
self.tm.allow_untrusted_code()

View file

@ -311,14 +311,15 @@ 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),
auth_token
};
let buf = Buffer::into_buf(name_registration).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::RegisterName.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
Ok(())
let name_registration = NameRegistration {
name: String::<128>::from_str(name),
auth_token
};
let buf = Buffer::into_buf(name_registration).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::RegisterName.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
Ok(())
}
pub fn set_predictor_api_token(&self, api_token: [u32; 4], gam_token: [u32; 4]) -> Result<(), xous::Error> {
let at = ApiToken {

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,11 +673,13 @@ fn wrapped_main() -> ! {
context_mgr.allow_mainmenu();
xous::return_scalar(msg.sender, 0).ok();
}
Some(Opcode::RegisterName) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let registration = buffer.to_original::<NameRegistration, _>().unwrap();
context_mgr.register_name(registration.name.to_str(), &registration.auth_token);
}
#[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,
None => {log::error!("unhandled message {:?}", msg);}
}

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(),
extra_names: 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,9 +59,10 @@ impl<'a> TokenManager {
if EXPECTED_APP_CONTEXTS.iter().find(|&&context| context == name).is_some() {
found = true;
}
if self.extra_names.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;
}
if !found {
log::error!("Server {} is not pre-registered in gam/lib.rs/EXPECTED_BOOT_CONTEXTS or apps.rs/EXPECTED_APP_CONTEXTS. Did you forget to register it?", name);
return None
@ -96,15 +103,20 @@ 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() {
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);
}
} else {
log::error!("Token {:?} does not correspond with a name", auth_token);
}
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() {
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);
}
} else {
log::error!("Token {:?} does not correspond with a name", auth_token);
}
}
}