What changed, and why it matters
This commit refactors how the BitBox02 hardware wallet handles U2F (Universal 2nd Factor) security-key workflows. It replaces an older polling-style task system with a new async executor and swaps several `static mut` global variables for safer building blocks from a vendored Rust crate called `grounded`. The change is mostly a code-quality and safety improvement: it removes deprecated `static mut` references and makes the U2F unlock/confirm workflows run as proper async tasks. There is no direct evidence in the commit message or diff that this fixes an active security vulnerability, but it reduces the risk of memory-unsafety bugs in a security-sensitive code path.
Treat as a routine hardening/refactoring change. Review the new `grounded` crate usage for correct initialization and single-threaded access assumptions, especially around `BITBOX02_HAL.get().as_mut().unwrap()` and the `complete_*` token checks. Ensure the `critical-section` implementation on the target is sound. No urgent patch action is indicated by the supplied materials.
Security signals we found
Replaces `static mut` global state with `GroundedCell`/`MaybeUninit` abstractions, reducing static-mut-aliasing and use-after-free risks
Moves U2F workflow polling into a single async executor, removing manual `spin()` polling and reducing opportunities for reentrancy/state corruption
Adds explicit `unsafe` safety contracts to C API functions requiring single-threaded, non-reentrant callers
Vendors a new dependency (`grounded`) and its transitive dependency `portable-atomic` with `critical-section` feature, increasing supply-chain/audit surface
No CVE, advisory, or vendor security disclosure is present in the supplied materials
Evidence from the diff
The patch vendors the grounded crate (0.2.1) and uses its GroundedCell and ConstInit abstractions to replace static mut state in src/rust/bitbox02-rust/src/workflow/u2f_c_api.rs. U2F unlock and confirm workflows are now spawned as dyn Future tasks via a new main_loop::spawn helper running on the existing bitbox_executor::Executor, instead of being manually polled from workflow_spin(). The C API entry points (rust_workflow_spawn_unlock, rust_workflow_spawn_confirm, rust_workflow_*_poll, rust_workflow_abort_current) remain but now operate on token-tracked GroundedCell<TaskState<_>> state. Stubs are provided for C unit tests and the graphical simulator. The app-u2f feature gate is split so the real implementation is only compiled into production firmware.
Changed components
src/rust/bitbox02-rust/src/workflow/u2f_c_api.rssrc/rust/bitbox02-rust/src/main_loop.rssrc/rust/bitbox02-rust/src/workflow.rssrc/rust/bitbox02-rust/src/hal/bitbox02.rsexternal/vendor/grounded/*src/rust/bitbox02-rust/Cargo.tomlsrc/rust/Cargo.locktest/simulator-graphical/Cargo.locktest/simulator-graphical-bb03/Cargo.lockInspect captured patch +1193 / −81
diff --git a/external/vendor/grounded/.cargo-checksum.json b/external/vendor/grounded/.cargo-checksum.json
new file mode 100644
index 0000000..9514813
--- /dev/null
+++ b/external/vendor/grounded/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{".cargo_vcs_info.json":"3e97f65005f1bc5bb8add659d6ecd87b2eeba24f16acedf05cc53bdde442aa5c",".github/workflows/clippy.yml":"7755bb25b230729d7d73d0b43cdda00d22ece8ef91598e032aff36fc1c662d02",".github/workflows/format.yml":"b67f80f8673574dd73adf0a787a5bf72417491a4bb61d478c4b8852506f6cc70",".github/workflows/rust.yml":"ed9dd848f1d1aaf80659df3f6c98d5caa9354bbb3ec98f7d0063ae511b1d6f14","Cargo.lock":"bfa666bb630557c36b31a97c42245db54b452241b5ad182f8bb83b9054732af8","Cargo.toml":"abbbf68fa5544490b40690978a7a5a556658b493d18d0001fe2119b443078db2","Cargo.toml.orig":"dfa5bd3e4aebebdbc216140f1c564e3cfb1675e8cec338b3321f198907259d5d","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"177540cad091a40e8071db310bc3b6115c4e329a92a234609b60c154b008a888","README.md":"34e8e5fa08d2735ad5dda6084c09978c3978e5886db0cdb370d4767080c39abb","src/alloc_single.rs":"40de300a511817397517ef61e1a7efcea5537756d032c1c1621dac9f44d3a1aa","src/const_init.rs":"ee73477ba827e16f67bd7e581da438eb64145ad907919e4f4508de7a27904800","src/lib.rs":"7cc59f73fe1f3aeb901f6f64fee6d6e1ff05f6c371f0ee3af3c1665bf59f96b9","src/uninit.rs":"a4a64d49c106264fdaeffaccba5eb10c97b81b7fa583281a3c71f732661d452f"},"package":"5a7c71ebd5d467418b46639b622912cd0338ce59766bd19130bffcbf9ac6df2c"}
\ No newline at end of file
diff --git a/external/vendor/grounded/.cargo_vcs_info.json b/external/vendor/grounded/.cargo_vcs_info.json
new file mode 100644
index 0000000..1885a34
--- /dev/null
+++ b/external/vendor/grounded/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "784db2d8b7995981edf0d62c872bcbb3830a7687"
+ },
+ "path_in_vcs": ""
+}
\ No newline at end of file
diff --git a/external/vendor/grounded/.github/workflows/clippy.yml b/external/vendor/grounded/.github/workflows/clippy.yml
new file mode 100644
index 0000000..942e19e
--- /dev/null
+++ b/external/vendor/grounded/.github/workflows/clippy.yml
@@ -0,0 +1,15 @@
+# SPDX-FileCopyrightText: 2024 Jonathan 'theJPster' Pallant <github@thejpster.org.uk>
+#
+# SPDX-License-Identifier: MIT OR Apache-2.0
+
+name: Clippy
+
+on: [push, pull_request]
+
+jobs:
+ cargo-clippy:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: Run Clippy
+ run: cargo clippy
diff --git a/external/vendor/grounded/.github/workflows/format.yml b/external/vendor/grounded/.github/workflows/format.yml
new file mode 100644
index 0000000..4f1be18
--- /dev/null
+++ b/external/vendor/grounded/.github/workflows/format.yml
@@ -0,0 +1,15 @@
+# SPDX-FileCopyrightText: 2024 Jonathan 'theJPster' Pallant <github@thejpster.org.uk>
+#
+# SPDX-License-Identifier: MIT OR Apache-2.0
+
+name: Format
+
+on: [push, pull_request]
+
+jobs:
+ cargo-fmt:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: rustup component add rustfmt
+ - run: cargo fmt -- --check
diff --git a/external/vendor/grounded/.github/workflows/rust.yml b/external/vendor/grounded/.github/workflows/rust.yml
new file mode 100644
index 0000000..51c12c7
--- /dev/null
+++ b/external/vendor/grounded/.github/workflows/rust.yml
@@ -0,0 +1,44 @@
+# SPDX-FileCopyrightText: 2024 Jonathan 'theJPster' Pallant <github@thejpster.org.uk>
+#
+# SPDX-License-Identifier: MIT OR Apache-2.0
+
+name: Build and Test
+
+on: [push, pull_request]
+
+jobs:
+ cargo-build-native:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: |
+ cargo build
+ cargo build --all-features
+ cargo-build-cross:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ target: [thumbv6m-none-eabi, riscv32i-unknown-none-elf, thumbv7m-none-eabi, thumbv7em-none-eabi, thumbv8m.base-none-eabi, thumbv8m.main-none-eabi, riscv32imac-unknown-none-elf]
+ steps:
+ - uses: actions/checkout@v4
+ - run: rustup target add ${{ matrix.target }}
+ - run: |
+ cargo build --target=${{ matrix.target }}
+ cargo build --target=${{ matrix.target }} --features=cas,critical-section
+ cargo-build-cross-with-cas:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ target: [thumbv7m-none-eabi, thumbv7em-none-eabi, thumbv8m.base-none-eabi, thumbv8m.main-none-eabi, riscv32imac-unknown-none-elf]
+ steps:
+ - uses: actions/checkout@v4
+ - run: rustup target add ${{ matrix.target }}
+ - run: |
+ cargo build --target=${{ matrix.target }} --features=cas
+ cargo-test-native:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: |
+ cargo test
+ cargo test --all-features
diff --git a/external/vendor/grounded/Cargo.lock b/external/vendor/grounded/Cargo.lock
new file mode 100644
index 0000000..62b5732
--- /dev/null
+++ b/external/vendor/grounded/Cargo.lock
@@ -0,0 +1,25 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "critical-section"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7059fff8937831a9ae6f0fe4d658ffabf58f2ca96aa9dec1c889f936f705f216"
+
+[[package]]
+name = "grounded"
+version = "0.2.1"
+dependencies = [
+ "portable-atomic",
+]
+
+[[package]]
+name = "portable-atomic"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7170ef9988bc169ba16dd36a7fa041e5c4cbeb6a35b76d4c03daded371eae7c0"
+dependencies = [
+ "critical-section",
+]
diff --git a/external/vendor/grounded/Cargo.toml b/external/vendor/grounded/Cargo.toml
new file mode 100644
index 0000000..f09cd30
--- /dev/null
+++ b/external/vendor/grounded/Cargo.toml
@@ -0,0 +1,47 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+name = "grounded"
+version = "0.2.1"
+authors = ["James Munns <james@onevariable.com>"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "A toolkit for managing unsafe statics"
+documentation = "https://docs.rs/grounded/"
+readme = "README.md"
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/jamesmunns/grounded"
+
+[package.metadata.docs.rs]
+features = ["cas"]
+rustdoc-args = [
+ "--cfg",
+ "doc_cfg",
+]
+
+[features]
+cas = ["portable-atomic/require-cas"]
+critical-section = ["portable-atomic/critical-section"]
+default = []
+
+[lib]
+name = "grounded"
+path = "src/lib.rs"
+
+[dependencies.portable-atomic]
+version = "1.3"
+default-features = false
diff --git a/external/vendor/grounded/Cargo.toml.orig b/external/vendor/grounded/Cargo.toml.orig
new file mode 100644
index 0000000..c68f5d5
--- /dev/null
+++ b/external/vendor/grounded/Cargo.toml.orig
@@ -0,0 +1,25 @@
+[package]
+name = "grounded"
+version = "0.2.1"
+authors = ["James Munns <james@onevariable.com>"]
+edition = "2021"
+readme = "README.md"
+repository = "https://github.com/jamesmunns/grounded"
+description = "A toolkit for managing unsafe statics"
+license = "MIT OR Apache-2.0"
+documentation = "https://docs.rs/grounded/"
+
+[dependencies.portable-atomic]
+version = "1.3"
+default-features = false
+
+[features]
+default = []
+# components that require compare-and-swap operations
+cas = ["portable-atomic/require-cas"]
+# Allow for use on non-atomic systems by use of critical-sections
+critical-section = ["portable-atomic/critical-section"]
+
+[package.metadata.docs.rs]
+features = ["cas"]
+rustdoc-args = ["--cfg", "doc_cfg"]
diff --git a/external/vendor/grounded/LICENSE-APACHE b/external/vendor/grounded/LICENSE-APACHE
new file mode 100644
index 0000000..16fe87b
--- /dev/null
+++ b/external/vendor/grounded/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/external/vendor/grounded/LICENSE-MIT b/external/vendor/grounded/LICENSE-MIT
new file mode 100644
index 0000000..ee10cca
--- /dev/null
+++ b/external/vendor/grounded/LICENSE-MIT
@@ -0,0 +1,25 @@
+Copyright (c) 2019 Anthony James Munns
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/external/vendor/grounded/README.md b/external/vendor/grounded/README.md
new file mode 100644
index 0000000..a63d92f
--- /dev/null
+++ b/external/vendor/grounded/README.md
@@ -0,0 +1,23 @@
+# Grounded
+
+Building blocks for handling potentially unsafe statics.
+
+This crate aims to provide useful and sound components that serve as building blocks for `static` datatypes that are common, and often necessary, in embedded systems.
+
+In some cases, fully safe methods and types will be provided. In other cases, "harm reduction" tools will be provided to make it easier to build sound abstractions and avoid undefined behavior.
+
+## License
+
+Licensed under either of
+
+- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or
+ <http://www.apache.org/licenses/LICENSE-2.0>)
+- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
+
+at your option.
+
+### Contribution
+
+Unless you explicitly state otherwise, any contribution intentionally submitted
+for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
+dual licensed as above, without any additional terms or conditions.
diff --git a/external/vendor/grounded/src/alloc_single.rs b/external/vendor/grounded/src/alloc_single.rs
new file mode 100644
index 0000000..a9c690b
--- /dev/null
+++ b/external/vendor/grounded/src/alloc_single.rs
@@ -0,0 +1,166 @@
+//! Utilities for allocating a single item, using a box-like smart pointer
+
+use core::{
+ ops::{Deref, DerefMut},
+ sync::atomic::Ordering,
+};
+use portable_atomic::AtomicBool;
+
+use crate::{const_init::ConstInit, uninit::GroundedCell};
+
+/// AllocSingle is our one-element allocator pool
+///
+/// If your type implements [ConstInit], consider using
+/// [AllocSingle::alloc_const_val] instead of [AllocSingle::alloc]
+/// to avoid unnecessary stack usage.
+///
+/// This does require use of CAS atomics. You must enable the `cas`
+/// feature, and if your target does not have native atomic CAS, you
+/// must also enable the `critical-section` feature.
+///
+/// ```rust
+/// use grounded::alloc_single::AllocSingle;
+///
+/// static SINGLE: AllocSingle<[u8; 256]> = AllocSingle::new();
+///
+/// // alloc a single item
+/// let mut s1 = SINGLE.alloc([4; 256]).unwrap();
+/// s1.iter().for_each(|b| assert_eq!(*b, 4));
+///
+/// // we can't alloc while `s1` is still live
+/// assert!(SINGLE.alloc([5; 256]).is_none());
+///
+/// // now drop it
+/// drop(s1);
+///
+/// // and we can alloc again
+/// let mut s2 = SINGLE.alloc([7; 256]).unwrap();
+/// s2.iter().for_each(|b| assert_eq!(*b, 7));
+/// ```
+pub struct AllocSingle<T> {
+ taken: AtomicBool,
+ storage: GroundedCell<T>,
+}
+
+impl<T> AllocSingle<T> {
+ /// Create a new, uninitalized, single-element allocation pool
+ pub const fn new() -> Self {
+ Self {
+ taken: AtomicBool::new(false),
+ storage: GroundedCell::uninit(),
+ }
+ }
+
+ /// Attempts to allocate a single item. Returns None and
+ /// discards `t` if an allocation is already live.
+ #[inline]
+ pub fn alloc(&self, t: T) -> Option<SingleBox<'_, T>> {
+ // Set taken, and if it was already taken before, we can't
+ // allocate
+ if self.taken.swap(true, Ordering::AcqRel) {
+ // already taken
+ return None;
+ }
+ let new = SingleBox { single: self };
+ // Initialize by moving t into the storage
+ unsafe {
+ new.as_ptr().write(t);
+ }
+ Some(new)
+ }
+}
+
+impl<T: ConstInit> AllocSingle<T> {
+ /// Attempts to allocate a single item, using `ConstInit::VAL` as
+ /// the initializer. Returns None if the item is already allocated
+ pub fn alloc_const_val(&self) -> Option<SingleBox<'_, T>> {
+ // Set taken, and if it was already taken before, we can't
+ // allocate
+ if self.taken.swap(true, Ordering::AcqRel) {
+ // already taken
+ return None;
+ }
+ let new = SingleBox { single: self };
+ // Initialize by writing t into the storage
+ unsafe {
+ new.as_ptr().write(T::VAL);
+ }
+ Some(new)
+ }
+}
+
+pub struct SingleBox<'a, T> {
+ single: &'a AllocSingle<T>,
+}
+
+impl<'a, T> SingleBox<'a, T> {
+ fn as_ptr(&self) -> *mut T {
+ self.single.storage.get()
+ }
+}
+
+impl<'a, T> Drop for SingleBox<'a, T> {
+ fn drop(&mut self) {
+ // When we drop the SingleBox, mark the AllocSingle as available again
+ unsafe { self.as_ptr().drop_in_place() }
+ self.single.taken.store(false, Ordering::Release);
+ }
+}
+
+impl<'a, T> Deref for SingleBox<'a, T> {
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ unsafe { &*self.as_ptr() }
+ }
+}
+
+impl<'a, T> DerefMut for SingleBox<'a, T> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ unsafe { &mut *self.as_ptr() }
+ }
+}
+
+#[cfg(test)]
+pub mod test {
+ use super::AllocSingle;
+ use crate::const_init::ConstInit;
+ use core::ops::Deref;
+
+ #[derive(Debug)]
+ struct Demo([u8; 512]);
+
+ impl ConstInit for Demo {
+ const VAL: Self = Demo([44u8; 512]);
+ }
+
+ #[test]
+ fn smoke() {
+ static SINGLE: AllocSingle<[u8; 1024]> = AllocSingle::new();
+ static SINGLE_DEMO: AllocSingle<Demo> = AllocSingle::new();
+
+ {
+ let buf = [0xAF; 1024];
+ let mut bx = SINGLE.alloc(buf).unwrap();
+ println!("{:?}", bx.as_slice());
+ bx.iter_mut().for_each(|b| *b = 123);
+ println!("{:?}", bx.as_slice());
+
+ // Second alloc fails
+ let buf2 = [0x01; 1024];
+ assert!(SINGLE.alloc(buf2).is_none());
+ }
+
+ // bx is dropped because we left scope, which means we can
+ // alloc again
+ let buf3 = [0x42; 1024];
+ let mut bx2 = SINGLE.alloc(buf3).unwrap();
+ println!("{:?}", bx2.as_slice());
+ bx2.iter_mut().for_each(|b| *b = 231);
+ println!("{:?}", bx2.as_slice());
+
+ // look ma no stack
+ let bx3 = SINGLE_DEMO.alloc_const_val().unwrap();
+ println!("{:?}", bx3.deref());
+ }
+}
diff --git a/external/vendor/grounded/src/const_init.rs b/external/vendor/grounded/src/const_init.rs
new file mode 100644
index 0000000..8d8a2f6
--- /dev/null
+++ b/external/vendor/grounded/src/const_init.rs
@@ -0,0 +1,50 @@
+//! Const Init
+//!
+//! A trait that is like `Default`, but const
+
+/// A trait that is like `Default`, but const
+pub trait ConstInit {
+ /// The constant default value
+ const VAL: Self;
+}
+
+// Here's some impls that roughly match the default
+// value of these types
+
+macro_rules! impl_const_init_for {
+ ($(($tyname:ty, $val:expr),)+) => {
+ $(
+ impl ConstInit for $tyname {
+ const VAL: Self = $val;
+ }
+ )+
+ };
+}
+
+impl_const_init_for! {
+ (u8, 0),
+ (u16, 0),
+ (u32, 0),
+ (u64, 0),
+ (u128, 0),
+ (i8, 0),
+ (i16, 0),
+ (i32, 0),
+ (i64, 0),
+ (i128, 0),
+ (f32, 0.0),
+ (f64, 0.0),
+ (bool, false),
+ ((), ()),
+}
+
+impl<T, const N: usize> ConstInit for [T; N]
+where
+ T: ConstInit,
+{
+ const VAL: Self = [T::VAL; N];
+}
+
+impl<T> ConstInit for Option<T> {
+ const VAL: Self = None;
+}
diff --git a/external/vendor/grounded/src/lib.rs b/external/vendor/grounded/src/lib.rs
new file mode 100644
index 0000000..1ced464
--- /dev/null
+++ b/external/vendor/grounded/src/lib.rs
@@ -0,0 +1,8 @@
+#![cfg_attr(not(test), no_std)]
+#![doc = include_str!("../README.md")]
+
+pub mod const_init;
+pub mod uninit;
+
+#[cfg(feature = "cas")]
+pub mod alloc_single;
diff --git a/external/vendor/grounded/src/uninit.rs b/external/vendor/grounded/src/uninit.rs
new file mode 100644
index 0000000..8ea11cf
--- /dev/null
+++ b/external/vendor/grounded/src/uninit.rs
@@ -0,0 +1,318 @@
+//! Helpers for dealing with statics that are (potentially) uninitialized at the
+//! start of a program.
+
+use core::{cell::UnsafeCell, mem::MaybeUninit};
+
+use crate::const_init::ConstInit;
+
+/// ## GroundedCell
+///
+/// [GroundedCell] is a type that contains a single `T`. The contained T is wrapped
+/// with:
+///
+/// * An [UnsafeCell] - as synchronization *must* be provided by the wrapping user
+/// * A [MaybeUninit] - as the contents will not be initialized at program start.
+///
+/// This type is intended to be used as a building block for other types, such as
+/// runtime initialized constants, data within uninitialized memory/linker sections,
+/// or similar.
+///
+/// This type may be used to provide inner mutability, when accessed through the
+/// [GroundedCell::get()] interface.
+///
+/// [GroundedCell] is also `#[repr(transparent)]`, as are `UnsafeCell` and `MaybeUninit`,
+/// which means that it will have the same layout and alignment as `T`.
+#[repr(transparent)]
+pub struct GroundedCell<T> {
+ inner: UnsafeCell<MaybeUninit<T>>,
+}
+
+unsafe impl<T> Sync for GroundedCell<T> {}
+unsafe impl<T: Send> Send for GroundedCell<T> {}
+
+impl<T: ConstInit> GroundedCell<T> {
+ /// Create a new GroundedCell with the cell initialized with
+ /// the value of [ConstInit::VAL].
+ ///
+ /// ```rust
+ /// use grounded::uninit::GroundedCell;
+ ///
+ /// static EXAMPLE: GroundedCell<[u8; 1024]> = GroundedCell::const_init();
+ /// ```
+ pub const fn const_init() -> Self {
+ Self {
+ inner: UnsafeCell::new(MaybeUninit::new(T::VAL)),
+ }
+ }
+}
+
+impl<T> GroundedCell<T> {
+ /// Create an uninitialized `GroundedCell`.
+ ///
+ /// ```rust
+ /// use grounded::uninit::GroundedCell;
+ ///
+ /// static EXAMPLE: GroundedCell<u32> = GroundedCell::uninit();
+ /// ```
+ pub const fn uninit() -> Self {
+ Self {
+ inner: UnsafeCell::new(MaybeUninit::uninit()),
+ }
+ }
+
+ /// Obtain a mutable pointer to the contained T.
+ ///
+ /// No claims are made on the validity of the T (it may be invalid or uninitialized),
+ /// and the caller is required to guarantee synchronization of access, e.g. guaranteeing
+ /// that access is shared XOR mutable for the duration of any references created from this
+ /// pointer.
+ ///
+ /// ```rust
+ /// use grounded::uninit::GroundedCell;
+ /// static EXAMPLE: GroundedCell<u32> = GroundedCell::uninit();
+ ///
+ /// let ptr: *mut u32 = EXAMPLE.get();
+ /// assert_ne!(core::ptr::null_mut(), ptr);
+ /// ```
+ pub fn get(&self) -> *mut T {
+ let mu_ptr: *mut MaybeUninit<T> = self.inner.get();
+ let t_ptr: *mut T = mu_ptr.cast::<T>();
+ t_ptr
+ }
+}
+
+/// ## GroundedArrayCell
+///
+/// [GroundedArrayCell] is a type that contains a contiguous array of `[T; N]`.
+/// The contained [T; N] is wrapped with:
+///
+/// * An [UnsafeCell] - as synchronization *must* be provided by the wrapping user
+/// * A [MaybeUninit] - as the contents will not be initialized at program start.
+///
+/// This type is intended to be used as a building block for other types, such as
+/// runtime initialized constants, data within uninitialized memory/linker sections,
+/// or similar.
+///
+/// This type may be used to provide inner mutability, when accessed through the
+/// [GroundedArrayCell::get_ptr_len()] interface.
+///
+/// [GroundedArrayCell] is also `#[repr(transparent)]`, as are `UnsafeCell` and `MaybeUninit`,
+/// which means that it will have the same layout and alignment as `[T; N]`.
+#[repr(transparent)]
+pub struct GroundedArrayCell<T, const N: usize> {
+ inner: UnsafeCell<MaybeUninit<[T; N]>>,
+}
+
+unsafe impl<T: Sync, const N: usize> Sync for GroundedArrayCell<T, N> {}
+
+impl<T: ConstInit, const N: usize> GroundedArrayCell<T, N> {
+ /// Create a new GroundedArrayCell with all cells initialized with
+ /// the value of [ConstInit::VAL].
+ ///
+ /// If your type's implementation of [ConstInit] happens to be all zeroes, like it
+ /// is for many integer and boolean primitives, it is likely your static will end
+ /// up in `.bss`.
+ ///
+ /// ```rust
+ /// use grounded::uninit::GroundedArrayCell;
+ ///
+ /// static EXAMPLE: GroundedArrayCell<u8, 1024> = GroundedArrayCell::const_init();
+ /// ```
+ pub const fn const_init() -> Self {
+ Self {
+ inner: UnsafeCell::new(MaybeUninit::new(<[T; N] as ConstInit>::VAL)),
+ }
+ }
+}
+
+impl<T, const N: usize> GroundedArrayCell<T, N> {
+ /// Create an uninitialized `GroundedArrayCell`.
+ ///
+ /// ```rust
+ /// use grounded::uninit::GroundedArrayCell;
+ ///
+ /// static EXAMPLE: GroundedArrayCell<u8, 128> = GroundedArrayCell::uninit();
+ /// ```
+ pub const fn uninit() -> Self {
+ Self {
+ inner: UnsafeCell::new(MaybeUninit::uninit()),
+ }
+ }
+
+ /// Initialize each element from the provided value, if `T: Copy`.
+ ///
+ /// ## Safety
+ ///
+ /// The caller must ensure that no other access is made to the data contained within this
+ /// cell for the duration of this function
+ #[inline]
+ pub unsafe fn initialize_all_copied(&self, val: T)
+ where
+ T: Copy,
+ {
+ let (mut ptr, len) = self.get_ptr_len();
+ let end = ptr.add(len);
+ while ptr != end {
+ ptr.write(val);
+ ptr = ptr.add(1);
+ }
+ }
+
+ /// Initialize each item, using a provided closure on a per-element basis
+ ///
+ /// ## Safety
+ ///
+ /// The caller must ensure that no other access is made to the data contained within this
+ /// cell for the duration of this function
+ #[inline]
+ pub unsafe fn initialize_all_with<F: FnMut() -> T>(&self, mut f: F) {
+ let (mut ptr, len) = self.get_ptr_len();
+ let end = ptr.add(len);
+ while ptr != end {
+ ptr.write(f());
+ ptr = ptr.add(1);
+ }
+ }
+
+ /// Obtain a mutable starting pointer to the contained [T; N].
+ ///
+ /// No claims are made on the validity of the [T; N] (they may be partially or wholly
+ /// invalid or uninitialized), and the caller is required to guarantee synchronization of
+ /// access, e.g. guaranteeing that access is shared XOR mutable for the duration of any
+ /// references (including slices) created from this pointer.
+ ///
+ /// ```rust
+ /// use grounded::uninit::GroundedArrayCell;
+ /// static EXAMPLE: GroundedArrayCell<u8, 128> = GroundedArrayCell::uninit();
+ ///
+ /// let ptr: *mut u8 = EXAMPLE.as_mut_ptr();
+ /// assert_ne!(core::ptr::null_mut(), ptr);
+ /// ```
+ #[inline]
+ pub fn as_mut_ptr(&self) -> *mut T {
+ let mu_ptr: *mut MaybeUninit<[T; N]> = self.inner.get();
+ let arr_ptr: *mut [T; N] = mu_ptr.cast::<[T; N]>();
+ let t_ptr: *mut T = arr_ptr.cast::<T>();
+ t_ptr
+ }
+
+ /// Obtain a mutable starting pointer and length to the contained [T; N].
+ ///
+ /// No claims are made on the validity of the [T; N] (they may be partially or wholly
+ /// invalid or uninitialized), and the caller is required to guarantee synchronization of
+ /// access, e.g. guaranteeing that access is shared XOR mutable for the duration of any
+ /// references (including slices) created from this pointer.
+ ///
+ /// ```rust
+ /// use grounded::uninit::GroundedArrayCell;
+ /// static EXAMPLE: GroundedArrayCell<u8, 128> = GroundedArrayCell::uninit();
+ ///
+ /// let (ptr, len): (*mut u8, usize) = EXAMPLE.get_ptr_len();
+ /// assert_ne!(core::ptr::null_mut(), ptr);
+ /// assert_eq!(len, 128);
+ /// ```
+ ///
+ /// ## NOTE
+ ///
+ /// This method is suggested to only be used for actions such as initializing the entire
+ /// range. If you are building a data structure that provides partial access safely, such
+ /// as a channel, bip-buffer, or similar, consider using one of the following methods, which
+ /// can help avoid cases where strict provenance is invalidated by creation of an aliasing
+ /// slice:
+ ///
+ /// * For getting a single element:
+ /// * [Self::get_element_unchecked()]
+ /// * [Self::get_element_mut_unchecked()]
+ /// * For getting a subslice:
+ /// * [Self::get_subslice_unchecked()]
+ /// * [Self::get_subslice_mut_unchecked()]
+ #[inline]
+ pub fn get_ptr_len(&self) -> (*mut T, usize) {
+ (self.as_mut_ptr(), N)
+ }
+
+ /// Obtain a reference to a single element, which can be thought of as `&data[offset]`.
+ ///
+ /// The reference is created **without** creating the entire slice this cell represents.
+ /// This is important, if a mutable reference of a disjoint region is currently live.
+ ///
+ /// ## Safety
+ ///
+ /// The caller **must** ensure all of the following:
+ ///
+ /// * The selected element has been initialized with a valid value prior to calling
+ /// this function
+ /// * No `&mut` slices or references may overlap the produced reference for the duration the reference is live
+ /// * No modifications (even via pointers) are made to to the element pointed to
+ /// while the reference is live
+ /// * `offset` is < N
+ #[inline]
+ pub unsafe fn get_element_unchecked(&self, offset: usize) -> &'_ T {
+ &*self.as_mut_ptr().add(offset)
+ }
+
+ /// Obtain a mutable reference to a single element, which can be thought of as `&mut data[offset]`.
+ ///
+ /// The reference is created **without** creating the entire slice this cell represents.
+ /// This is important, if a mutable reference of a disjoint region is currently live.
+ ///
+ /// ## Safety
+ ///
+ /// The caller **must** ensure all of the following:
+ ///
+ /// * The selected element has been initialized with a valid value prior to calling
+ /// this function
+ /// * No slices or references of any kind may overlap the produced reference for the duration
+ /// the reference is live
+ /// * No modifications (even via pointers) are made to to the element pointed to
+ /// while the reference is live, except via the returned mutable reference
+ /// * `offset` is < N
+ #[allow(clippy::mut_from_ref)]
+ #[inline]
+ pub unsafe fn get_element_mut_unchecked(&self, offset: usize) -> &mut T {
+ &mut *self.as_mut_ptr().add(offset)
+ }
+
+ /// Obtain a subslice starting at `offset`, of length `len`, which
+ /// can be thought of as `&data[offset..][..len]`.
+ ///
+ /// The subslice is created **without** creating the entire slice this cell represents.
+ /// This is important, if a mutable reference of a disjoint region is currently live.
+ ///
+ /// ## Safety
+ ///
+ /// The caller **must** ensure all of the following:
+ ///
+ /// * All elements in this region have been initialized with a valid value prior to calling
+ /// this function
+ /// * No `&mut` slices may overlap the produced slice for the duration the slice is live
+ /// * No modifications (even via pointers) are made to data within the range of this slice
+ /// while the slice is live
+ /// * `offset` and `offset + len` are <= N
+ #[inline]
+ pub unsafe fn get_subslice_unchecked(&self, offset: usize, len: usize) -> &'_ [T] {
+ core::slice::from_raw_parts(self.as_mut_ptr().add(offset), len)
+ }
+
+ /// Obtain a mutable subslice starting at `offset`, of length `len`, which
+ /// can be thought of as `&mut data[offset..][..len]`.
+ ///
+ /// The subslice is created **without** creating the entire slice this cell represents.
+ /// This is important, if ANY reference of a disjoint region is currently live.
+ ///
+ /// ## Safety
+ ///
+ /// The caller **must** ensure all of the following:
+ ///
+ /// * All elements in this region have been initialized with a valid value prior to calling
+ /// this function
+ /// * No ``&` or &mut` slices may overlap the produced slice for the duration the slice is live
+ /// * No modifications (even via pointers) are made to data within the range of this slice
+ /// while the slice is live, except via the returned mutable reference
+ /// * `offset` and `offset + len` are <= N
+ #[allow(clippy::mut_from_ref)]
+ #[inline]
+ pub unsafe fn get_subslice_mut_unchecked(&self, offset: usize, len: usize) -> &'_ mut [T] {
+ core::slice::from_raw_parts_mut(self.as_mut_ptr().add(offset), len)
+ }
+}
diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock
index b0d165d..04e5d44 100644
--- a/src/rust/Cargo.lock
+++ b/src/rust/Cargo.lock
@@ -173,6 +173,7 @@ dependencies = [
"erc20_params",
"fatfs-sys",
"futures-lite",
+ "grounded",
"hex",
"hex_lit",
"hmac",
@@ -627,6 +628,15 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "grounded"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a7c71ebd5d467418b46639b622912cd0338ce59766bd19130bffcbf9ac6df2c"
+dependencies = [
+ "portable-atomic",
+]
+
[[package]]
name = "group"
version = "0.13.0"
@@ -863,6 +873,9 @@ name = "portable-atomic"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "280dc24453071f1b63954171985a0b0d30058d287960968b9b2aca264c8d4ee6"
+dependencies = [
+ "critical-section",
+]
[[package]]
name = "powerfmt"
diff --git a/src/rust/bitbox02-rust/Cargo.toml b/src/rust/bitbox02-rust/Cargo.toml
index 3f4297d..d6c5389 100644
--- a/src/rust/bitbox02-rust/Cargo.toml
+++ b/src/rust/bitbox02-rust/Cargo.toml
@@ -49,6 +49,7 @@ bip39 = { workspace = true }
bitcoin_hashes = { version = "0.14.0", default-features = false, features = ["small-hash"] }
futures-lite = { workspace = true }
hex_lit = { workspace = true, features = ["rust_v_1_46"] }
+grounded = { version = "0.2.0", default-features = false, features = ["critical-section"] }
[dependencies.prost]
# keep version in sync with tools/prost-build/Cargo.toml.
diff --git a/src/rust/bitbox02-rust/src/hal/bitbox02.rs b/src/rust/bitbox02-rust/src/hal/bitbox02.rs
index 7a9cb8c..fdccdd6 100644
--- a/src/rust/bitbox02-rust/src/hal/bitbox02.rs
+++ b/src/rust/bitbox02-rust/src/hal/bitbox02.rs
@@ -18,6 +18,10 @@ pub struct BitBox02Hal {
system: system::BitBox02System,
}
+impl grounded::const_init::ConstInit for BitBox02Hal {
+ const VAL: Self = Self::new();
+}
+
impl BitBox02Hal {
pub const fn new() -> Self {
Self {
diff --git a/src/rust/bitbox02-rust/src/main_loop.rs b/src/rust/bitbox02-rust/src/main_loop.rs
index 0bbec68..878acca 100644
--- a/src/rust/bitbox02-rust/src/main_loop.rs
+++ b/src/rust/bitbox02-rust/src/main_loop.rs
@@ -1,15 +1,23 @@
// SPDX-License-Identifier: Apache-2.0
+use alloc::boxed::Box;
use bitbox_executor::Executor;
use bitbox02::ringbuffer::RingBuffer;
use bitbox02::uart::USART_0_BUFFER_SIZE;
use bitbox02::usb_packet::USB_FRAME;
+use core::future::Future;
use core::mem::MaybeUninit;
+use core::pin::Pin;
use core::sync::atomic::{AtomicBool, Ordering};
const UART_OUT_BUF_LEN: u32 = 2048;
static EXECUTOR: Executor = Executor::new();
+type DynExecutorFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;
+
+pub fn spawn(fut: DynExecutorFuture) {
+ EXECUTOR.spawn(fut).detach();
+}
fn main_loop(hal: &mut impl crate::hal::Hal) -> ! {
static ORIENTATION_CHOSEN: AtomicBool = AtomicBool::new(false);
@@ -28,12 +36,10 @@ fn main_loop(hal: &mut impl crate::hal::Hal) -> ! {
bitbox02::da14531::set_name(&device_name, &mut uart_write_queue);
// This starts the async orientation screen workflow, which is processed by the loop below.
- EXECUTOR
- .spawn(async {
- crate::workflow::orientation_screen::orientation_screen().await;
- ORIENTATION_CHOSEN.store(true, Ordering::Relaxed);
- })
- .detach();
+ spawn(Box::pin(async {
+ crate::workflow::orientation_screen::orientation_screen().await;
+ ORIENTATION_CHOSEN.store(true, Ordering::Relaxed);
+ }));
let mut hww_data = None;
let mut hww_frame: USB_FRAME = unsafe { MaybeUninit::zeroed().assume_init() };
@@ -149,9 +155,6 @@ fn main_loop(hal: &mut impl crate::hal::Hal) -> ! {
bitbox02::screen::process();
/* And finally, run the high-level event processing. */
- #[cfg(feature = "app-u2f")]
- crate::workflow::u2f_c_api::workflow_spin();
-
crate::async_usb::spin();
// Run async executor
diff --git a/src/rust/bitbox02-rust/src/workflow.rs b/src/rust/bitbox02-rust/src/workflow.rs
index b71f8e1..b48ccc2 100644
--- a/src/rust/bitbox02-rust/src/workflow.rs
+++ b/src/rust/bitbox02-rust/src/workflow.rs
@@ -16,8 +16,46 @@ pub mod status;
pub mod transaction;
pub mod trinary_choice;
pub mod trinary_input_string;
-#[cfg(feature = "app-u2f")]
-pub mod u2f_c_api;
pub mod unlock;
pub mod unlock_animation;
pub mod verify_message;
+
+// Active in production firmware.
+#[cfg(all(
+ feature = "app-u2f",
+ not(any(feature = "c-unit-testing", feature = "simulator-graphical"))
+))]
+pub mod u2f_c_api;
+
+// Stubs for C unit tests and C simulator - these are currently compiled and linked but they don't
+// actually have to spawn/poll futures. The C simulator does not contain U2F, and the unit tests
+// don't contain an executor.
+#[cfg(all(
+ feature = "app-u2f",
+ any(feature = "c-unit-testing", feature = "simulator-graphical")
+))]
+pub mod u2f_c_api {
+ #![allow(clippy::missing_safety_doc)]
+
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn rust_workflow_spawn_unlock() {}
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn rust_workflow_spawn_confirm(
+ _title: *const core::ffi::c_char,
+ _body: *const core::ffi::c_char,
+ ) {
+ panic!("unused");
+ }
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn rust_workflow_unlock_poll(_result_out: &mut bool) -> bool {
+ panic!("unused");
+ }
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn rust_workflow_confirm_poll(_result_out: &mut bool) -> bool {
+ panic!("unused");
+ }
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn rust_workflow_abort_current() {
+ panic!("unused");
+ }
+}
diff --git a/src/rust/bitbox02-rust/src/workflow/u2f_c_api.rs b/src/rust/bitbox02-rust/src/workflow/u2f_c_api.rs
index 9c8ebb0..834dc66 100644
--- a/src/rust/bitbox02-rust/src/workflow/u2f_c_api.rs
+++ b/src/rust/bitbox02-rust/src/workflow/u2f_c_api.rs
@@ -4,128 +4,174 @@
//! usb message proessing is not ported to Rust. If that happens, the `async_usb` module can be
//! used and this can be deleted.
-// TODO: figure out how to deal with the static muts below.
-// https://doc.rust-lang.org/nightly/edition-guide/rust-2024/static-mut-references.html
-#![allow(static_mut_refs)]
-#![allow(clippy::missing_safety_doc)]
-
extern crate alloc;
+use crate::hal::{Hal, Ui};
use crate::workflow::confirm;
use alloc::boxed::Box;
use alloc::string::String;
-use core::task::Poll;
-use util::bb02_async::{Task, spin};
+use core::ffi::CStr;
+use core::sync::atomic::{AtomicU32, Ordering};
+use grounded::const_init::ConstInit;
+use grounded::uninit::GroundedCell;
-enum TaskState<'a, O> {
+enum TaskState<O> {
Nothing,
- Running(Task<'a, O>),
+ Running(u32),
ResultAvailable(O),
}
-static mut UNLOCK_STATE: TaskState<'static, Result<(), ()>> = TaskState::Nothing;
+impl<O> ConstInit for TaskState<O> {
+ const VAL: Self = Self::Nothing;
+}
+
+static NEXT_TASK_TOKEN: AtomicU32 = AtomicU32::new(0);
+static UNLOCK_STATE: GroundedCell<TaskState<Result<(), ()>>> = GroundedCell::const_init();
+static CONFIRM_STATE: GroundedCell<TaskState<Result<(), confirm::UserAbort>>> =
+ GroundedCell::const_init();
+static BITBOX02_HAL: GroundedCell<crate::hal::BitBox02Hal> = GroundedCell::const_init();
+
+fn next_task_token() -> u32 {
+ NEXT_TASK_TOKEN.fetch_add(1, Ordering::Relaxed)
+}
+
+/// # Safety
+/// Must not be called concurrently or reentrantly with other operations that mutate unlock
+/// workflow state in this module.
+/// Callers must guarantee single-threaded access to this workflow.
+unsafe fn complete_unlock(token: u32, result: Result<(), ()>) {
+ unsafe {
+ if let TaskState::Running(current_token) = UNLOCK_STATE.get().as_ref().unwrap()
+ && *current_token == token
+ {
+ UNLOCK_STATE.get().write(TaskState::ResultAvailable(result));
+ }
+ }
+}
-static mut CONFIRM_TITLE: Option<String> = None;
-static mut CONFIRM_BODY: Option<String> = None;
-static mut CONFIRM_PARAMS: Option<confirm::Params> = None;
-static mut CONFIRM_STATE: TaskState<'static, Result<(), confirm::UserAbort>> = TaskState::Nothing;
-static mut BITBOX02_HAL: crate::hal::BitBox02Hal = crate::hal::BitBox02Hal::new();
+/// # Safety
+/// Must not be called concurrently or reentrantly with other operations that mutate confirm
+/// workflow state in this module.
+/// Callers must guarantee single-threaded access to this workflow.
+unsafe fn complete_confirm(token: u32, result: Result<(), confirm::UserAbort>) {
+ unsafe {
+ if let TaskState::Running(current_token) = CONFIRM_STATE.get().as_ref().unwrap()
+ && *current_token == token
+ {
+ CONFIRM_STATE
+ .get()
+ .write(TaskState::ResultAvailable(result));
+ }
+ }
+}
+/// # Safety
+/// Must be called from the same single-threaded, non-reentrant execution context as all other
+/// U2F workflow C API calls. In particular, do not call this from interrupts or from multiple
+/// threads.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_spawn_unlock() {
+ let token = next_task_token();
unsafe {
- UNLOCK_STATE =
- TaskState::Running(Box::pin(crate::workflow::unlock::unlock(&mut BITBOX02_HAL)));
+ UNLOCK_STATE.get().write(TaskState::Running(token));
}
+ crate::main_loop::spawn(Box::pin(async move {
+ let result =
+ unsafe { crate::workflow::unlock::unlock(BITBOX02_HAL.get().as_mut().unwrap()).await };
+ unsafe { complete_unlock(token, result) };
+ }));
}
+/// # Safety
+/// `title` and `body` must be valid non-null pointers to NUL-terminated UTF-8 strings, readable
+/// for the duration of this call.
+///
+/// This must be called from the same single-threaded, non-reentrant execution context as all
+/// other U2F workflow C API calls (no interrupts/multi-threaded callers).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_spawn_confirm(
title: *const core::ffi::c_char,
body: *const core::ffi::c_char,
) {
+ let title: String = unsafe { CStr::from_ptr(title).to_str().unwrap().into() };
+ let body: String = unsafe { CStr::from_ptr(body).to_str().unwrap().into() };
+ let token = next_task_token();
unsafe {
- CONFIRM_TITLE = Some(core::ffi::CStr::from_ptr(title).to_str().unwrap().into());
- CONFIRM_BODY = Some(core::ffi::CStr::from_ptr(body).to_str().unwrap().into());
- CONFIRM_PARAMS = Some(confirm::Params {
- title: CONFIRM_TITLE.as_ref().unwrap(),
- body: CONFIRM_BODY.as_ref().unwrap(),
+ CONFIRM_STATE.get().write(TaskState::Running(token));
+ }
+ crate::main_loop::spawn(Box::pin(async move {
+ let params = confirm::Params {
+ title: &title,
+ body: &body,
accept_only: true,
..Default::default()
- });
-
- CONFIRM_STATE =
- TaskState::Running(Box::pin(confirm::confirm(CONFIRM_PARAMS.as_ref().unwrap())));
- }
-}
-
-pub fn workflow_spin() {
- unsafe {
- match UNLOCK_STATE {
- TaskState::Running(ref mut task) => {
- let result = spin(task);
- if let Poll::Ready(result) = result {
- UNLOCK_STATE = TaskState::ResultAvailable(result);
- }
- }
- _ => (),
- }
- match CONFIRM_STATE {
- TaskState::Running(ref mut task) => {
- let result = spin(task);
- if let Poll::Ready(result) = result {
- CONFIRM_STATE = TaskState::ResultAvailable(result);
- }
- }
- _ => (),
- }
- }
+ };
+ let result = unsafe {
+ BITBOX02_HAL
+ .get()
+ .as_mut()
+ .unwrap()
+ .ui()
+ .confirm(¶ms)
+ .await
+ };
+ unsafe { complete_confirm(token, result) };
+ }));
}
/// Returns true if there was a result.
+///
+/// # Safety
+/// `result_out` must be a valid, non-null writable pointer to a `bool` for the duration of this
+/// call.
+///
+/// This must be called from the same single-threaded, non-reentrant execution context as all
+/// other U2F workflow C API calls (no interrupts/multi-threaded callers).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_unlock_poll(result_out: &mut bool) -> bool {
unsafe {
- match UNLOCK_STATE {
+ match UNLOCK_STATE.get().as_ref().unwrap() {
TaskState::ResultAvailable(result) => {
- UNLOCK_STATE = TaskState::Nothing;
- match result {
- Ok(()) => *result_out = true,
- Err(()) => *result_out = false,
- }
+ *result_out = result.is_ok();
+ UNLOCK_STATE.get().write(TaskState::Nothing);
true
}
- _ => false,
+ TaskState::Running(_) => false,
+ TaskState::Nothing => panic!("polled non-existing future"),
}
}
}
/// Returns true if there was a result.
+///
+/// # Safety
+/// `result_out` must be a valid, non-null writable pointer to a `bool` for the duration of this
+/// call.
+///
+/// This must be called from the same single-threaded, non-reentrant execution context as all
+/// other U2F workflow C API calls (no interrupts/multi-threaded callers).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_confirm_poll(result_out: &mut bool) -> bool {
unsafe {
- match CONFIRM_STATE {
- TaskState::ResultAvailable(ref result) => {
- CONFIRM_TITLE = None;
- CONFIRM_BODY = None;
- CONFIRM_PARAMS = None;
- CONFIRM_STATE = TaskState::Nothing;
+ match CONFIRM_STATE.get().as_ref().unwrap() {
+ TaskState::ResultAvailable(result) => {
+ CONFIRM_STATE.get().write(TaskState::Nothing);
*result_out = result.is_ok();
true
}
- _ => false,
+ TaskState::Running(_) => false,
+ TaskState::Nothing => false,
}
}
}
+/// # Safety
+/// Must be called from the same single-threaded, non-reentrant execution context as all other
+/// U2F workflow C API calls (no interrupts/multi-threaded callers).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_workflow_abort_current() {
unsafe {
- UNLOCK_STATE = TaskState::Nothing;
-
- CONFIRM_TITLE = None;
- CONFIRM_BODY = None;
- CONFIRM_PARAMS = None;
- CONFIRM_STATE = TaskState::Nothing;
+ UNLOCK_STATE.get().write(TaskState::Nothing);
+ CONFIRM_STATE.get().write(TaskState::Nothing);
}
}
diff --git a/test/simulator-graphical-bb03/Cargo.lock b/test/simulator-graphical-bb03/Cargo.lock
index 2c76775..2c4cb6c 100644
--- a/test/simulator-graphical-bb03/Cargo.lock
+++ b/test/simulator-graphical-bb03/Cargo.lock
@@ -393,6 +393,7 @@ dependencies = [
"erc20_params",
"fatfs-sys",
"futures-lite",
+ "grounded",
"hex",
"hex_lit",
"hmac",
@@ -1384,6 +1385,15 @@ dependencies = [
"gl_generator",
]
+[[package]]
+name = "grounded"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a7c71ebd5d467418b46639b622912cd0338ce59766bd19130bffcbf9ac6df2c"
+dependencies = [
+ "portable-atomic",
+]
+
[[package]]
name = "half"
version = "2.7.1"
@@ -2315,6 +2325,15 @@ dependencies = [
"universal-hash",
]
+[[package]]
+name = "portable-atomic"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
+dependencies = [
+ "critical-section",
+]
+
[[package]]
name = "powerfmt"
version = "0.2.0"
diff --git a/test/simulator-graphical/Cargo.lock b/test/simulator-graphical/Cargo.lock
index b9a401b..ed5d921 100644
--- a/test/simulator-graphical/Cargo.lock
+++ b/test/simulator-graphical/Cargo.lock
@@ -355,6 +355,7 @@ dependencies = [
"erc20_params",
"fatfs-sys",
"futures-lite",
+ "grounded",
"hex",
"hex_lit",
"hmac",
@@ -1329,6 +1330,15 @@ dependencies = [
"gl_generator",
]
+[[package]]
+name = "grounded"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a7c71ebd5d467418b46639b622912cd0338ce59766bd19130bffcbf9ac6df2c"
+dependencies = [
+ "portable-atomic",
+]
+
[[package]]
name = "half"
version = "2.6.0"
@@ -2261,6 +2271,15 @@ dependencies = [
"universal-hash",
]
+[[package]]
+name = "portable-atomic"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
+dependencies = [
+ "critical-section",
+]
+
[[package]]
name = "powerfmt"
version = "0.2.0"
Why this scored 32/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.