dice: support fallible allocation for retry
Adds a new error, NoMemory, and uses it to implement fallible allocation
for the retry module. When feature `"std"` is not used, first try to
reserve the underlying buffer before resizing.
Bug: 369146791
Test: m libdiced_open_dice_nostd libdiced_open_dice
Test: Manual inclusions and test runs in the WIP CL aosp/3443480
Change-Id: I7c907a5630526eba4e668d729a3e98a94c648eab
diff --git a/libs/dice/open_dice/src/error.rs b/libs/dice/open_dice/src/error.rs
index 9089432..c9eb5cc 100644
--- a/libs/dice/open_dice/src/error.rs
+++ b/libs/dice/open_dice/src/error.rs
@@ -31,6 +31,8 @@
PlatformError,
/// Unsupported key algorithm.
UnsupportedKeyAlgorithm(coset::iana::Algorithm),
+ /// A failed fallible allocation. Used in no_std environments.
+ MemoryAllocationError,
}
/// This makes `DiceError` accepted by anyhow.
@@ -48,6 +50,7 @@
Self::UnsupportedKeyAlgorithm(algorithm) => {
write!(f, "Unsupported key algorithm: {algorithm:?}")
}
+ Self::MemoryAllocationError => write!(f, "Memory allocation failed"),
}
}
}
diff --git a/libs/dice/open_dice/src/retry.rs b/libs/dice/open_dice/src/retry.rs
index 6e75e91..803673d 100644
--- a/libs/dice/open_dice/src/retry.rs
+++ b/libs/dice/open_dice/src/retry.rs
@@ -13,9 +13,9 @@
// limitations under the License.
//! This module implements a retry version for multiple DICE functions that
-//! require preallocated output buffer. As the retry functions require
-//! memory allocation on heap, currently we only expose these functions in
-//! std environment.
+//! require preallocated output buffer. When running without std the allocation
+//! of this buffer may fail and callers will see Error::MemoryAllocationError.
+//! When running with std, allocation may fail.
use crate::bcc::{bcc_format_config_descriptor, bcc_main_flow, DiceConfigValues};
use crate::dice::{
@@ -62,6 +62,9 @@
let mut buffer = Vec::new();
match f(&mut buffer) {
Err(DiceError::BufferTooSmall(actual_size)) => {
+ #[cfg(not(feature = "std"))]
+ buffer.try_reserve_exact(actual_size).map_err(|_| DiceError::MemoryAllocationError)?;
+
buffer.resize(actual_size, 0);
f(&mut buffer)?;
}