PangeaOS Code Snippets & Reference Implementations v1.2.3
Coding-Ready #![no_std] Rust & Assembly Design Patterns (§1–§8) — Fault Localization, Absolute PKRU Masks, Non-Local Scheduler Continuation & DoS Scenarios
Purpose: Coding-ready
#![no_std]design patterns for implementing fault localization, DoS resilience, Two-Stack non-local transitions, and PFN state management in PangeaOS v1.2.3.
Note: Hardware state transitions cannot be safely implemented by standalone Rust functions alone; the assembly gates in §5 must be paired with the.text.gate_asm/.text.isr_entrylinker sections (linker.ld) andbincheckverification.
1. Fault Classes, Recovery Actions & const fn Absolute PKRU Masks (fault-core)
F3ProtectionUncertain evaluates whether the target CPU or device can be safely isolated, escalating to GlobalFailStop if access revocation cannot be guaranteed rather than blindly converting every timeout into a full halt or reusing unconfirmed frames. L2 actions are determined by cause-specific policy (first CPU overrun preempts, repeated overrun quarantines; memory exhaustion rejects allocation; IPC full applies backpressure/drop).
#![no_std]
#![forbid(unsafe_code)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FaultClass {
/// Malformed request, bounds violation, or invalid opcode. OS invariants intact.
L0Request,
/// Domain panic, local CPU exception (#PF/#GP/#UD/#CP), SFI rejection, or budget overrun.
L1Domain,
/// CPU, memory, IPC, or interrupt quota exhaustion.
L2Resource,
/// Fault isolatable by halting a specific device or subsystem.
L3Subsystem,
/// Loss of Domain 0, trusted gate, or shared isolation invariants.
F1CoreIntegrity,
/// Unrecoverable hardware fault or unverified shared state integrity (#MC).
F2HardwareFatal,
/// Unconfirmed completion of TLB or IOTLB protection updates.
F3ProtectionUncertain,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RecoveryAction {
RejectRequest,
PreemptDomain,
QuarantineDomain,
Backpressure,
EnforceResourcePolicy,
IsolateDevice,
RestrictedMode,
PinResourcesAndQuarantine,
GlobalFailStop,
}
pub const fn action_for(class: FaultClass) -> RecoveryAction {
match class {
FaultClass::L0Request => RecoveryAction::RejectRequest,
FaultClass::L1Domain => RecoveryAction::QuarantineDomain,
FaultClass::L2Resource => RecoveryAction::EnforceResourcePolicy,
FaultClass::L3Subsystem => RecoveryAction::IsolateDevice,
FaultClass::F1CoreIntegrity | FaultClass::F2HardwareFatal => {
RecoveryAction::GlobalFailStop
}
FaultClass::F3ProtectionUncertain => {
RecoveryAction::PinResourcesAndQuarantine
}
}
}
/// PKRU bit definitions (For key k: bit 2k = AD, bit 2k+1 = WD)
pub const PKRU_RW: u32 = 0b00;
pub const PKRU_RO: u32 = 0b10; // AD=0, WD=1
pub const PKRU_NA: u32 = 0b11; // AD=1, WD=1
/// Generates the compile-time absolute PKRU mask for Domain d (1..=12).
/// Only K_d is RW; K14 (IPC Control) is RO; all other keys (K0, K13, K15, other domains) are NA.
pub const fn pkru_for_domain(domain_id: u16) -> u32 {
assert!(domain_id >= 1 && domain_id <= 12, "Domain ID out of bounds (1..=12)");
let mut mask: u32 = 0xFFFF_FFFF;
mask &= !(0b11 << (domain_id as u32 * 2));
mask = (mask & !(0b11 << (14 * 2))) | (PKRU_RO << (14 * 2));
mask
}
/// Absolute PKRU mask for normal Domain 0 execution (K0=RW, K13=RO, K14=RW, K1..12 & K15=NA)
pub const PKRU_KERNEL_DEFAULT: u32 = {
let mut mask: u32 = 0xFFFF_FFFF;
mask &= !(0b11 << (0 * 2));
mask = (mask & !(0b11 << (13 * 2))) | (PKRU_RO << (13 * 2));
mask &= !(0b11 << (14 * 2));
mask
};
/// Absolute PKRU mask exclusively for inside the K13 PT Update Gate (K0=RW, K13=RW, K14=RW)
pub const PKRU_KERNEL_PT_UPDATE: u32 = PKRU_KERNEL_DEFAULT & !(0b11 << (13 * 2));
2. IPC Counter Snapshot Verification (pangea-ring)
After snapshotting head and tail, shared memory must never be re-read to alter the processed value; all descriptor fields are copied into local variables before validation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RingError {
InvalidCapacity,
CapacityExceeded,
InvalidDescriptorLength,
StaleGeneration,
}
/// Snapshots untrusted head/tail counters once before validation.
/// Capacity need not be a power of two, but a fixed upper bound is enforced per ring.
pub fn checked_pending(
head_snapshot: u32,
tail_snapshot: u32,
capacity: u32,
) -> Result<u32, RingError> {
if capacity == 0 {
return Err(RingError::InvalidCapacity);
}
// wrapping_sub handles u32 counter wrap-around deterministically; reject if delta > capacity.
let pending = tail_snapshot.wrapping_sub(head_snapshot);
if pending > capacity {
return Err(RingError::CapacityExceeded);
}
Ok(pending)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_attacker_controlled_large_delta() {
assert_eq!(checked_pending(10, 10 + 257, 256), Err(RingError::CapacityExceeded));
}
#[test]
fn accepts_wrapping_counter_when_delta_is_small() {
assert_eq!(checked_pending(u32::MAX - 3, 2, 8), Ok(6));
}
}
3. Generational Capability Handle Validation (cap-core)
This type alone does not form a security boundary; K0 protection of the ledger table, synchronized revocation across cores, trusted acquisition of current_domain from K0 Per-CPU state, and handle forgery checks are mandatory.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CapabilityHandle {
pub slot: u32,
pub generation: u32,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CapabilityError {
OutOfRange,
StaleGeneration,
WrongOwner,
RightsDenied,
Revoked,
}
bitflags::bitflags! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Rights: u32 {
const READ = 1 << 0;
const WRITE = 1 << 1;
const DMA = 1 << 2;
const RESET = 1 << 3;
}
}
pub struct CapabilityEntry {
pub generation: u32,
pub owner_domain: u16,
pub rights: Rights,
pub live: bool,
}
/// Callable exclusively from Domain 0 trusted gate paths.
pub fn validate_capability(
handle: CapabilityHandle,
current_domain: u16,
requested: Rights,
table: &[CapabilityEntry],
) -> Result<(), CapabilityError> {
let entry = table.get(handle.slot as usize).ok_or(CapabilityError::OutOfRange)?;
if !entry.live { return Err(CapabilityError::Revoked); }
if entry.generation != handle.generation { return Err(CapabilityError::StaleGeneration); }
if entry.owner_domain != current_domain { return Err(CapabilityError::WrongOwner); }
if !entry.rights.contains(requested) { return Err(CapabilityError::RightsDenied); }
Ok(())
}
4. Per-Domain Resource Quota Accounting (fault-core / alloc-buddy)
Enforcing CPU budgets requires pairing this accounting logic with the APIC timer / NMI watchdog, exclusive access to K0 quota state, accounting across CPU migrations, and refunding upon deallocation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum QuotaError {
CpuBudgetExceeded,
MemoryBudgetExceeded,
QueueFull,
}
pub struct DomainQuota {
pub cpu_budget_ns: u64,
pub cpu_used_ns: u64,
pub memory_limit_bytes: u64,
pub memory_used_bytes: u64,
pub queue_limit: u32,
pub queue_used: u32,
}
impl DomainQuota {
pub fn charge_cpu(&mut self, elapsed_ns: u64) -> Result<(), QuotaError> {
let next = self.cpu_used_ns.saturating_add(elapsed_ns);
if next > self.cpu_budget_ns {
return Err(QuotaError::CpuBudgetExceeded);
}
self.cpu_used_ns = next;
Ok(())
}
pub fn reserve_memory(&mut self, bytes: u64) -> Result<(), QuotaError> {
let next = self.memory_used_bytes.checked_add(bytes)
.ok_or(QuotaError::MemoryBudgetExceeded)?;
if next > self.memory_limit_bytes {
return Err(QuotaError::MemoryBudgetExceeded);
}
self.memory_used_bytes = next;
Ok(())
}
pub fn reserve_queue_slot(&mut self) -> Result<(), QuotaError> {
if self.queue_used >= self.queue_limit {
return Err(QuotaError::QueueFull);
}
self.queue_used += 1;
Ok(())
}
}
5. Localized Panic Pattern & Non-Local Continuation Assembly (percpu / gate-asm)
Immediately after pangea_panic_dispatch_trusted returns control to the Domain 0 scheduler continuation, Domain 0 must execute the full §9.1 domain quarantine sequence (SMP halt IPIs, capability revocation, IOMMU invalidation, and PFN quarantine).
#![no_std]
use core::panic::PanicInfo;
use core::arch::global_asm;
/// Scheduler recovery continuation stored in K0 Per-CPU state.
#[repr(C)]
pub struct SchedulerContinuation {
pub rsp: u64,
pub rbp: u64,
pub rbx: u64,
pub r12: u64,
pub r13: u64,
pub r14: u64,
pub r15: u64,
pub return_rip: u64,
}
/// K0-protected Per-CPU state record bound at GS:0x00
#[repr(C, align(4096))]
pub struct TrustedPerCpuState {
pub self_ptr: u64, // GS:0x00
pub k0_priv_rsp: u64, // GS:0x08 (Two-Stack IST pivot target)
pub active_domain_id: u16, // GS:0x10 (0 = Domain 0, 1..12 = Domain)
pub reentrancy_depth: u16, // GS:0x12
pub active_domain_gen: u32, // GS:0x14
pub sched_cont: SchedulerContinuation, // GS:0x18..0x58
}
unsafe extern "C" {
/// Trusted assembly determines the active subject from K0 Per-CPU state,
/// performing a non-local jump to quarantine if in a domain, or to the
/// fatal halt path if in Domain 0.
fn pangea_panic_dispatch_trusted() -> !;
}
#[panic_handler]
fn panic(_info: &PanicInfo<'_>) -> ! {
// Never reference domain-writable stacks or self-reported domain IDs.
unsafe { pangea_panic_dispatch_trusted() }
}
global_asm!(
".section .text.gate_asm,\"ax\",@progbits",
".global pangea_panic_dispatch_trusted",
"pangea_panic_dispatch_trusted:",
" endbr64",
" cli",
" cld",
// 1. Force PKRU to absolute PKRU_KERNEL_DEFAULT (0xFFFCFFFF) before touching K0 memory
" mov eax, 0xFFFCFFFF",
" xor ecx, ecx",
" xor edx, edx",
" wrpkru",
// 2. Inspect active_domain_id at GS:0x10 (0 = Domain 0 invariant violation -> F1 Fail-Stop)
" movzx eax, word ptr gs:[0x10]",
" test eax, eax",
" jz pangea_fatal_core_halt",
// 3. Domain 1..12 localized panic: reset active_domain_id to 0 and jump to SchedulerContinuation
" mov word ptr gs:[0x10], 0",
" mov rsp, qword ptr gs:[0x18]",
" mov rbp, qword ptr gs:[0x20]",
" mov rbx, qword ptr gs:[0x28]",
" mov r12, qword ptr gs:[0x30]",
" mov r13, qword ptr gs:[0x38]",
" mov r14, qword ptr gs:[0x40]",
" mov r15, qword ptr gs:[0x48]",
" mov rax, 1", // Return code 1 = Domain Aborted via Panic
" jmp qword ptr gs:[0x50]",
".global pangea_fatal_core_halt",
"pangea_fatal_core_halt:",
" cli",
"2:",
" hlt",
" jmp 2b"
);
6. Lifecycle State Machine Types (DomainState & PfnState)
State transitions are protected by Domain 0 synchronization primitives. Transitioning from PfnState::Quarantine to Erased is permitted if and only if tlb_ack_pending == false && iotlb_ack_pending == false.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DomainState {
Created,
Verified,
Ready,
Running,
Quiescing,
Quarantined,
Reinitializing,
PermanentlyDisabled,
}
pub const fn may_transition(from: DomainState, to: DomainState) -> bool {
use DomainState::*;
matches!((from, to),
(Created, Verified) |
(Verified, Ready) |
(Ready, Running) |
(Running, Quiescing) |
(Quiescing, Quarantined) |
(Quarantined, Reinitializing) |
(Reinitializing, Verified) |
(Quarantined, PermanentlyDisabled))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PfnState {
Free,
Allocated { domain: u16, generation: u32 },
DmaPinned { domain: u16, generation: u32, pin_count: u16 },
Quarantine { prev_domain: u16, tlb_ack_pending: bool, iotlb_ack_pending: bool },
Erased,
Guard,
Reserved,
PageTable { level: u8 },
KernelImage,
ShadowStack { domain: u16 },
}
7. DoS Regression Pseudo-Scenarios
GIVEN: domain-7 is running, CPU budget is enforced by APIC timer
WHEN: domain-7 enters a non-yielding infinite loop
THEN: timer interrupt enters trusted IST stack and pivots to k0_priv_rsp
AND: scheduler reads domain ID from protected K0 per-CPU state
AND: domain-7 is preempted; repeated overrun causes quarantine
AND: other eligible domains continue to make progress
AND: no global panic/reboot occurs
GIVEN: domain-4 publishes tail such that wrapping_sub(tail, head) > capacity
WHEN: consumer snapshots counters and validates delta
THEN: descriptor is rejected, per-domain strike counter increments
AND: no unbounded loop or out-of-range index is used
AND: the OS remains alive
GIVEN: TLB shootdown acknowledgement cannot be obtained
WHEN: domain memory re-keying/release is requested
THEN: affected frames remain pinned in PfnState::Quarantine and are not cleared or reused
AND: affected domain/core is quarantined if safely possible
AND: if access revocation cannot be guaranteed, enter F3 policy
8. Strictly Prohibited Implementation Practices
- Using
panic!as control flow for external input errors. - Restoring
PKRU/PKRSor returnRIP/RSPfrom a domain-writable stack. - Claiming
WRPKRUis sealed solely through raw unaligned byte-sequence searches. - Overlooking
PKRUrestoration viaXRSTOR/ XSAVE state. - Assuming per-peer Read-Only / Read-Write page permissions exist simultaneously on a single shared SASOS page table.
- Freeing, zeroizing, or reusing physical frames before TLB and IOTLB invalidations complete.
- Allowing unbounded domain restarts, audit logs, queues, or recovery recursion.
- Reporting security features as "fully supported" before physical hardware verification is completed.