Skip to content

Commit

Permalink
Use log::panic!() in no-std contexts (#284)
Browse files Browse the repository at this point in the history
  • Loading branch information
ia0 authored Nov 8, 2023
1 parent ca4c264 commit 91e4f69
Show file tree
Hide file tree
Showing 19 changed files with 79 additions and 46 deletions.
6 changes: 6 additions & 0 deletions crates/board/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 0.5.1-git

### Patch

- Use `logger` alias instead of `log` for `wasefire-logger` crate

## 0.5.0

### Major
Expand Down
2 changes: 1 addition & 1 deletion crates/board/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/board/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "wasefire-board-api"
version = "0.5.0"
version = "0.5.1-git"
authors = ["Julien Cretin <[email protected]>"]
license = "Apache-2.0"
publish = true
Expand Down
16 changes: 8 additions & 8 deletions crates/board/src/usb/serial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use usb_device::class_prelude::UsbBus;
use usb_device::UsbError;
use usbd_serial::SerialPort;
use wasefire_logger as logger;
use wasefire_logger as log;

use crate::{Error, Unsupported};

Expand Down Expand Up @@ -132,12 +132,12 @@ impl<T: HasSerial> Api for WithSerial<T> {
fn read(output: &mut [u8]) -> Result<usize, Error> {
match T::with_serial(|serial| serial.port.read(output)) {
Ok(len) => {
logger::trace!("{}{:?} = read({})", len, &output[.. len], output.len());
log::trace!("{}{:?} = read({})", len, &output[.. len], output.len());
Ok(len)
}
Err(UsbError::WouldBlock) => Ok(0),
Err(e) => {
logger::debug!("{} = read({})", logger::Debug2Format(&e), output.len());
log::debug!("{} = read({})", log::Debug2Format(&e), output.len());
Err(Error::World)
}
}
Expand All @@ -150,12 +150,12 @@ impl<T: HasSerial> Api for WithSerial<T> {
}
match T::with_serial(|serial| serial.port.write(input)) {
Ok(len) => {
logger::trace!("{} = write({}{:?})", len, input.len(), input);
log::trace!("{} = write({}{:?})", len, input.len(), input);
Ok(len)
}
Err(UsbError::WouldBlock) => Ok(0),
Err(e) => {
logger::debug!("{} = write({}{:?})", logger::Debug2Format(&e), input.len(), input);
log::debug!("{} = write({}{:?})", log::Debug2Format(&e), input.len(), input);
Err(Error::World)
}
}
Expand All @@ -165,15 +165,15 @@ impl<T: HasSerial> Api for WithSerial<T> {
loop {
match T::with_serial(|serial| serial.port.flush()) {
Ok(()) => {
logger::trace!("flush()");
log::trace!("flush()");
break Ok(());
}
Err(UsbError::WouldBlock) => {
logger::debug!("flush() didn't flush all data, retrying");
log::debug!("flush() didn't flush all data, retrying");
continue;
}
Err(e) => {
logger::debug!("{} = flush()", logger::Debug2Format(&e));
log::debug!("{} = flush()", log::Debug2Format(&e));
break Err(Error::World);
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/runner-host/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/runner-nordic/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions crates/runner-nordic/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ use usbd_serial::{SerialPort, USB_CLASS_CDC};
use wasefire_board_api::usb::serial::Serial;
use wasefire_board_api::{Id, Support};
use wasefire_scheduler::Scheduler;
use {wasefire_board_api as board, wasefire_logger as logger};
use {wasefire_board_api as board, wasefire_logger as log};

use crate::storage::Storage;
use crate::tasks::button::{self, channel, Button};
Expand Down Expand Up @@ -100,7 +100,7 @@ fn main() -> ! {
#[cfg(feature = "debug")]
systick::init(c.SYST);
allocator::init();
logger::debug!("Runner starts.");
log::debug!("Runner starts.");
let p = nrf52840_hal::pac::Peripherals::take().unwrap();
let port0 = gpio::p0::Parts::new(p.P0);
let buttons = [
Expand Down Expand Up @@ -146,7 +146,7 @@ fn main() -> ! {
for &interrupt in INTERRUPTS {
unsafe { NVIC::unmask(interrupt) };
}
logger::debug!("Runner is initialized.");
log::debug!("Runner is initialized.");
const WASM: &[u8] = include_bytes!("../../../target/wasefire/applet.wasm");
Scheduler::<Board>::run(WASM)
}
Expand Down
6 changes: 3 additions & 3 deletions crates/runner-nordic/src/tasks/clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use nrf52840_hal::timer::{Instance, OneShot, Periodic};
use nrf52840_hal::Timer;
use wasefire_board_api::timer::{Api, Command};
use wasefire_board_api::{Error, Id, Support};
use wasefire_logger as logger;
use wasefire_logger as log;

use crate::with_state;

Expand Down Expand Up @@ -113,7 +113,7 @@ impl<T: Instance + Send> ErasedSlot for Slot<T> {
Slot::Periodic(x) => x.cancel(),
};
if result.is_err() {
logger::error!("Could not cancel timer.");
log::error!("Could not cancel timer.");
}
}

Expand Down Expand Up @@ -146,7 +146,7 @@ impl<T: Instance + Send> ErasedSlot for Slot<T> {
Slot::Periodic(x) => x.wait().is_ok(),
};
if !done {
logger::error!("Called wait but timer is not done.");
log::error!("Called wait but timer is not done.");
}
}
}
5 changes: 5 additions & 0 deletions crates/scheduler/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
### Minor

- Use `debug::exit()` board API when the applet traps
- Use `log::panic!()` on interpreter errors

### Patch

- Use `logger` alias instead of `log` for `wasefire-logger` crate

## 0.2.2

Expand Down
2 changes: 1 addition & 1 deletion crates/scheduler/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/scheduler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ digest = { version = "0.10.7", default-features = false, features = ["mac"] }
generic-array = { version = "0.14.7", default-features = false }
typenum = { version = "1.17.0", default-features = false }
wasefire-applet-api = { version = "0.5.0", path = "../api", features = ["host"] }
wasefire-board-api = { version = "0.5.0", path = "../board" }
wasefire-board-api = { version = "0.5.1-git", path = "../board" }
wasefire-interpreter = { version = "0.1.4", path = "../interpreter", features = ["toctou"] }
wasefire-logger = { version = "0.1.3", path = "../logger" }
wasefire-store = { version = "0.2.2", path = "../store" }
Expand Down
4 changes: 2 additions & 2 deletions crates/scheduler/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use core::borrow::Borrow;
use derivative::Derivative;
use wasefire_board_api::{Api as Board, Event};
use wasefire_interpreter::InstId;
use wasefire_logger as logger;
use wasefire_logger as log;

use crate::Scheduler;

Expand Down Expand Up @@ -93,7 +93,7 @@ pub fn process<B: Board>(scheduler: &mut Scheduler<B>, event: Event<B>) {
Some(x) => x,
None => {
// This should not happen because we remove pending events when disabling an event.
logger::error!("Missing handler for event.");
log::error!("Missing handler for event.");
return;
}
};
Expand Down
31 changes: 15 additions & 16 deletions crates/scheduler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ use wasefire_board_api::{self as board, Api as Board, Singleton, Support};
use wasefire_interpreter::{
self as interpreter, Call, Error, InstId, Module, RunAnswer, RunResult, Store, Val,
};
use wasefire_logger::{self as logger, *};
use wasefire_store as store;
use {wasefire_logger as log, wasefire_store as store};

mod call;
mod event;
Expand All @@ -59,17 +58,17 @@ impl<B: Board> Events<B> {
pub fn push(&mut self, event: board::Event<B>) {
const MAX_EVENTS: usize = 10;
if self.0.contains(&event) {
trace!("Merging {}", Debug2Format(&event));
log::trace!("Merging {}", log::Debug2Format(&event));
} else if self.0.len() < MAX_EVENTS {
debug!("Pushing {}", Debug2Format(&event));
log::debug!("Pushing {}", log::Debug2Format(&event));
self.0.push_back(event);
} else {
warn!("Dropping {}", Debug2Format(&event));
log::warn!("Dropping {}", log::Debug2Format(&event));
}
}

pub fn pop(&mut self) -> Option<board::Event<B>> {
self.0.pop_front().inspect(|event| debug!("Popping {}", Debug2Format(&event)))
self.0.pop_front().inspect(|event| log::debug!("Popping {}", log::Debug2Format(&event)))
}
}

Expand Down Expand Up @@ -185,7 +184,7 @@ impl<'a, B: Board, T: Signature> SchedulerCall<'a, B, T> {
impl<B: Board> Scheduler<B> {
pub fn run(wasm: &'static [u8]) -> ! {
let mut scheduler = Self::new();
debug!("Loading applet.");
log::debug!("Loading applet.");
scheduler.load(wasm);
loop {
scheduler.flush_events();
Expand Down Expand Up @@ -230,9 +229,9 @@ impl<B: Board> Scheduler<B> {
self.perf.record(perf::Slot::Platform);
match store.invoke(inst, "init", vec![]) {
Ok(RunResult::Done(x)) => assert!(x.is_empty()),
Ok(RunResult::Host { .. }) => logger::panic!("init called into host"),
Ok(RunResult::Host { .. }) => log::panic!("init called into host"),
Err(Error::NotFound) => (),
Err(e) => core::panic!("{e:?}"),
Err(e) => log::panic!("{}", log::Debug2Format(&e)),
}
#[cfg(feature = "debug")]
self.perf.record(perf::Slot::Applets);
Expand Down Expand Up @@ -279,7 +278,7 @@ impl<B: Board> Scheduler<B> {
let args = args.iter().map(|x| x.unwrap_i32()).collect();
let erased = SchedulerCallT { scheduler: self, args };
let call = api_id.merge(erased);
debug!("Calling {}", Debug2Format(&call.id()));
log::debug!("Calling {}", log::Debug2Format(&call.id()));
call::process(call);
}

Expand All @@ -290,7 +289,7 @@ impl<B: Board> Scheduler<B> {
}

fn call(&mut self, inst: InstId, name: &'static str, args: &[u32]) {
debug!("Schedule thread {}{:?}.", name, args);
log::debug!("Schedule thread {}{:?}.", name, args);
let args = args.iter().map(|&x| Val::I32(x)).collect();
#[cfg(feature = "debug")]
self.perf.record(perf::Slot::Platform);
Expand All @@ -303,13 +302,13 @@ impl<B: Board> Scheduler<B> {
fn process_answer(&mut self, result: Result<RunAnswer, interpreter::Error>) {
match result {
Ok(RunAnswer::Done(x)) => {
debug!("Thread is done.");
log::debug!("Thread is done.");
debug_assert!(x.is_empty());
self.applet.done();
}
Ok(RunAnswer::Host) => (),
Err(Error::Trap) => applet_trapped::<B>(None),
Err(e) => core::panic!("{e:?}"),
Err(e) => log::panic!("{}", log::Debug2Format(&e)),
}
}
}
Expand All @@ -321,9 +320,9 @@ fn convert_results<T: Signature>(results: T::Results) -> Vec<Val> {
fn applet_trapped<B: Board>(reason: Option<&'static str>) -> ! {
// Until we support multiple applets, we just exit the platform when the applet traps.
match reason {
None => logger::error!("Applet trapped in wasm (think segfault)."),
Some("sa") => logger::error!("Applet aborted (probably a panic)."),
Some(name) => logger::error!("Applet trapped calling host {:?}.", name),
None => log::error!("Applet trapped in wasm (think segfault)."),
Some("sa") => log::error!("Applet aborted (probably a panic)."),
Some(name) => log::error!("Applet trapped calling host {:?}.", name),
}
<board::Debug<B> as board::debug::Api>::exit(false);
}
Expand Down
6 changes: 6 additions & 0 deletions crates/stub/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 0.1.3-git

### Minor

- Use `wasefire-logger` for panics

## 0.1.2

### Patch
Expand Down
7 changes: 6 additions & 1 deletion crates/stub/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion crates/stub/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "wasefire-stub"
version = "0.1.2"
version = "0.1.3-git"
authors = ["Julien Cretin <[email protected]>"]
license = "Apache-2.0"
publish = true
Expand All @@ -25,3 +25,4 @@ rand = { version = "0.8.5", default-features = false, features = ["std", "std_rn
sha2 = { version = "0.10.7", default-features = false }
signature = { version = "2.1.0", default-features = false }
wasefire-applet-api = { version = "0.5.0", path = "../api", features = ["native", "wasm"] }
wasefire-logger = { version = "0.1.3", path = "../logger" }
9 changes: 5 additions & 4 deletions crates/stub/src/crypto/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use hkdf::{Hkdf, HmacImpl};
use hmac::Hmac;
use sha2::{Sha256, Sha384};
use wasefire_applet_api::crypto::{hash as api, Error};
use wasefire_logger as log;

enum Context {
Sha256(Sha256),
Expand Down Expand Up @@ -77,7 +78,7 @@ unsafe extern "C" fn chu(params: api::update::Params) {
match CONTEXTS.lock().unwrap().get(id) {
Context::Sha256(x) => x.update(data),
Context::Sha384(x) => x.update(data),
_ => panic!("Invalid context"),
_ => log::panic!("Invalid context"),
};
}

Expand All @@ -88,7 +89,7 @@ unsafe extern "C" fn chf(params: api::finalize::Params) -> api::finalize::Result
match CONTEXTS.lock().unwrap().take(id) {
Context::Sha256(x) => x.finalize_into(digest(32).into()),
Context::Sha384(x) => x.finalize_into(digest(48).into()),
_ => panic!("Invalid context"),
_ => log::panic!("Invalid context"),
};
api::finalize::Results { res: 0 }
}
Expand Down Expand Up @@ -122,7 +123,7 @@ unsafe extern "C" fn chv(params: api::hmac_update::Params) {
match CONTEXTS.lock().unwrap().get(id) {
Context::HmacSha256(x) => x.update(data),
Context::HmacSha384(x) => x.update(data),
_ => panic!("Invalid context"),
_ => log::panic!("Invalid context"),
};
}

Expand All @@ -133,7 +134,7 @@ unsafe extern "C" fn chg(params: api::hmac_finalize::Params) -> api::hmac_finali
match CONTEXTS.lock().unwrap().take(id) {
Context::HmacSha256(x) => x.finalize_into(hmac(32).into()),
Context::HmacSha384(x) => x.finalize_into(hmac(48).into()),
_ => panic!("Invalid context"),
_ => log::panic!("Invalid context"),
};
api::hmac_finalize::Results { res: 0 }
}
Expand Down
Loading

0 comments on commit 91e4f69

Please sign in to comment.