|
libmemalloc 0.0.0-alpha
The Magic of Memory Transmutation
|
Use this catalogue to review a concrete failure mechanism and choose a regression test. The code standard owns the requirements and profiles; the architecture guide owns module and lifecycle boundaries. A pitfall is not a new blanket prohibition. Distinguish performance cost, logical failure and undefined behavior.
For each applicable entry, record the trigger in your program, the affected invariant and the observation that would detect its failure. Safe Rust can reject lifetime misuse at compile time while still permitting leaks, deadlocks, logic errors and unbounded work. Unsafe abstractions require separate soundness review.
The counterexamples below are short review descriptions or contextual expressions, not executable programs. Do not execute UB examples to establish correctness. Compile-fail tests check the intended diagnostic; Miri/sanitizer tests exercise valid API calls that challenge implementation invariants. FFI tests must respect unsafe caller preconditions unless a separately contained negative-testing harness is explicitly designed for them.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A parser calls payload.to_vec() before every read-only helper.
Failure mechanism: Each independent buffer can copy bytes and allocate even though no consumer needs ownership.
Prevention: Borrow a slice or move the existing owner; keep a deliberate snapshot when isolation requires it.
Verification design: Compare allocation and byte-copy counts with representative payload sizes and retained-result tests.
Prevention controls: RUST-009, RUST-008.
External references: Technical context.
Contextual prevention example:
inspect(&payload);
Failure fragment or claim (do not execute):
inspect(&payload.clone());
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: format!, collect::<Vec<_>>() or boxed closures enter an allocation-free operation.
Failure mechanism: Short expressions hide heap work and can introduce exhaustion or allocator reentry.
Prevention: Use bounded caller-owned storage, borrowed views or a measured preallocation policy; include diagnostics.
Verification design: Instrument allocations after setup, including rejection and cleanup paths.
Prevention controls: RUST-025, RUST-056.
External references: Technical context.
Contextual prevention example:
write!(bounded_writer, "count={count}")?;
Failure fragment or claim (do not execute):
let message = format!("count={count}"); // Inside a no-allocation path.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A std::sync::MutexGuard remains live when an async function suspends.
Failure mechanism: Another task can block the executor thread needed to resume the lock owner, or the future fails a Send bound.
Prevention: End the guard scope before suspension. Use an async mutex only when exclusive access must span the wait.
Verification design: Run competing tasks on a constrained executor and assert completion under a test deadline.
Prevention controls: RUST-037.
External references: Technical context.
Contextual prevention example:
let request = { shared.lock()?.make_request() };
send(request).await?;
Failure fragment or claim (do not execute):
let guard = shared.lock()?; send(guard.request()).await?;
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A wrapper assumes every interrupted mutation must poison its mutex.
Failure mechanism: Poisoning is advisory; some panic situations are not detected. Recovery without repair may expose invalid state.
Prevention: Maintain soundness independently of poisoning and define a domain recovery decision.
Verification design: Inject panics at mutation stages; inspect protected state before recovery.
Prevention controls: RUST-036.
External references: Technical context.
Contextual prevention example:
let state = recover_after_checking_invariants(poisoned)?;
Failure fragment or claim (do not execute):
let state = poisoned.into_inner(); // Assumes invariants still hold.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A parent and callback each retain a strong reference to the other.
Failure mechanism: Reference counts never reach zero, so logical shutdown and resource release may never happen.
Prevention: Use a justified weak edge or explicitly unregister the callback and break the cycle.
Verification design: Count drops and live callbacks after dropping the external root; include failed initialization.
Prevention controls: RUST-039, RUST-026.
External references: Technical context.
Contextual prevention example:
let parent = std::rc::Rc::downgrade(&parent);
Failure fragment or claim (do not execute):
child.parent = Some(std::rc::Rc::clone(&parent)); // Completes a strong cycle.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A callback reenters while a borrow_mut() guard is live.
Failure mechanism: The nested borrow panics at runtime; choosing RefCell did not prove non-overlap.
Prevention: Shorten guard scope or use try_borrow_mut when rejection is expected; document reentry.
Verification design: Use a callback that attempts reentry and check both error behavior and later usability.
Prevention controls: RUST-014.
External references: Technical context.
Contextual prevention example:
let state = cell.try_borrow_mut().map_err(|_| Error::Busy)?;
Failure fragment or claim (do not execute):
let state = cell.borrow_mut(); callback_that_reenters();
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: An external u64 length becomes u32 or usize through as.
Failure mechanism: The converted length can differ from the validated length, undermining bounds or allocation calculations.
Prevention: Use TryFrom and validate the target domain before allocation or access.
Verification design: Test zero, maximum accepted value, one above it and 32-bit targets.
Prevention controls: RUST-012, RUST-020.
External references: Technical context.
Contextual prevention example:
let length = usize::try_from(wire_length).map_err(|_| Error::Length)?;
Failure fragment or claim (do not execute):
let length = wire_length as usize;
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A cache reconstructs a pointer from an integer after its original owner was freed.
Failure mechanism: A matching numerical address does not restore allocation lifetime or valid provenance.
Prevention: Retain the owner and derive pointers through documented APIs; use generational IDs for lookup.
Verification design: Review allocation lineage and exercise owner replacement/reuse under Miri.
Prevention controls: RUST-028, RUST-041.
External references: Technical context.
Contextual prevention example:
let owner = registry.acquire(id)?; inspect(owner.as_ref());
Failure fragment or claim (do not execute):
let value = unsafe { &*(saved_address as *const Entry) };
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: Code transmutes an arbitrary integer into an enum because their sizes match.
Failure mechanism: Some bit patterns are invalid for the destination, and equal size proves neither validity nor lifetime.
Prevention: Decode through a checked match or a reviewed conversion with a complete validity proof.
Verification design: Test all admitted tags and reject unknown ones without constructing an invalid enum.
Prevention controls: RUST-031, RUST-020.
External references: Technical context.
Contextual prevention example:
let tag = Tag::try_from(raw_tag)?;
Failure fragment or claim (do not execute):
let tag: Tag = unsafe { std::mem::transmute(raw_tag) };
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: assume_init() runs after only some elements or fields were written.
Failure mechanism: The resulting value contains uninitialized or invalid data; partial cleanup may also drop unwritten elements.
Prevention: Track initialization progress, expose initialized values only after completion and drop the valid prefix.
Verification design: Inject failure after each initialized element and verify exact destructor counts.
Prevention controls: RUST-030.
External references: Technical context.
Contextual prevention example:
slot.write(value); initialized += 1;
Failure fragment or claim (do not execute):
let value = unsafe { slot.assume_init() }; // No complete initialization.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A wrapper forms &*ptr and then checks alignment or nullness.
Failure mechanism: Reference creation already requires validity; a later check cannot repair the operation.
Prevention: Check rejectable scalar conditions first and require external lifetime/access facts in an unsafe contract.
Verification design: Review operation order and test safe rejection without constructing invalid references.
Prevention controls: RUST-029.
External references: Technical context.
Contextual prevention example:
if ptr.is_null() {
return Err(Error::Null);
}
// The remaining lifetime, extent and aliasing proof is still required.
Failure fragment or claim (do not execute):
let value = unsafe { &*ptr };
if ptr.is_null() { return Err(Error::Null); }
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A decoder reads a default-layout Rust struct from network bytes.
Failure mechanism: Field order, padding and value validity are not a wire-format contract; repr(C) alone is not serialization.
Prevention: Decode fields with explicit offsets, byte order and range checks.
Verification design: Use byte-level golden vectors and target-width/endianness cases.
Prevention controls: RUST-011, RUST-023.
External references: Technical context.
Contextual prevention example:
let id = u32::from_le_bytes(encoded_id);
Failure fragment or claim (do not execute):
let record = unsafe { std::ptr::read(input.as_ptr().cast::<Record>()) };
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A declaration uses the wrong calling convention, integer width or struct field representation.
Failure mechanism: The foreign caller and Rust implementation disagree about arguments or returns, potentially causing UB.
Prevention: Generate or review declarations for the actual target and use an explicit native ABI.
Verification design: Compile a real C consumer and assert layout/signature agreement on each supported ABI.
Prevention controls: RUST-011.
External references: Technical context.
Contextual prevention example:
#[repr(C)]
struct NativeView {
data: *const u8,
len: usize,
}
Failure fragment or claim (do not execute):
struct NativeView { data: Vec<u8> } // Exposed as a C ABI record.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: An exported operation panics after a failed allocation or invariant check.
Failure mechanism: A non-unwinding boundary can abort; permitted unwinding needs an agreed ABI and foreign cleanup behavior.
Prevention: Use Result internally and a documented boundary error/panic policy; do not treat catch_unwind as an abort catcher.
Verification design: Test panic behavior in a subprocess for each panic strategy.
Prevention controls: RUST-035, RUST-005.
External references: Technical context.
Contextual prevention example:
match operation() {
Ok(value) => encode_success(value),
Err(error) => encode_error(error),
}
Failure fragment or claim (do not execute):
extern "C" fn entry() { panic!("bad input"); }
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A raw-handle wrapper manually implements Send despite thread-affine destruction.
Failure mechanism: Safe callers can move it to another thread and invoke an operation the resource contract forbids.
Prevention: Let auto traits apply where possible; otherwise prove transfer, sharing and destructor requirements separately.
Verification design: Audit generic bounds and callback thread rules; use compile-fail cases for forbidden transfer.
Prevention controls: RUST-033.
External references: Technical context.
Contextual prevention example:
// Keep the handle on its owning thread and send requests through a port.
Failure fragment or claim (do not execute):
unsafe impl Send for ThreadAffineHandle {}
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: Drop panics during unwinding or destroys memory already transferred to another owner.
Failure mechanism: The process can abort or the resource can be released twice; skipped Drop is also legal in safe code.
Prevention: Track transfer state and provide explicit fallible finalization without relying on guaranteed destruction.
Verification design: Inject errors during construction/finalization and count exactly-once releases.
Prevention controls: RUST-026.
External references: Technical context.
Contextual prevention example:
let result = writer.finish(); report_completion(result);
Failure fragment or claim (do not execute):
impl Drop for Writer {
fn drop(&mut self) { self.flush().unwrap(); }
}
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: An unchecked projection exposes a movable field that an internal pointer relies on.
Failure mechanism: Pinned address-dependent state can become invalid despite the outer Pin wrapper.
Prevention: Define structural pinning and audit projection, replacement, Drop and Unpin together.
Verification design: Review every mutable accessor and use a qualified pin-projection implementation.
Prevention controls: RUST-032.
External references: Technical context.
Contextual prevention example:
let pinned = Box::pin(operation());
Failure fragment or claim (do not execute):
let moved = unsafe { std::ptr::read(pinned.as_ref().get_ref()) };
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A select branch drops an in-progress read or write and retries as if nothing happened.
Failure mechanism: External progress or consumed bytes may already exist, producing duplication or data loss.
Prevention: Keep progress in a surviving owner, or use an operation documented as cancellation safe for that use.
Verification design: Cancel at each await point; compare received bytes and state against uninterrupted execution.
Prevention controls: RUST-038, RUST-046.
External references: Technical context.
Contextual prevention example:
transfer.sent += write_some(&payload[transfer.sent..]).await?;
Failure fragment or claim (do not execute):
write_all(payload).await?; // Cancellation retries the whole payload.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: One path acquires A then B while another acquires B then A.
Failure mechanism: Each waits for a resource held by the other; reentrant callbacks can create the same cycle.
Prevention: Use a declared acquisition order and call unknown code outside internal critical sections.
Verification design: Model the lock graph and test coordinated opposing operations with bounded deadlines.
Prevention controls: RUST-036.
External references: Technical context.
Contextual prevention example:
let first = lock_a.lock()?; let second = lock_b.lock()?; // All paths use A before B.
Failure fragment or claim (do not execute):
let first = lock_b.lock()?; let second = lock_a.lock()?; // Other paths use the opposite order.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A ready flag uses Relaxed while publishing non-atomic payload data.
Failure mechanism: The reader has no required happens-before relation for observing initialized payload.
Prevention: Use the ordering/protocol justified by publication and reclamation; stronger ordering alone cannot fix lifetime.
Verification design: Model writer/reader interleavings and run supported weakly ordered targets.
Prevention controls: RUST-040, RUST-041.
External references: Technical context.
Contextual prevention example:
// Payload validity follows the protocol; Release publishes prior writes. ready.store(true, Ordering::Release);
Failure fragment or claim (do not execute):
ready.store(true, Ordering::Relaxed); // Claimed to publish non-atomic data.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: An unchecked size multiplication appears safe because debug tests panic.
Failure mechanism: Release behavior can produce an unintended count, and profile configuration can change checks.
Prevention: Use checked multiplication/addition for sizes; choose wrapping only for a specified modular domain.
Verification design: Test overflow boundaries in debug and release and verify no mutation after rejection.
Prevention controls: RUST-020.
External references: Technical context.
Contextual prevention example:
let bytes = count.checked_mul(item_size).ok_or(Error::Size)?;
Failure fragment or claim (do not execute):
let bytes = count * item_size;
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A generic method invokes a Clone implementation, iterator adapter or boxed-future provider.
Failure mechanism: The public signature does not state the allocation, retention or synchronization cost of its implementation.
Prevention: Define the resource contract for the selected provider; keep generics from hiding an unreviewed hot-path cost.
Verification design: Measure production implementations as well as mocks, including trait dispatch and error formatting.
Prevention controls: RUST-009, RUST-019, RUST-025.
External references: Technical context.
Contextual prevention example:
// Provider contract: bounded work, no allocation after construction. provider.process(input)?;
Failure fragment or claim (do not execute):
let copy = generic_value.clone(); // Assumed cheap for every implementation.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A borrow conflict is bypassed with raw pointers or unchecked aliasing.
Failure mechanism: The original ownership conflict remains; the compiler can no longer enforce the missing contract.
Prevention: Restructure lifetimes, split disjoint slices or move ownership before considering a smaller unsafe primitive.
Verification design: Document the safe alternative and audit the entire invariant boundary.
Prevention controls: RUST-008, RUST-010.
External references: Technical context.
Contextual prevention example:
let (left, right) = values.split_at_mut(midpoint);
Failure fragment or claim (do not execute):
let left = unsafe { &mut *ptr };
let right = unsafe { &mut *ptr }; // Overlapping mutable references.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A safe setter permits a length larger than the backing allocation used by unchecked reads.
Failure mechanism: Safe callers can violate the internal invariant and trigger UB through an apparently safe method.
Prevention: Keep fields private and make every safe mutation preserve the unchecked operation contract.
Verification design: Fuzz sequences of safe operations under Miri, not just the unsafe function in isolation.
Prevention controls: RUST-010, RUST-018, RUST-029.
External references: Technical context.
Contextual prevention example:
if len > self.initialized {
return Err(Error::Bounds);
}
self.len = len;
Failure fragment or claim (do not execute):
pub fn set_len(&mut self, len: usize) { self.len = len; }
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: Input controls recursive depth, vector reservation or spawned tasks without admission limits.
Failure mechanism: Memory-safe code can exhaust stack, heap, descriptors or scheduling capacity.
Prevention: Apply limits before work, bound queues and define an error that does not require more unbounded resources.
Verification design: Exercise each limit and sustained rejection; inspect retained memory and live resources.
Prevention controls: RUST-025, RUST-027, RUST-049.
External references: Technical context.
Contextual prevention example:
limits.check_payload(bytes.len())?; queue.try_send(request)?;
Failure fragment or claim (do not execute):
loop {
tasks.push(spawn_work(next_input()));
}
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A pointer into a Vec remains cached while push or reserve may move its storage.
Failure mechanism: The saved address can become stale even though the Vec owner still exists.
Prevention: Reacquire views after mutation, or use storage with the required stability and a matching API.
Verification design: Force growth from small capacities and inspect all saved pointers under Miri.
Prevention controls: RUST-024, RUST-028.
External references: Technical context.
Contextual prevention example:
values.push(next); let view = values.as_slice();
Failure fragment or claim (do not execute):
let ptr = values.as_ptr();
values.push(next);
let value = unsafe { *ptr };
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A wrapper constructs a Rust owner from memory allocated by an unrelated C allocator.
Failure mechanism: Drop invokes an incompatible deallocator, layout or capacity contract.
Prevention: Keep the native owner with its matching destroy function; copy into a Rust owner when needed.
Verification design: Test allocation/deallocation pairing in a native harness and instrument failure transfers.
Prevention controls: RUST-024, RUST-034.
External references: Technical context.
Contextual prevention example:
// The native owner calls the paired native destroy function. native_owner.close()?;
Failure fragment or claim (do not execute):
let owner = unsafe { Box::from_raw(pointer_from_foreign_allocator) };
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A wrapper passes (null, 0) directly to from_raw_parts.
Failure mechanism: The slice constructor still requires a non-null aligned pointer, including empty slices.
Prevention: Return an empty slice before raw construction when the foreign contract permits null for empty input.
Verification design: Test the empty-null case through the documented wrapper; never invoke the raw API incorrectly.
Prevention controls: RUST-029.
External references: Technical context.
Contextual prevention example:
if len == 0 {
return Ok(&[]);
}
// Construct the nonempty slice only under the complete unsafe contract.
Failure fragment or claim (do not execute):
let bytes = unsafe { std::slice::from_raw_parts(std::ptr::null(), 0) };
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: An error path abandons initialized fields or drops uninitialized storage.
Failure mechanism: Manual initialization bypasses ordinary automatic cleanup until valid owners are established.
Prevention: Use safe collection construction or an initialized-prefix guard with a precise ownership state.
Verification design: Count drops for failure at each step and success after complete initialization.
Prevention controls: RUST-030, RUST-026.
External references: Technical context.
Contextual prevention example:
// Initialization guard owns only 0..initialized and drops that prefix. guard.push_initialized(value)?;
Failure fragment or claim (do not execute):
initialized = capacity; // Marks unwritten elements as owned values.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A format macro or accessor borrows a potentially unaligned packed field.
Failure mechanism: The implicit reference can violate alignment before any load that appears explicit in source.
Prevention: Copy through a permitted value access or use a reviewed raw unaligned read; prefer byte decoding.
Verification design: Inspect expanded operations and test the decoder with deliberately unaligned source placement.
Prevention controls: RUST-023, RUST-029.
External references: Technical context.
Contextual prevention example:
let word = u32::from_le_bytes([input[0], input[1], input[2], input[3]]);
Failure fragment or claim (do not execute):
let field_ref = &packed.field; // May create an unaligned reference.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A report or serialized artifact follows map iteration order.
Failure mechanism: Insertion history and randomized hashing can change ordering across runs.
Prevention: Sort output keys or choose an ordered collection whose ordering matches the format.
Verification design: Repeat with different process seeds and insertion permutations, comparing serialized bytes.
Prevention controls: RUST-057.
External references: Technical context.
Contextual prevention example:
let mut entries: Vec<_> = map.iter().collect(); entries.sort_by_key(|entry| entry.0);
Failure fragment or claim (do not execute):
for entry in &map { encode(entry); } // Claims canonical serialization.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A validated identifier derives unchecked deserialization or exposes its inner field.
Failure mechanism: A second construction path admits values rejected by the intended constructor.
Prevention: Route conversion, deserialization and Default through the same invariant owner.
Verification design: Test each public construction path with invalid and boundary values.
Prevention controls: RUST-018.
External references: Technical context.
Contextual prevention example:
let port = Port::try_from(decoded_value)?;
Failure fragment or claim (do not execute):
let port = Port(decoded_value); // Bypasses validation inside the owner.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A shared wrapper mutates UnsafeCell storage without a thread protocol.
Failure mechanism: Interior mutability permits a category of aliasing; it does not prevent concurrent data races.
Prevention: Provide exclusive access or approved atomic/locking synchronization, with a complete Sync proof.
Verification design: Model overlapping readers/writers and review the safe API for unguarded access.
Prevention controls: RUST-014, RUST-033, RUST-040.
External references: Technical context.
Contextual prevention example:
let mut guard = state.lock()?; guard.update();
Failure fragment or claim (do not execute):
unsafe { *shared_cell.get() = next }; // No exclusive-access protocol.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A reader loads a pointer while another thread removes and frees the object.
Failure mechanism: Atomic access protects the pointer slot, not the pointee; address reuse can mask replacement.
Prevention: Use a retention/reclamation protocol and account for ABA in comparisons.
Verification design: Force remove/reuse interleavings and inspect reclamation under model tests.
Prevention controls: RUST-041.
External references: Technical context.
Contextual prevention example:
let retained = shared.acquire()?; inspect(retained.as_ref());
Failure fragment or claim (do not execute):
let ptr = shared.load(Ordering::Acquire);
unsafe { inspect(&*ptr) }; // Removal can free it before use.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: An adapter reports only failure after writing a prefix, then retries the full buffer.
Failure mechanism: The destination can receive duplicate bytes or a malformed record.
Prevention: Expose progress or maintain it internally under a bounded retry contract; document non-atomic effects.
Verification design: Inject short writes, interruptions and a later failure; assert exact destination bytes.
Prevention controls: RUST-046, RUST-045.
External references: Technical context.
Contextual prevention example:
progress += writer.write(&payload[progress..])?;
Failure fragment or claim (do not execute):
writer.write(payload)?; return Ok(()); // Ignores a short write.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A success response follows an in-memory flush before required persistent synchronization.
Failure mechanism: A crash can lose or partially publish an update the caller believed durable.
Prevention: Use a platform-specific write/sync/rename or journal protocol with a recovery design.
Verification design: Crash at each persistence stage and verify recovered invariants.
Prevention controls: RUST-046.
External references: Technical context.
Contextual prevention example:
file.write_all(payload)?; file.sync_all()?; // Remaining rename/directory rules belong to the platform.
Failure fragment or claim (do not execute):
buffered.flush()?; // Claimed to guarantee durable transaction commit.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A path is checked, then an attacker replaces a symlink before the file opens.
Failure mechanism: The authorized spelling and the opened object can differ.
Prevention: Use an authority-aware open protocol and validate the actual object under platform guarantees.
Verification design: Exercise replacement races and traversal variants in an isolated directory fixture.
Prevention controls: RUST-048.
External references: Technical context.
Contextual prevention example:
let file = directory_capability.open_authorized(relative_path)?;
Failure fragment or claim (do not execute):
if path.exists() {
File::open(path)?; // Checked object can change before open.
}
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A secret-bearing type derives Debug and enters an error chain or log.
Failure mechanism: A harmless-looking diagnostic exposes credentials or key material.
Prevention: Provide redacted formatting and minimize retained secret copies; include nested error sources.
Verification design: Render success/failure diagnostics with a canary secret and assert its absence.
Prevention controls: RUST-050, RUST-004.
External references: Technical context.
Contextual prevention example:
formatter.write_str("Credentials([redacted])")
Failure fragment or claim (do not execute):
write!(formatter, "Credentials({:?})", self.secret)
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: Workspace tests pass only because a sibling enables a dependency feature.
Failure mechanism: An external consumer with fewer features fails or receives different behavior.
Prevention: Test each supported feature set and a clean consumer of the packaged crate.
Verification design: Build default, no-default and supported combinations independently.
Prevention controls: RUST-053, RUST-055.
External references: Technical context.
Contextual prevention example:
// Build the packaged leaf in a clean consumer with default features off.
Failure fragment or claim (do not execute):
// Workspace all-features succeeds, so every leaf feature set is supported.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A crate uses alloc or a panic-capable operation while claiming a bounded core.
Failure mechanism: Removing std does not enforce the claimed resource or termination contract.
Prevention: Declare CORE, ALLOC and REALTIME properties separately and audit dependencies.
Verification design: Compile the actual target without default features; measure allocations and inspect panic paths.
Prevention controls: RUST-043, RUST-025.
External references: Technical context.
Contextual prevention example:
#![no_std] // Separately check dependencies, panic paths and allocation budget.
Failure fragment or claim (do not execute):
#![no_std] extern crate alloc; // Claimed as a no-heap guarantee.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: An added dependency runs build.rs or a procedural macro with CI credentials available.
Failure mechanism: Compilation executes code on the host before any runtime sandbox applies.
Prevention: Review provenance and build authority; isolate untrusted builds and pin dependency resolution.
Verification design: Inspect build dependencies, environment access and clean-build network behavior.
Prevention controls: RUST-052, RUST-054.
External references: Technical context.
Contextual prevention example:
// Build untrusted dependencies in a credential-free isolated environment.
Failure fragment or claim (do not execute):
// Run dependency build.rs with release-signing credentials available.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A new API compiles on the developer toolchain but exceeds the declared MSRV.
Failure mechanism: Consumers on a supported compiler cannot build, even if the edition is unchanged.
Prevention: Test the declared MSRV and record edition/style edition separately.
Verification design: Compile a clean package consumer on the minimum and pinned compilers.
Prevention controls: RUST-055.
External references: Technical context.
Contextual prevention example:
// Test the declared rust-version and the pinned release compiler.
Failure fragment or claim (do not execute):
// One latest-toolchain run establishes compatibility with every edition.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: CI runs all features on one host and reports all targets qualified.
Failure mechanism: Disabled code, minimal features, other target triples and runtime paths remain untested.
Prevention: Maintain an explicit product matrix and separate compile/link/execute evidence.
Verification design: Audit the selected jobs against target triples and feature absence as well as presence.
Prevention controls: RUST-053, RUST-059.
External references: Technical context.
Contextual prevention example:
// Matrix row = target triple + feature set + compiler + execution mode.
Failure fragment or claim (do not execute):
cargo test --all-features // Claimed to execute on all CPU architectures.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A small Miri test is used to approve all safe callers of an unsafe abstraction.
Failure mechanism: The run explores only its executed paths and supported operations under its model.
Prevention: Combine invariant review, adversarial safe-client tests and complementary verification.
Verification design: Record model/toolchain, seeds, unsupported FFI and remaining coverage gaps.
Prevention controls: RUST-010, RUST-058, RUST-059.
External references: Technical context.
Contextual prevention example:
// Record Miri paths, assumptions and unsupported native calls.
Failure fragment or claim (do not execute):
// One clean Miri run proves the abstraction for all safe callers.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A specialized function executes before CPU and OS capability checks.
Failure mechanism: Unsupported target-feature execution can violate the platform contract.
Prevention: Centralize detection and safe fallback; do not use build-host features as deployment facts.
Verification design: Force each supported backend and simulate feature absence without executing forbidden instructions.
Prevention controls: RUST-059.
External references: Technical context.
Contextual prevention example:
// Detection precedes target_feature entry; tests observe backend identity.
Failure fragment or claim (do not execute):
// Compile with target-cpu=native and ship to unknown processors.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A GlobalAlloc implementation formats a message with heap-backed logging.
Failure mechanism: Allocator entry reenters itself or an internal lock, causing recursion or deadlock.
Prevention: Use a proven nonallocating diagnostic path or collect bounded counters outside the allocator.
Verification design: Instrument entry depth and test failure reporting and lazy initialization.
Prevention controls: RUST-056.
External references: Technical context.
Contextual prevention example:
// Count through a reviewed nonallocating path; format outside allocation.
Failure fragment or claim (do not execute):
let message = format!("allocation size={size}");
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: The measured result is unused, or setup, cloning and destruction move outside the claimed operation.
Failure mechanism: The optimizer may remove work or the experiment measures only a cheaper sub-operation.
Prevention: Consume results, separate kernel and lifecycle measurements and preserve reference checks.
Verification design: Inspect optimized code and compare end-to-end results and costs.
Prevention controls: RUST-009, RUST-059.
External references: Technical context.
Contextual prevention example:
let output = std::hint::black_box(candidate(std::hint::black_box(input))); check_output(output);
Failure fragment or claim (do not execute):
candidate(input); // Unused result in an isolated benchmark.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A wrapper relies on its Drop to revoke a borrowed pointer handed to a longer-lived subsystem.
Failure mechanism: Safe mem::forget can bypass Drop, leaving another safe operation able to use invalid storage.
Prevention: Make lifetime safety survive leaked values; use a borrow or a retained owner enforced by the API.
Verification design: Review deliberate forget/leak scenarios without executing UB; use compile-fail ownership tests.
Prevention controls: RUST-008, RUST-026.
External references: Technical context.
Contextual prevention example:
// Retain owned backing storage until the subsystem releases its access.
Failure fragment or claim (do not execute):
// Drop revokes access, so forgetting the guard cannot affect soundness.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: A dispatch cache keeps a code pointer after a plugin reload or topology/configuration change.
Failure mechanism: The cached capability or code lifetime no longer matches the selected operation.
Prevention: Give invalidation and reclamation one synchronized owner and a complete cache key.
Verification design: Test replacement with active users and assert generation/backend identity.
Prevention controls: RUST-051.
External references: Technical context.
Contextual prevention example:
// Hold a generation lease through the call and retire after draining users.
Failure fragment or claim (do not execute):
cached_function(); // Code library was unloaded after cache lookup.
Class: FAILURE_SCENARIO. This entry adds no independent implementation requirement.
Trigger: Markdown contains plausible Rust snippets that no Cargo target or rustdoc test discovers.
Failure mechanism: The code can drift while the repository tests remain green.
Prevention: Label complete files, contextual fragments and negative cases; extract/run complete examples separately.
Verification design: Verify the extracted file inventory and retained compiler/formatter/test results.
Prevention controls: RUST-004, RUST-058, RUST-059.
External references: Technical context.
Contextual prevention example:
// Extract named complete fences, then compile, lint and execute them.
Failure fragment or claim (do not execute):
// cargo test discovers every Markdown fence in docs automatically.
Save the following library as raw_input.rs. The wrapper permits a null pointer for empty input and rejects null for nonempty input. It cannot validate the lifetime or accessibility of an arbitrary foreign address; those facts remain caller obligations, so the function stays unsafe. The maximum admitted length also bounds the byte sum, avoiding overflow without unbounded work.
#![deny(unsafe_op_in_unsafe_fn)]
use std::slice;
const MAX_INPUT_BYTES: usize = 4096;
#[derive(Debug, PartialEq, Eq)]
pub enum InputError {
Limit,
Null,
}
/// Sums at most 4096 bytes without retaining the input.
///
/// # Errors
/// Returns `Limit` if the length exceeds the budget, and `Null` for a null
/// pointer with a nonzero admitted length. Empty input returns zero.
///
/// # Safety
/// If `data` is non-null and `len` is in 1..=4096, `data` must refer to
/// `len` initialized bytes in one live allocation. The bytes must remain
/// readable and must not be mutated for this call, including by foreign
/// threads or a device. No pointer validity obligation applies to inputs
/// that this function rejects before reading, or to empty input.
///
/// # Examples
/// ```
/// use raw_input::sum_raw;
///
/// let bytes = [1_u8, 2, 3];
/// // SAFETY: The array remains live and immutable throughout the call.
/// let result = unsafe { sum_raw(bytes.as_ptr(), bytes.len()) };
/// assert_eq!(result, Ok(6));
/// ```
pub unsafe fn sum_raw(data: *const u8, len: usize) -> Result<u64, InputError> {
if len > MAX_INPUT_BYTES {
return Err(InputError::Limit);
}
if len == 0 {
return Ok(0);
}
if data.is_null() {
return Err(InputError::Null);
}
// SAFETY: The checks establish a non-null pointer and a bounded nonzero
// length below isize::MAX. u8 has alignment 1. The caller guarantees one
// live allocation, initialized readable bytes and no mutation during
// this call. The slice stays within this call and is not retained.
let bytes = unsafe { slice::from_raw_parts(data, len) };
Ok(bytes.iter().map(|byte| u64::from(*byte)).sum())
}
#[cfg(test)]
mod tests {
use super::{InputError, MAX_INPUT_BYTES, sum_raw};
use std::ptr;
#[test]
fn null_empty_is_accepted() {
// SAFETY: Empty input imposes no pointer validity obligation.
assert_eq!(unsafe { sum_raw(ptr::null(), 0) }, Ok(0));
}
#[test]
fn null_nonempty_is_rejected() {
// SAFETY: Null input is rejected before any reference or read.
assert_eq!(unsafe { sum_raw(ptr::null(), 1) }, Err(InputError::Null));
}
#[test]
fn oversized_input_is_rejected_before_pointer_use() {
// SAFETY: The length rejection precedes any pointer use.
let result = unsafe { sum_raw(ptr::null(), MAX_INPUT_BYTES + 1) };
assert_eq!(result, Err(InputError::Limit));
}
#[test]
fn admitted_boundary_has_a_bounded_sum() {
let bytes = [255_u8; MAX_INPUT_BYTES];
// SAFETY: This live immutable array contains the full admitted range.
let result = unsafe { sum_raw(bytes.as_ptr(), bytes.len()) };
assert_eq!(result, Ok(1_044_480));
}
}
// EOF
This example demonstrates an unsafe Rust boundary, not a complete C export. A C-facing adapter must define calling convention, result representation and symbol ownership separately. Tests only call the function within its documented safety contract; they do not pass dangling or fabricated non-null pointers.
For an independent negative lifetime test, the following complete snippet must fail with a diagnostic about returning a value that references local storage. Check that diagnostic in the harness. Any unrelated parser or missing-import error is a failed test setup, not a successful lifetime check.
fn escaped_slice() -> &'static [u8] {
let bytes = [1_u8, 2, 3];
&bytes
}
fn main() {
let _ = escaped_slice();
}
Use the source register for revision and scope. The following primary API references support the particularly sensitive boundary cases:
| Entries | Technical reference |
|---|---|
| RPIT-008, RPIT-026, RPIT-034 | Pointer safety and provenance. |
| RPIT-010, RPIT-029 | MaybeUninit initialization and drop contracts. |
| RPIT-011, RPIT-028 | Raw slice construction. |
| RPIT-012, RPIT-030 | Type representation. |
| RPIT-015, RPIT-033 | Send and Sync. |
| RPIT-017 | Pin and structural pinning. |
| RPIT-003 | Tokio shared state. |
| RPIT-004 | Mutex poisoning. |
| RPIT-018 | Tokio select cancellation safety. |
| RPIT-020 | Atomic ordering. |
| RPIT-035 | Partial Write behavior. |
| RPIT-039 | Cargo feature unification. |
| RPIT-044 | Miri scope and limitations. |
| RPIT-046 | GlobalAlloc safety. |