diff --git a/.github/workflows/doc.yml b/.github/workflows/doc.yml
index eb460e738..4bc73fdcf 100644
--- a/.github/workflows/doc.yml
+++ b/.github/workflows/doc.yml
@@ -17,7 +17,7 @@ jobs:
strategy:
matrix:
crates:
- - stm32
+ #- stm32 # runs out of disk space...
- rest
# This will ensure at most one doc build job is running at a time
@@ -46,7 +46,7 @@ jobs:
- name: Install docserver
run: |
- wget -q -O /usr/local/bin/builder "https://github.com/embassy-rs/docserver/releases/download/v0.3/builder"
+ wget -q -O /usr/local/bin/builder "https://github.com/embassy-rs/docserver/releases/download/v0.4/builder"
chmod +x /usr/local/bin/builder
- name: build-stm32
@@ -69,12 +69,15 @@ jobs:
builder ./embassy-futures crates/embassy-futures/git.zup
builder ./embassy-lora crates/embassy-lora/git.zup
builder ./embassy-net crates/embassy-net/git.zup
+ builder ./embassy-net-driver crates/embassy-net-driver/git.zup
+ builder ./embassy-net-driver-channel crates/embassy-net-driver-channel/git.zup
builder ./embassy-nrf crates/embassy-nrf/git.zup
builder ./embassy-rp crates/embassy-rp/git.zup
builder ./embassy-sync crates/embassy-sync/git.zup
builder ./embassy-time crates/embassy-time/git.zup
builder ./embassy-usb crates/embassy-usb/git.zup
builder ./embassy-usb-driver crates/embassy-usb-driver/git.zup
+ builder ./embassy-usb-logger crates/embassy-usb-logger/git.zup
- name: upload
run: |
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml
index b93c8783d..3bfe5ef03 100644
--- a/.github/workflows/rust.yml
+++ b/.github/workflows/rust.yml
@@ -68,5 +68,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- - name: Test
- run: cd embassy-sync && cargo test
+
+ - name: Test boot
+ working-directory: ./embassy-boot/boot
+ run: cargo test && cargo test --features "ed25519-dalek" && cargo test --features "ed25519-salty"
+
+ - name: Test sync
+ working-directory: ./embassy-sync
+ run: cargo test
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 5e9e51799..db37b64ce 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -1,29 +1,27 @@
{
"editor.formatOnSave": true,
- "rust-analyzer.checkOnSave.allTargets": false,
- "rust-analyzer.checkOnSave.noDefaultFeatures": true,
+ "rust-analyzer.check.allTargets": false,
+ "rust-analyzer.check.noDefaultFeatures": true,
"rust-analyzer.cargo.noDefaultFeatures": true,
"rust-analyzer.procMacro.enable": true,
"rust-analyzer.cargo.target": "thumbv7em-none-eabi",
+ //"rust-analyzer.cargo.target": "thumbv8m.main-none-eabihf",
"rust-analyzer.cargo.features": [
- // These are needed to prevent embassy-net from failing to build
- //"embassy-net/medium-ethernet",
- //"embassy-net/tcp",
- //"embassy-net/pool-16",
- //"time-tick-16mhz",
- //"defmt-timestamp-uptime",
"nightly",
- //"unstable-traits",
],
"rust-analyzer.linkedProjects": [
// Declare for the target you wish to develop
- //"embassy-executor/Cargo.toml",
- //"embassy-sync/Cargo.toml",
- "examples/nrf/Cargo.toml",
+ // "embassy-executor/Cargo.toml",
+ // "embassy-sync/Cargo.toml",
+ "examples/nrf52840/Cargo.toml",
+ //"examples/nrf5340/Cargo.toml",
+ // "examples/nrf-rtos-trace/Cargo.toml",
// "examples/rp/Cargo.toml",
// "examples/std/Cargo.toml",
// "examples/stm32f0/Cargo.toml",
// "examples/stm32f1/Cargo.toml",
+ // "examples/stm32f2/Cargo.toml",
+ // "examples/stm32f3/Cargo.toml",
// "examples/stm32f4/Cargo.toml",
// "examples/stm32f7/Cargo.toml",
// "examples/stm32g0/Cargo.toml",
@@ -32,8 +30,11 @@
// "examples/stm32l0/Cargo.toml",
// "examples/stm32l1/Cargo.toml",
// "examples/stm32l4/Cargo.toml",
+ // "examples/stm32l5/Cargo.toml",
// "examples/stm32u5/Cargo.toml",
+ // "examples/stm32wb/Cargo.toml",
// "examples/stm32wb55/Cargo.toml",
+ // "examples/stm32wl/Cargo.toml",
// "examples/stm32wl55/Cargo.toml",
// "examples/wasm/Cargo.toml",
],
diff --git a/README.md b/README.md
index 9f08bf676..938f2f4a6 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@ Rust's async/await allows
No more messing with hardware timers. embassy_time provides Instant, Duration and Timer types that are globally available and never overflow.
- **Real-time ready** -
-Tasks on the same async executor run cooperatively, but you can create multiple executors with different priorities, so that higher priority tasks preempt lower priority ones. See the example.
+Tasks on the same async executor run cooperatively, but you can create multiple executors with different priorities, so that higher priority tasks preempt lower priority ones. See the example.
- **Low-power ready** -
Easily build devices with years of battery life. The async executor automatically puts the core to sleep when there's no work to do. Tasks are woken by interrupts, there is no busy-loop polling while waiting.
@@ -31,7 +31,7 @@ The embassy-net network stac
The nrf-softdevice crate provides Bluetooth Low Energy 4.x and 5.x support for nRF52 microcontrollers.
- **LoRa** -
-embassy-lora supports LoRa networking on STM32WL wireless microcontrollers and Semtech SX127x transceivers.
+embassy-lora supports LoRa networking on STM32WL wireless microcontrollers and Semtech SX126x and SX127x transceivers.
- **USB** -
embassy-usb implements a device-side USB stack. Implementations for common classes such as USB serial (CDC ACM) and USB HID are available, and a rich builder API allows building your own.
@@ -87,7 +87,8 @@ async fn main(spawner: Spawner) {
Examples are found in the `examples/` folder seperated by the chip manufacturer they are designed to run on. For example:
-* `examples/nrf` run on the `nrf52840-dk` board (PCA10056) but should be easily adaptable to other nRF52 chips and boards.
+* `examples/nrf52840` run on the `nrf52840-dk` board (PCA10056) but should be easily adaptable to other nRF52 chips and boards.
+* `examples/nrf5340` run on the `nrf5340-dk` board (PCA10095).
* `examples/stm32xx` for the various STM32 families.
* `examples/rp` are for the RP2040 chip.
* `examples/std` are designed to run locally on your PC.
@@ -110,7 +111,7 @@ cargo install probe-run
- Change directory to the sample's base directory. For example:
```bash
-cd examples/nrf
+cd examples/nrf52840
```
- Run the example
diff --git a/ci.sh b/ci.sh
index cd1c0786c..4199f91d3 100755
--- a/ci.sh
+++ b/ci.sh
@@ -36,10 +36,12 @@ cargo batch \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,log \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,defmt \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt \
- --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,pool-16 \
- --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,pool-16,unstable-traits \
- --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,pool-16,nightly \
- --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,pool-16,unstable-traits,nightly \
+ --- build --release --manifest-path embassy-sync/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt \
+ --- build --release --manifest-path embassy-time/Cargo.toml --target thumbv6m-none-eabi --features nightly,unstable-traits,defmt,defmt-timestamp-uptime,tick-hz-32_768,generic-queue-8 \
+ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet \
+ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,unstable-traits \
+ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,nightly \
+ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,unstable-traits,nightly \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52805,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52810,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52811,gpiote,time-driver-rtc1 \
@@ -61,7 +63,8 @@ cargo batch \
--- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,intrinsics \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f410tb,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f411ce,defmt,exti,time-driver-any,unstable-traits \
- --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f429zi,log,exti,time-driver-any,unstable-traits \
+ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f413vh,defmt,exti,time-driver-any,unstable-traits \
+ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f429zi,log,exti,time-driver-any,unstable-traits,embedded-sdmmc \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h755zi-cm7,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h7b3ai,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32l476vg,defmt,exti,time-driver-any,unstable-traits \
@@ -74,18 +77,21 @@ cargo batch \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f217zg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,stm32l552ze,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32wl54jc-cm0p,defmt,exti,time-driver-any,unstable-traits \
- --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32wle5ub,defmt,exti,time-driver-any,unstable-traits \
+ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32wle5jb,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f107vc,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f103re,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f100c4,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-boot/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840 \
+ --- build --release --manifest-path embassy-boot/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns \
+ --- build --release --manifest-path embassy-boot/rp/Cargo.toml --target thumbv6m-none-eabi \
--- build --release --manifest-path embassy-boot/stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wl55jc-cm4 \
--- build --release --manifest-path docs/modules/ROOT/examples/basic/Cargo.toml --target thumbv7em-none-eabi \
--- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-pac/Cargo.toml --target thumbv7em-none-eabi \
--- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-hal/Cargo.toml --target thumbv7em-none-eabi \
--- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-irq/Cargo.toml --target thumbv7em-none-eabi \
--- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-async/Cargo.toml --target thumbv7em-none-eabi \
- --- build --release --manifest-path examples/nrf/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/nrf \
+ --- build --release --manifest-path examples/nrf52840/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/nrf52840 \
+ --- build --release --manifest-path examples/nrf5340/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/nrf5340 \
--- build --release --manifest-path examples/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/rp \
--- build --release --manifest-path examples/stm32f0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32f0 \
--- build --release --manifest-path examples/stm32f1/Cargo.toml --target thumbv7m-none-eabi --out-dir out/examples/stm32f1 \
@@ -93,6 +99,7 @@ cargo batch \
--- build --release --manifest-path examples/stm32f3/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f3 \
--- build --release --manifest-path examples/stm32f4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32f4 \
--- build --release --manifest-path examples/stm32f7/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f7 \
+ --- build --release --manifest-path examples/stm32c0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32c0 \
--- build --release --manifest-path examples/stm32g0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32g0 \
--- build --release --manifest-path examples/stm32g4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32g4 \
--- build --release --manifest-path examples/stm32h7/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h7 \
@@ -103,7 +110,9 @@ cargo batch \
--- build --release --manifest-path examples/stm32u5/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32u5 \
--- build --release --manifest-path examples/stm32wb/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32wb \
--- build --release --manifest-path examples/stm32wl/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32wl \
- --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/boot/nrf --bin b \
+ --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840 --out-dir out/examples/boot/nrf --bin b \
+ --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns --out-dir out/examples/boot/nrf --bin b \
+ --- build --release --manifest-path examples/boot/application/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/boot/rp --bin b \
--- build --release --manifest-path examples/boot/application/stm32f3/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/boot/stm32f3 --bin b \
--- build --release --manifest-path examples/boot/application/stm32f7/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/boot/stm32f7 --bin b \
--- build --release --manifest-path examples/boot/application/stm32h7/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/boot/stm32h7 --bin b \
@@ -112,6 +121,8 @@ cargo batch \
--- build --release --manifest-path examples/boot/application/stm32l4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/boot/stm32l4 --bin b \
--- build --release --manifest-path examples/boot/application/stm32wl/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/boot/stm32wl --bin b \
--- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840 \
+ --- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns \
+ --- build --release --manifest-path examples/boot/bootloader/rp/Cargo.toml --target thumbv6m-none-eabi \
--- build --release --manifest-path examples/boot/bootloader/stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wl55jc-cm4 \
--- build --release --manifest-path examples/wasm/Cargo.toml --target wasm32-unknown-unknown --out-dir out/examples/wasm \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f103c8 --out-dir out/tests/bluepill-stm32f103c8 \
diff --git a/ci_stable.sh b/ci_stable.sh
index 0332c3faf..b4b0b83e7 100755
--- a/ci_stable.sh
+++ b/ci_stable.sh
@@ -13,8 +13,8 @@ cargo batch \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features log \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features defmt \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv6m-none-eabi --features defmt \
- --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,pool-16 \
- --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,pool-16,unstable-traits \
+ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet \
+ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,unstable-traits \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nrf52805,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nrf52810,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nrf52811,gpiote,time-driver-rtc1 \
@@ -36,7 +36,7 @@ cargo batch \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32g491re,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u585zi,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb55vy,defmt,exti,time-driver-any,unstable-traits \
- --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wl55uc-cm4,defmt,exti,time-driver-any,unstable-traits \
+ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wl55cc-cm4,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l4r9zi,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f303vc,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f411ce,defmt,time-driver-any \
@@ -65,5 +65,5 @@ cargo batch \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l151cb-a,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f217zg,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f217zg,defmt,exti,time-driver-any,unstable-traits \
- --- build --release --manifest-path examples/nrf/Cargo.toml --target thumbv7em-none-eabi --no-default-features --out-dir out/examples/nrf --bin raw_spawn \
+ --- build --release --manifest-path examples/nrf52840/Cargo.toml --target thumbv7em-none-eabi --no-default-features --out-dir out/examples/nrf52840 --bin raw_spawn \
--- build --release --manifest-path examples/stm32l0/Cargo.toml --target thumbv6m-none-eabi --no-default-features --out-dir out/examples/stm32l0 --bin raw_spawn \
diff --git a/docs/modules/ROOT/examples/basic/Cargo.toml b/docs/modules/ROOT/examples/basic/Cargo.toml
index c13f546e2..d9f8a285a 100644
--- a/docs/modules/ROOT/examples/basic/Cargo.toml
+++ b/docs/modules/ROOT/examples/basic/Cargo.toml
@@ -6,14 +6,13 @@ version = "0.1.0"
license = "MIT OR Apache-2.0"
[dependencies]
-embassy-executor = { version = "0.1.0", path = "../../../../../embassy-executor", features = ["defmt", "nightly"] }
+embassy-executor = { version = "0.1.0", path = "../../../../../embassy-executor", features = ["defmt", "nightly", "integrated-timers"] }
embassy-time = { version = "0.1.0", path = "../../../../../embassy-time", features = ["defmt", "nightly"] }
embassy-nrf = { version = "0.1.0", path = "../../../../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "nightly"] }
defmt = "0.3"
defmt-rtt = "0.3"
-cortex-m = "0.7.3"
+cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] }
cortex-m-rt = "0.7.0"
-embedded-hal = "0.2.6"
panic-probe = { version = "0.3", features = ["print-defmt"] }
diff --git a/examples/nrf/build.rs b/docs/modules/ROOT/examples/basic/build.rs
similarity index 100%
rename from examples/nrf/build.rs
rename to docs/modules/ROOT/examples/basic/build.rs
diff --git a/examples/nrf/memory.x b/docs/modules/ROOT/examples/basic/memory.x
similarity index 100%
rename from examples/nrf/memory.x
rename to docs/modules/ROOT/examples/basic/memory.x
diff --git a/docs/modules/ROOT/pages/basic_application.adoc b/docs/modules/ROOT/pages/basic_application.adoc
index 4dc4a6359..3f4f16e28 100644
--- a/docs/modules/ROOT/pages/basic_application.adoc
+++ b/docs/modules/ROOT/pages/basic_application.adoc
@@ -21,7 +21,7 @@ Then, what follows are some declarations on how to deal with panics and faults.
[source,rust]
----
-include::example$basic/src/main.rs[lines="11..12"]
+include::example$basic/src/main.rs[lines="10"]
----
=== Task declaration
@@ -30,7 +30,7 @@ After a bit of import declaration, the tasks run by the application should be de
[source,rust]
----
-include::example$basic/src/main.rs[lines="13..22"]
+include::example$basic/src/main.rs[lines="12..20"]
----
An embassy task must be declared `async`, and may NOT take generic arguments. In this case, we are handed the LED that should be blinked and the interval of the blinking.
@@ -45,23 +45,10 @@ The `Spawner` is the way the main application spawns other tasks. The `Periphera
[source,rust]
----
-include::example$basic/src/main.rs[lines="23..-1"]
+include::example$basic/src/main.rs[lines="22..-1"]
----
-`#[embassy_executor::main]` takes an optional `config` parameter specifying a function that returns an instance of HAL's `Config` struct. For example:
-
-```rust
-fn embassy_config() -> embassy_nrf::config::Config {
- embassy_nrf::config::Config::default()
-}
-
-#[embassy_executor::main(config = "embassy_config()")]
-async fn main(_spawner: Spawner, p: embassy_nrf::Peripherals) {
- // ...
-}
-```
-
-What happens when the `blinker` task have been spawned and main returns? Well, the main entry point is actually just like any other task, except that you can only have one and it takes some specific type arguments. The magic lies within the `#[embassy::main]` macro. The macro does the following:
+What happens when the `blinker` task has been spawned and main returns? Well, the main entry point is actually just like any other task, except that you can only have one and it takes some specific type arguments. The magic lies within the `#[embassy::main]` macro. The macro does the following:
. Creates an Embassy Executor
. Initializes the microcontroller HAL to get the `Peripherals`
@@ -76,7 +63,7 @@ The project definition needs to contain the embassy dependencies:
[source,toml]
----
-include::example$basic/Cargo.toml[lines="8..9"]
+include::example$basic/Cargo.toml[lines="9..11"]
----
Depending on your microcontroller, you may need to replace `embassy-nrf` with something else (`embassy-stm32` for STM32. Remember to update feature flags as well).
diff --git a/docs/modules/ROOT/pages/bootloader.adoc b/docs/modules/ROOT/pages/bootloader.adoc
index ae92e9d5d..b7215e52a 100644
--- a/docs/modules/ROOT/pages/bootloader.adoc
+++ b/docs/modules/ROOT/pages/bootloader.adoc
@@ -6,7 +6,7 @@ The bootloader can be used either as a library or be flashed directly if you are
By design, the bootloader does not provide any network capabilities. Networking capabilities for fetching new firmware can be provided by the user application, using the bootloader as a library for updating the firmware, or by using the bootloader as a library and adding this capability yourself.
-The bootloader supports both internal and external flash by relying on the `embedded-storage` traits.
+The bootloader supports both internal and external flash by relying on the `embedded-storage` traits. The bootloader optionally supports the verification of firmware that has been digitally signed (recommended).
== Hardware support
@@ -15,6 +15,7 @@ The bootloader supports
* nRF52 with and without softdevice
* STM32 L4, WB, WL, L1, L0, F3, F7 and H7
+* Raspberry Pi: RP2040
In general, the bootloader works on any platform that implements the `embedded-storage` traits for its internal flash, but may require custom initialization code to work.
@@ -25,12 +26,69 @@ image::bootloader_flash.png[Bootloader flash layout]
The bootloader divides the storage into 4 main partitions, configurable when creating the bootloader
instance or via linker scripts:
-* BOOTLOADER - Where the bootloader is placed. The bootloader itself consumes about 8kB of flash.
-* ACTIVE - Where the main application is placed. The bootloader will attempt to load the application at the start of this partition. This partition is only written to by the bootloader.
-* DFU - Where the application-to-be-swapped is placed. This partition is written to by the application.
-* BOOTLOADER STATE - Where the bootloader stores the current state describing if the active and dfu partitions need to be swapped. When the new firmware has been written to the DFU partition, a flag is set to instruct the bootloader that the partitions should be swapped.
+* BOOTLOADER - Where the bootloader is placed. The bootloader itself consumes about 8kB of flash, but if you need to debug it and have space available, increasing this to 24kB will allow you to run the bootloader with probe-rs.
+* ACTIVE - Where the main application is placed. The bootloader will attempt to load the application at the start of this partition. This partition is only written to by the bootloader. The size required for this partition depends on the size of your application.
+* DFU - Where the application-to-be-swapped is placed. This partition is written to by the application. This partition must be at least 1 page bigger than the ACTIVE partition, since the swap algorithm uses the extra space to ensure power safe copy of data:
++
+Partition Size~dfu~= Partition Size~active~+ Page Size~active~
++
+All values are specified in bytes.
+
+* BOOTLOADER STATE - Where the bootloader stores the current state describing if the active and dfu partitions need to be swapped. When the new firmware has been written to the DFU partition, a magic field is written to instruct the bootloader that the partitions should be swapped. This partition must be able to store a magic field as well as the partition swap progress. The partition size given by:
++
+Partition Size~state~ = Write Size~state~ + (2 × Partition Size~active~ / Page Size~active~)
++
+All values are specified in bytes.
The partitions for ACTIVE (+BOOTLOADER), DFU and BOOTLOADER_STATE may be placed in separate flash. The page size used by the bootloader is determined by the lowest common multiple of the ACTIVE and DFU page sizes.
The BOOTLOADER_STATE partition must be big enough to store one word per page in the ACTIVE and DFU partitions combined.
The bootloader has a platform-agnostic part, which implements the power fail safe swapping algorithm given the boundaries set by the partitions. The platform-specific part is a minimal shim that provides additional functionality such as watchdogs or supporting the nRF52 softdevice.
+
+=== FirmwareUpdater
+
+The `FirmwareUpdater` is an object for conveniently flashing firmware to the DFU partition and subsequently marking it as being ready for swapping with the active partition on the next reset. Its principle methods are `write_firmware`, which is called once per the size of the flash "write block" (typically 4KiB), and `mark_updated`, which is the final call.
+
+=== Verification
+
+The bootloader supports the verification of firmware that has been flashed to the DFU partition. Verification requires that firmware has been signed digitally using link:https://ed25519.cr.yp.to/[`ed25519`] signatures. With verification enabled, the `FirmwareUpdater::verify_and_mark_updated` method is called in place of `mark_updated`. A public key and signature are required, along with the actual length of the firmware that has been flashed. If verification fails then the firmware will not be marked as updated and therefore be rejected.
+
+Signatures are normally conveyed with the firmware to be updated and not written to flash. How signatures are provided is a firmware responsibility.
+
+To enable verification use either the `ed25519-dalek` or `ed25519-salty` features when depending on the `embassy-boot` crate. We recommend `ed25519-salty` at this time due to its small size.
+
+==== Tips on keys and signing with ed25519
+
+Ed25519 is a public key signature system where you are responsible for keeping the private key secure. We recommend embedding the *public* key in your program so that it can be easily passed to `verify_and_mark_updated`. An example declaration of the public key in your firmware:
+
+[source, rust]
+----
+static PUBLIC_SIGNING_KEY: &[u8] = include_bytes!("key.pub");
+----
+
+Signatures are often conveyed along with firmware by appending them.
+
+Ed25519 keys can be generated by a variety of tools. We recommend link:https://man.openbsd.org/signify[`signify`] as it is in wide use to sign and verify OpenBSD distributions, and is straightforward to use.
+
+The following set of Bash commands can be used to generate public and private keys on Unix platforms, and also generate a local `key.pub` file with the `signify` file headers removed. Declare a `SECRETS_DIR` environment variable in a secure location.
+
+[source, bash]
+----
+signify -G -n -p $SECRETS_DIR/key.pub -s $SECRETS_DIR/key.sec
+tail -n1 $SECRETS_DIR/key.pub | base64 -d -i - | dd ibs=10 skip=1 > key.pub
+chmod 700 $SECRETS_DIR/key.sec
+export SECRET_SIGNING_KEY=$(tail -n1 $SECRETS_DIR/key.sec)
+----
+
+Then, to sign your firmware given a declaration of `FIRMWARE_DIR` and a firmware filename of `myfirmware`:
+
+[source, bash]
+----
+shasum -a 512 -b $FIRMWARE_DIR/myfirmware > $SECRETS_DIR/message.txt
+cat $SECRETS_DIR/message.txt | dd ibs=128 count=1 | xxd -p -r > $SECRETS_DIR/message.txt
+signify -S -s $SECRETS_DIR/key.sec -m $SECRETS_DIR/message.txt -x $SECRETS_DIR/message.txt.sig
+cp $FIRMWARE_DIR/myfirmware $FIRMWARE_DIR/myfirmware+signed
+tail -n1 $SECRETS_DIR/message.txt.sig | base64 -d -i - | dd ibs=10 skip=1 >> $FIRMWARE_DIR/myfirmware+signed
+----
+
+Remember, guard the `$SECRETS_DIR/key.sec` key as compromising it means that another party can sign your firmware.
\ No newline at end of file
diff --git a/docs/modules/ROOT/pages/getting_started.adoc b/docs/modules/ROOT/pages/getting_started.adoc
index f3492a3d0..9015d7845 100644
--- a/docs/modules/ROOT/pages/getting_started.adoc
+++ b/docs/modules/ROOT/pages/getting_started.adoc
@@ -45,7 +45,7 @@ You can run an example by opening a terminal and entering the following commands
[source, bash]
----
-cd examples/nrf
+cd examples/nrf52840
cargo run --bin blinky --release
----
diff --git a/docs/modules/ROOT/pages/layer_by_layer.adoc b/docs/modules/ROOT/pages/layer_by_layer.adoc
index a96dd9fe2..a78a64a97 100644
--- a/docs/modules/ROOT/pages/layer_by_layer.adoc
+++ b/docs/modules/ROOT/pages/layer_by_layer.adoc
@@ -8,7 +8,7 @@ The application we'll write is a simple 'push button, blink led' application, wh
== PAC version
-The PAC is the lowest API for accessing peripherals and registers, if you don't count reading/writing directly to memory addresses. It provide distinct types
+The PAC is the lowest API for accessing peripherals and registers, if you don't count reading/writing directly to memory addresses. It provides distinct types
to make accessing peripheral registers easier, but it does not prevent you from writing unsafe code.
Writing an application using the PAC directly is therefore not recommended, but if the functionality you want to use is not exposed in the upper layers, that's what you need to use.
@@ -20,13 +20,13 @@ The blinky app using PAC is shown below:
include::example$layer-by-layer/blinky-pac/src/main.rs[]
----
-As you can see, there are a lot of code needed to enable the peripheral clocks, configuring the input pins and the output pins of the application.
+As you can see, a lot of code is needed to enable the peripheral clocks and to configure the input pins and the output pins of the application.
Another downside of this application is that it is busy-looping while polling the button state. This prevents the microcontroller from utilizing any sleep mode to save power.
== HAL version
-To simplify our application, we can use the HAL instead. The HAL exposes higher level APIs that handle details such
+To simplify our application, we can use the HAL instead. The HAL exposes higher level APIs that handle details such as:
* Automatically enabling the peripheral clock when you're using the peripheral
* Deriving and applying register configuration from higher level types
@@ -39,7 +39,7 @@ The HAL example is shown below:
include::example$layer-by-layer/blinky-hal/src/main.rs[]
----
-As you can see, the application becomes a lot simpler, even without using any async code. The `Input` and `Output` hides all the details accessing the GPIO registers, and allow you to use a much simpler API to query the state of the button and toggle the LED output accordingly.
+As you can see, the application becomes a lot simpler, even without using any async code. The `Input` and `Output` types hide all the details of accessing the GPIO registers and allow you to use a much simpler API for querying the state of the button and toggling the LED output.
The same downside from the PAC example still applies though: the application is busy looping and consuming more power than necessary.
diff --git a/docs/modules/ROOT/pages/stm32.adoc b/docs/modules/ROOT/pages/stm32.adoc
index 8ed9ab04b..7bfc0592b 100644
--- a/docs/modules/ROOT/pages/stm32.adoc
+++ b/docs/modules/ROOT/pages/stm32.adoc
@@ -4,9 +4,9 @@ The link:https://github.com/embassy-rs/embassy/tree/master/embassy-stm32[Embassy
== The infinite variant problem
-STM32 microcontrollers comes in many families and flavors, and supporting all of them is a big undertaking. Embassy has taken advantage of the fact
+STM32 microcontrollers come in many families, and flavors and supporting all of them is a big undertaking. Embassy has taken advantage of the fact
that the STM32 peripheral versions are shared across chip families. Instead of re-implementing the SPI
-peripheral for every STM32 chip family, embassy have a single SPI implementation that depends on
+peripheral for every STM32 chip family, embassy has a single SPI implementation that depends on
code-generated register types that are identical for STM32 families with the same version of a given peripheral.
=== The metapac
diff --git a/embassy-boot/boot/Cargo.toml b/embassy-boot/boot/Cargo.toml
index 54c67a375..0b0c77b1e 100644
--- a/embassy-boot/boot/Cargo.toml
+++ b/embassy-boot/boot/Cargo.toml
@@ -1,26 +1,50 @@
[package]
edition = "2021"
name = "embassy-boot"
-version = "0.1.0"
-description = "Bootloader using Embassy"
+version = "0.1.1"
+description = "A lightweight bootloader supporting firmware updates in a power-fail-safe way, with trial boots and rollbacks."
license = "MIT OR Apache-2.0"
+repository = "https://github.com/embassy-rs/embassy"
+categories = [
+ "embedded",
+ "no-std",
+ "asynchronous",
+]
[package.metadata.embassy_docs]
src_base = "https://github.com/embassy-rs/embassy/blob/embassy-boot-v$VERSION/embassy-boot/boot/src/"
src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-boot/boot/src/"
target = "thumbv7em-none-eabi"
+features = ["defmt"]
+
+[package.metadata.docs.rs]
+features = ["defmt"]
[lib]
[dependencies]
defmt = { version = "0.3", optional = true }
log = { version = "0.4", optional = true }
+ed25519-dalek = { version = "1.0.1", default_features = false, features = ["u32_backend"], optional = true }
embassy-sync = { version = "0.1.0", path = "../../embassy-sync" }
embedded-storage = "0.3.0"
embedded-storage-async = "0.3.0"
+salty = { git = "https://github.com/ycrypto/salty.git", rev = "a9f17911a5024698406b75c0fac56ab5ccf6a8c7", optional = true }
+signature = { version = "1.6.4", default-features = false }
[dev-dependencies]
log = "0.4"
env_logger = "0.9"
-rand = "0.8"
+rand = "0.7" # ed25519-dalek v1.0.1 depends on this exact version
futures = { version = "0.3", features = ["executor"] }
+
+[dev-dependencies.ed25519-dalek]
+default_features = false
+features = ["rand", "std", "u32_backend"]
+
+[features]
+ed25519-dalek = ["dep:ed25519-dalek", "_verify"]
+ed25519-salty = ["dep:salty", "_verify"]
+
+#Internal features
+_verify = []
\ No newline at end of file
diff --git a/embassy-boot/README.md b/embassy-boot/boot/README.md
similarity index 100%
rename from embassy-boot/README.md
rename to embassy-boot/boot/README.md
diff --git a/embassy-boot/boot/src/lib.rs b/embassy-boot/boot/src/lib.rs
index 8286601ec..be254e9d7 100644
--- a/embassy-boot/boot/src/lib.rs
+++ b/embassy-boot/boot/src/lib.rs
@@ -1,7 +1,7 @@
#![feature(type_alias_impl_trait)]
#![no_std]
#![warn(missing_docs)]
-#![doc = include_str!("../../README.md")]
+#![doc = include_str!("../README.md")]
mod fmt;
use embedded_storage::nor_flash::{ErrorType, NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash};
@@ -52,6 +52,16 @@ pub enum BootError {
BadMagic,
}
+#[cfg(feature = "defmt")]
+impl defmt::Format for BootError {
+ fn format(&self, fmt: defmt::Formatter) {
+ match self {
+ BootError::Flash(_) => defmt::write!(fmt, "BootError::Flash(_)"),
+ BootError::BadMagic => defmt::write!(fmt, "BootError::BadMagic"),
+ }
+ }
+}
+
impl From for BootError
where
E: NorFlashError,
@@ -150,7 +160,7 @@ impl BootLoader {
/// +-----------+------------+--------+--------+--------+--------+
/// | Active | 0 | 1 | 2 | 3 | - |
/// | DFU | 0 | 3 | 2 | 1 | X |
- /// +-----------+-------+--------+--------+--------+--------+
+ /// +-----------+------------+--------+--------+--------+--------+
///
/// The algorithm starts by copying 'backwards', and after the first step, the layout is
/// as follows:
@@ -557,6 +567,33 @@ where
self.state
}
}
+/// Errors returned by FirmwareUpdater
+#[derive(Debug)]
+pub enum FirmwareUpdaterError {
+ /// Error from flash.
+ Flash(NorFlashErrorKind),
+ /// Signature errors.
+ Signature(signature::Error),
+}
+
+#[cfg(feature = "defmt")]
+impl defmt::Format for FirmwareUpdaterError {
+ fn format(&self, fmt: defmt::Formatter) {
+ match self {
+ FirmwareUpdaterError::Flash(_) => defmt::write!(fmt, "FirmwareUpdaterError::Flash(_)"),
+ FirmwareUpdaterError::Signature(_) => defmt::write!(fmt, "FirmwareUpdaterError::Signature(_)"),
+ }
+ }
+}
+
+impl From for FirmwareUpdaterError
+where
+ E: NorFlashError,
+{
+ fn from(error: E) -> Self {
+ FirmwareUpdaterError::Flash(error.kind())
+ }
+}
/// FirmwareUpdater is an application API for interacting with the BootLoader without the ability to
/// 'mess up' the internal bootloader state
@@ -609,7 +646,11 @@ impl FirmwareUpdater {
/// This is useful to check if the bootloader has just done a swap, in order
/// to do verifications and self-tests of the new image before calling
/// `mark_booted`.
- pub async fn get_state(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result {
+ pub async fn get_state(
+ &mut self,
+ flash: &mut F,
+ aligned: &mut [u8],
+ ) -> Result {
flash.read(self.state.from as u32, aligned).await?;
if !aligned.iter().any(|&b| b != SWAP_MAGIC) {
@@ -619,12 +660,126 @@ impl FirmwareUpdater {
}
}
+ /// Verify the DFU given a public key. If there is an error then DO NOT
+ /// proceed with updating the firmware as it must be signed with a
+ /// corresponding private key (otherwise it could be malicious firmware).
+ ///
+ /// Mark to trigger firmware swap on next boot if verify suceeds.
+ ///
+ /// If the "ed25519-salty" feature is set (or another similar feature) then the signature is expected to have
+ /// been generated from a SHA-512 digest of the firmware bytes.
+ ///
+ /// If no signature feature is set then this method will always return a
+ /// signature error.
+ ///
+ /// # Safety
+ ///
+ /// The `_aligned` buffer must have a size of F::WRITE_SIZE, and follow the alignment rules for the flash being read from
+ /// and written to.
+ #[cfg(feature = "_verify")]
+ pub async fn verify_and_mark_updated(
+ &mut self,
+ _flash: &mut F,
+ _public_key: &[u8],
+ _signature: &[u8],
+ _update_len: usize,
+ _aligned: &mut [u8],
+ ) -> Result<(), FirmwareUpdaterError> {
+ let _end = self.dfu.from + _update_len;
+ let _read_size = _aligned.len();
+
+ assert_eq!(_aligned.len(), F::WRITE_SIZE);
+ assert!(_end <= self.dfu.to);
+
+ #[cfg(feature = "ed25519-dalek")]
+ {
+ use ed25519_dalek::{Digest, PublicKey, Sha512, Signature, SignatureError, Verifier};
+
+ let into_signature_error = |e: SignatureError| FirmwareUpdaterError::Signature(e.into());
+
+ let public_key = PublicKey::from_bytes(_public_key).map_err(into_signature_error)?;
+ let signature = Signature::from_bytes(_signature).map_err(into_signature_error)?;
+
+ let mut digest = Sha512::new();
+
+ let mut offset = self.dfu.from;
+ let last_offset = _end / _read_size * _read_size;
+
+ while offset < last_offset {
+ _flash.read(offset as u32, _aligned).await?;
+ digest.update(&_aligned);
+ offset += _read_size;
+ }
+
+ let remaining = _end % _read_size;
+
+ if remaining > 0 {
+ _flash.read(last_offset as u32, _aligned).await?;
+ digest.update(&_aligned[0..remaining]);
+ }
+
+ public_key
+ .verify(&digest.finalize(), &signature)
+ .map_err(into_signature_error)?
+ }
+ #[cfg(feature = "ed25519-salty")]
+ {
+ use salty::constants::{PUBLICKEY_SERIALIZED_LENGTH, SIGNATURE_SERIALIZED_LENGTH};
+ use salty::{PublicKey, Sha512, Signature};
+
+ fn into_signature_error(_: E) -> FirmwareUpdaterError {
+ FirmwareUpdaterError::Signature(signature::Error::default())
+ }
+
+ let public_key: [u8; PUBLICKEY_SERIALIZED_LENGTH] = _public_key.try_into().map_err(into_signature_error)?;
+ let public_key = PublicKey::try_from(&public_key).map_err(into_signature_error)?;
+ let signature: [u8; SIGNATURE_SERIALIZED_LENGTH] = _signature.try_into().map_err(into_signature_error)?;
+ let signature = Signature::try_from(&signature).map_err(into_signature_error)?;
+
+ let mut digest = Sha512::new();
+
+ let mut offset = self.dfu.from;
+ let last_offset = _end / _read_size * _read_size;
+
+ while offset < last_offset {
+ _flash.read(offset as u32, _aligned).await?;
+ digest.update(&_aligned);
+ offset += _read_size;
+ }
+
+ let remaining = _end % _read_size;
+
+ if remaining > 0 {
+ _flash.read(last_offset as u32, _aligned).await?;
+ digest.update(&_aligned[0..remaining]);
+ }
+
+ let message = digest.finalize();
+ let r = public_key.verify(&message, &signature);
+ trace!(
+ "Verifying with public key {}, signature {} and message {} yields ok: {}",
+ public_key.to_bytes(),
+ signature.to_bytes(),
+ message,
+ r.is_ok()
+ );
+ r.map_err(into_signature_error)?
+ }
+
+ self.set_magic(_aligned, SWAP_MAGIC, _flash).await
+ }
+
/// Mark to trigger firmware swap on next boot.
///
/// # Safety
///
/// The `aligned` buffer must have a size of F::WRITE_SIZE, and follow the alignment rules for the flash being written to.
- pub async fn mark_updated(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<(), F::Error> {
+ #[cfg(not(feature = "_verify"))]
+ pub async fn mark_updated(
+ &mut self,
+ flash: &mut F,
+ aligned: &mut [u8],
+ ) -> Result<(), FirmwareUpdaterError> {
assert_eq!(aligned.len(), F::WRITE_SIZE);
self.set_magic(aligned, SWAP_MAGIC, flash).await
}
@@ -634,7 +789,11 @@ impl FirmwareUpdater {
/// # Safety
///
/// The `aligned` buffer must have a size of F::WRITE_SIZE, and follow the alignment rules for the flash being written to.
- pub async fn mark_booted(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<(), F::Error> {
+ pub async fn mark_booted(
+ &mut self,
+ flash: &mut F,
+ aligned: &mut [u8],
+ ) -> Result<(), FirmwareUpdaterError> {
assert_eq!(aligned.len(), F::WRITE_SIZE);
self.set_magic(aligned, BOOT_MAGIC, flash).await
}
@@ -644,7 +803,7 @@ impl FirmwareUpdater {
aligned: &mut [u8],
magic: u8,
flash: &mut F,
- ) -> Result<(), F::Error> {
+ ) -> Result<(), FirmwareUpdaterError> {
flash.read(self.state.from as u32, aligned).await?;
if aligned.iter().any(|&b| b != magic) {
@@ -672,7 +831,7 @@ impl FirmwareUpdater {
data: &[u8],
flash: &mut F,
block_size: usize,
- ) -> Result<(), F::Error> {
+ ) -> Result<(), FirmwareUpdaterError> {
assert!(data.len() >= F::ERASE_SIZE);
flash
@@ -700,7 +859,10 @@ impl FirmwareUpdater {
///
/// Using this instead of `write_firmware` allows for an optimized API in
/// exchange for added complexity.
- pub async fn prepare_update(&mut self, flash: &mut F) -> Result {
+ pub async fn prepare_update(
+ &mut self,
+ flash: &mut F,
+ ) -> Result {
flash.erase((self.dfu.from) as u32, (self.dfu.to) as u32).await?;
trace!("Erased from {} to {}", self.dfu.from, self.dfu.to);
@@ -717,7 +879,11 @@ impl FirmwareUpdater {
/// This is useful to check if the bootloader has just done a swap, in order
/// to do verifications and self-tests of the new image before calling
/// `mark_booted`.
- pub fn get_state_blocking(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result {
+ pub fn get_state_blocking(
+ &mut self,
+ flash: &mut F,
+ aligned: &mut [u8],
+ ) -> Result {
flash.read(self.state.from as u32, aligned)?;
if !aligned.iter().any(|&b| b != SWAP_MAGIC) {
@@ -727,12 +893,126 @@ impl FirmwareUpdater {
}
}
+ /// Verify the DFU given a public key. If there is an error then DO NOT
+ /// proceed with updating the firmware as it must be signed with a
+ /// corresponding private key (otherwise it could be malicious firmware).
+ ///
+ /// Mark to trigger firmware swap on next boot if verify suceeds.
+ ///
+ /// If the "ed25519-salty" feature is set (or another similar feature) then the signature is expected to have
+ /// been generated from a SHA-512 digest of the firmware bytes.
+ ///
+ /// If no signature feature is set then this method will always return a
+ /// signature error.
+ ///
+ /// # Safety
+ ///
+ /// The `_aligned` buffer must have a size of F::WRITE_SIZE, and follow the alignment rules for the flash being read from
+ /// and written to.
+ #[cfg(feature = "_verify")]
+ pub fn verify_and_mark_updated_blocking(
+ &mut self,
+ _flash: &mut F,
+ _public_key: &[u8],
+ _signature: &[u8],
+ _update_len: usize,
+ _aligned: &mut [u8],
+ ) -> Result<(), FirmwareUpdaterError> {
+ let _end = self.dfu.from + _update_len;
+ let _read_size = _aligned.len();
+
+ assert_eq!(_aligned.len(), F::WRITE_SIZE);
+ assert!(_end <= self.dfu.to);
+
+ #[cfg(feature = "ed25519-dalek")]
+ {
+ use ed25519_dalek::{Digest, PublicKey, Sha512, Signature, SignatureError, Verifier};
+
+ let into_signature_error = |e: SignatureError| FirmwareUpdaterError::Signature(e.into());
+
+ let public_key = PublicKey::from_bytes(_public_key).map_err(into_signature_error)?;
+ let signature = Signature::from_bytes(_signature).map_err(into_signature_error)?;
+
+ let mut digest = Sha512::new();
+
+ let mut offset = self.dfu.from;
+ let last_offset = _end / _read_size * _read_size;
+
+ while offset < last_offset {
+ _flash.read(offset as u32, _aligned)?;
+ digest.update(&_aligned);
+ offset += _read_size;
+ }
+
+ let remaining = _end % _read_size;
+
+ if remaining > 0 {
+ _flash.read(last_offset as u32, _aligned)?;
+ digest.update(&_aligned[0..remaining]);
+ }
+
+ public_key
+ .verify(&digest.finalize(), &signature)
+ .map_err(into_signature_error)?
+ }
+ #[cfg(feature = "ed25519-salty")]
+ {
+ use salty::constants::{PUBLICKEY_SERIALIZED_LENGTH, SIGNATURE_SERIALIZED_LENGTH};
+ use salty::{PublicKey, Sha512, Signature};
+
+ fn into_signature_error(_: E) -> FirmwareUpdaterError {
+ FirmwareUpdaterError::Signature(signature::Error::default())
+ }
+
+ let public_key: [u8; PUBLICKEY_SERIALIZED_LENGTH] = _public_key.try_into().map_err(into_signature_error)?;
+ let public_key = PublicKey::try_from(&public_key).map_err(into_signature_error)?;
+ let signature: [u8; SIGNATURE_SERIALIZED_LENGTH] = _signature.try_into().map_err(into_signature_error)?;
+ let signature = Signature::try_from(&signature).map_err(into_signature_error)?;
+
+ let mut digest = Sha512::new();
+
+ let mut offset = self.dfu.from;
+ let last_offset = _end / _read_size * _read_size;
+
+ while offset < last_offset {
+ _flash.read(offset as u32, _aligned)?;
+ digest.update(&_aligned);
+ offset += _read_size;
+ }
+
+ let remaining = _end % _read_size;
+
+ if remaining > 0 {
+ _flash.read(last_offset as u32, _aligned)?;
+ digest.update(&_aligned[0..remaining]);
+ }
+
+ let message = digest.finalize();
+ let r = public_key.verify(&message, &signature);
+ trace!(
+ "Verifying with public key {}, signature {} and message {} yields ok: {}",
+ public_key.to_bytes(),
+ signature.to_bytes(),
+ message,
+ r.is_ok()
+ );
+ r.map_err(into_signature_error)?
+ }
+
+ self.set_magic_blocking(_aligned, SWAP_MAGIC, _flash)
+ }
+
/// Mark to trigger firmware swap on next boot.
///
/// # Safety
///
/// The `aligned` buffer must have a size of F::WRITE_SIZE, and follow the alignment rules for the flash being written to.
- pub fn mark_updated_blocking(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<(), F::Error> {
+ #[cfg(not(feature = "_verify"))]
+ pub fn mark_updated_blocking(
+ &mut self,
+ flash: &mut F,
+ aligned: &mut [u8],
+ ) -> Result<(), FirmwareUpdaterError> {
assert_eq!(aligned.len(), F::WRITE_SIZE);
self.set_magic_blocking(aligned, SWAP_MAGIC, flash)
}
@@ -742,7 +1022,11 @@ impl FirmwareUpdater {
/// # Safety
///
/// The `aligned` buffer must have a size of F::WRITE_SIZE, and follow the alignment rules for the flash being written to.
- pub fn mark_booted_blocking(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<(), F::Error> {
+ pub fn mark_booted_blocking(
+ &mut self,
+ flash: &mut F,
+ aligned: &mut [u8],
+ ) -> Result<(), FirmwareUpdaterError> {
assert_eq!(aligned.len(), F::WRITE_SIZE);
self.set_magic_blocking(aligned, BOOT_MAGIC, flash)
}
@@ -752,7 +1036,7 @@ impl FirmwareUpdater {
aligned: &mut [u8],
magic: u8,
flash: &mut F,
- ) -> Result<(), F::Error> {
+ ) -> Result<(), FirmwareUpdaterError> {
flash.read(self.state.from as u32, aligned)?;
if aligned.iter().any(|&b| b != magic) {
@@ -780,7 +1064,7 @@ impl FirmwareUpdater {
data: &[u8],
flash: &mut F,
block_size: usize,
- ) -> Result<(), F::Error> {
+ ) -> Result<(), FirmwareUpdaterError> {
assert!(data.len() >= F::ERASE_SIZE);
flash.erase(
@@ -804,7 +1088,10 @@ impl FirmwareUpdater {
///
/// Using this instead of `write_firmware_blocking` allows for an optimized
/// API in exchange for added complexity.
- pub fn prepare_update_blocking(&mut self, flash: &mut F) -> Result {
+ pub fn prepare_update_blocking(
+ &mut self,
+ flash: &mut F,
+ ) -> Result {
flash.erase((self.dfu.from) as u32, (self.dfu.to) as u32)?;
trace!("Erased from {} to {}", self.dfu.from, self.dfu.to);
@@ -953,6 +1240,7 @@ mod tests {
}
#[test]
+ #[cfg(not(feature = "_verify"))]
fn test_swap_state() {
const STATE: Partition = Partition::new(0, 4096);
const ACTIVE: Partition = Partition::new(4096, 61440);
@@ -1022,6 +1310,7 @@ mod tests {
}
#[test]
+ #[cfg(not(feature = "_verify"))]
fn test_separate_flash_active_page_biggest() {
const STATE: Partition = Partition::new(2048, 4096);
const ACTIVE: Partition = Partition::new(4096, 16384);
@@ -1074,6 +1363,7 @@ mod tests {
}
#[test]
+ #[cfg(not(feature = "_verify"))]
fn test_separate_flash_dfu_page_biggest() {
const STATE: Partition = Partition::new(2048, 4096);
const ACTIVE: Partition = Partition::new(4096, 16384);
@@ -1133,6 +1423,55 @@ mod tests {
assert_partitions(ACTIVE, DFU, STATE, 4096, 4);
}
+ #[test]
+ #[cfg(feature = "_verify")]
+ fn test_verify() {
+ // The following key setup is based on:
+ // https://docs.rs/ed25519-dalek/latest/ed25519_dalek/#example
+
+ use ed25519_dalek::Keypair;
+ use rand::rngs::OsRng;
+
+ let mut csprng = OsRng {};
+ let keypair: Keypair = Keypair::generate(&mut csprng);
+
+ use ed25519_dalek::{Digest, Sha512, Signature, Signer};
+ let firmware: &[u8] = b"This are bytes that would otherwise be firmware bytes for DFU.";
+ let mut digest = Sha512::new();
+ digest.update(&firmware);
+ let message = digest.finalize();
+ let signature: Signature = keypair.sign(&message);
+
+ use ed25519_dalek::PublicKey;
+ let public_key: PublicKey = keypair.public;
+
+ // Setup flash
+
+ const STATE: Partition = Partition::new(0, 4096);
+ const DFU: Partition = Partition::new(4096, 8192);
+ let mut flash = MemFlash::<8192, 4096, 4>([0xff; 8192]);
+
+ let firmware_len = firmware.len();
+
+ let mut write_buf = [0; 4096];
+ write_buf[0..firmware_len].copy_from_slice(firmware);
+ NorFlash::write(&mut flash, DFU.from as u32, &write_buf).unwrap();
+
+ // On with the test
+
+ let mut updater = FirmwareUpdater::new(DFU, STATE);
+
+ let mut aligned = [0; 4];
+
+ assert!(block_on(updater.verify_and_mark_updated(
+ &mut flash,
+ &public_key.to_bytes(),
+ &signature.to_bytes(),
+ firmware_len,
+ &mut aligned,
+ ))
+ .is_ok());
+ }
struct MemFlash([u8; SIZE]);
impl NorFlash
@@ -1171,7 +1510,7 @@ mod tests {
impl ReadNorFlash
for MemFlash
{
- const READ_SIZE: usize = 4;
+ const READ_SIZE: usize = 1;
fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
let len = buf.len();
@@ -1194,7 +1533,7 @@ mod tests {
impl AsyncReadNorFlash
for MemFlash
{
- const READ_SIZE: usize = 4;
+ const READ_SIZE: usize = 1;
type ReadFuture<'a> = impl Future