Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-kernel/src/task_runtime.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-kernel / src / task_runtime.rs` 931 lines ยท 31352 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! EL0 execution of one admitted, loaded artifact task. 17 //! 18 //! The loader (`artifact_loader`) builds the private address space and the 19 //! capability table; this module only enters EL0 with that state, dispatches 20 //! the task's syscalls against its own table, enforces the admitted CPU, 21 //! elapsed-time and syscall budgets, and returns control to the kernel on 22 //! exit, fault, timeout, bad syscall, or budget overrun. It has no parser, 23 //! signature, or policy responsibilities. 24 //! 25 //! Entry ABI (v0 loader, ABI v1 register forms): 26 //! - `x0` = VA of the task's handle array (u64 register-form handles, in 27 //! grant order) at the top of its stack; `x1` = handle count; 28 //! `x2` = data section base VA; `x3` = admitted data memory length. 29 //! - Every other general-purpose and SIMD/FP register is zero. 30 //! - `sp_el0` is 16-byte aligned below the handle array. 31 //! 32 //! Syscalls (`svc #0`, number in `x8`): 33 //! - `SYS_EXIT` (2): `x0` = exit code. Ends the task. 34 //! - `SYS_OBJECT_READ` (6): `x0` = handle, `x1` = byte offset (8-aligned). 35 //! Returns the u64 at that offset in `x0`, or `SYSCALL_DENIED`. 36 //! - `SYS_OBJECT_WRITE` (7): `x0` = handle, `x1` = offset, `x2` = value. 37 //! Returns 0 or `SYSCALL_DENIED`. 38 //! - Any other number terminates the task with `ExecutionStatus::BadSyscall`. 39 //! 40 //! A capability-table resource value is the task's grant index; kind, object 41 //! id, byte range and operation/byte budgets come from that grant. 42 43 use crate::abi::{Handle, ResourceKind}; 44 use crate::admission::GrantedCapability; 45 use crate::caps::{CapTable, Rights}; 46 use core::sync::atomic::{AtomicBool, Ordering}; 47 48 pub const SYS_EXIT: u64 = 2; 49 pub const SYS_OBJECT_READ: u64 = 6; 50 pub const SYS_OBJECT_WRITE: u64 = 7; 51 pub const SYSCALL_DENIED: u64 = u64::MAX; 52 53 /// Capability slots per loaded task (== artifact v0 maximum). 54 pub const TASK_CAPABILITIES: usize = 16; 55 56 /// Kernel-owned object reachable by SEED-0B qualification artifacts. 57 pub const SEED_OBJECT_ID: u32 = 1; 58 pub const SEED_OBJECT_WORDS: [u64; 4] = [ 59 0xa1e0_5eed_0000_0001, 60 0xa1e0_5eed_0000_0002, 61 0xa1e0_5eed_0000_0003, 62 0xa1e0_5eed_0000_0004, 63 ]; 64 /// Size of the seed object in bytes. 65 pub const SEED_OBJECT_BYTES: u64 = (SEED_OBJECT_WORDS.len() * 8) as u64; 66 67 /// ASID used for loaded artifact tasks (M3 demos use 1). 68 pub const TASK_ASID: u16 = 2; 69 70 /// SPSR used when a termination returns control to EL1h with DAIF masked. 71 const SPSR_EL1H_MASKED: u64 = 0x3c5; 72 73 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 74 pub enum ExecutionStatus { 75 NotRun, 76 Exited(u64), 77 Timeout, 78 Fault { esr: u64, far: u64, elr: u64 }, 79 BadSyscall(u64), 80 ResourceOverrun, 81 } 82 83 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 84 pub struct TaskOutcome { 85 pub status: ExecutionStatus, 86 pub syscalls: u32, 87 pub object_reads_ok: u32, 88 pub denials: u32, 89 /// Denied `SYS_OBJECT_WRITE` calls (subset of `denials`). 90 pub write_denials: u32, 91 /// Denials because the handle did not resolve in the task's table: 92 /// forged, never-issued, stale, or zero (subset of `denials`). 93 pub invalid_handle_denials: u32, 94 pub elapsed_ticks: u64, 95 } 96 97 impl TaskOutcome { 98 pub const fn not_run() -> Self { 99 Self { 100 status: ExecutionStatus::NotRun, 101 syscalls: 0, 102 object_reads_ok: 0, 103 denials: 0, 104 write_denials: 0, 105 invalid_handle_denials: 0, 106 elapsed_ticks: 0, 107 } 108 } 109 } 110 111 /// Why one object access was refused. 112 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 113 pub enum Denial { 114 /// The handle does not resolve in this task's capability table. 115 InvalidHandle, 116 /// The handle resolves but lacks the right, or names another resource. 117 Authority, 118 /// Offset, alignment, grant range, or object size. 119 Bounds, 120 /// The grant's operation or byte budget is spent. 121 Budget, 122 } 123 124 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 125 pub struct TaskBudget { 126 pub cpu_ticks: u64, 127 pub elapsed_ticks: u64, 128 pub syscalls: u32, 129 } 130 131 impl TaskBudget { 132 /// With one task on one core, CPU time never exceeds elapsed time, so the 133 /// tighter of the two budgets is the single wall-clock limit. 134 pub const fn tick_limit(self) -> u64 { 135 if self.cpu_ticks < self.elapsed_ticks { 136 self.cpu_ticks 137 } else { 138 self.elapsed_ticks 139 } 140 } 141 } 142 143 /// Everything the runtime needs to run one task. Built by the loader. 144 pub struct TaskContext<'a> { 145 /// Physical address of the task's private L0 table. 146 pub root: u64, 147 pub entry_pc: u64, 148 pub stack_pointer: u64, 149 pub args: [u64; 4], 150 pub capabilities: &'a mut CapTable, 151 pub grants: &'a [Option], 152 pub budget: TaskBudget, 153 } 154 155 /// Counter ticks elapsed since `start`, correct across one counter wrap. 156 pub const fn elapsed_since(start: u64, now: u64) -> u64 { 157 now.wrapping_sub(start) 158 } 159 160 /// True once `limit` ticks have passed since `start`. 161 pub const fn deadline_expired(start: u64, now: u64, limit: u64) -> bool { 162 elapsed_since(start, now) >= limit 163 } 164 165 /// Consumption of one grant's operation and byte budgets. 166 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] 167 pub struct GrantUsage { 168 pub operations: u32, 169 pub bytes: u64, 170 } 171 172 /// What the dispatcher must do with the trapped task after a syscall. 173 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 174 pub enum SyscallAction { 175 /// Resume EL0 with this value in `x0`. 176 Return(u64), 177 /// End the task with this status. 178 Terminate(ExecutionStatus), 179 } 180 181 /// Host-testable accounting and authority state of the running task. 182 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 183 pub struct RuntimeState { 184 pub budget: TaskBudget, 185 pub start: u64, 186 pub syscalls: u32, 187 pub object_reads_ok: u32, 188 pub denials: u32, 189 pub write_denials: u32, 190 pub invalid_handle_denials: u32, 191 pub usage: [GrantUsage; TASK_CAPABILITIES], 192 pub object: [u64; 4], 193 } 194 195 impl RuntimeState { 196 pub const fn new(budget: TaskBudget, start: u64) -> Self { 197 Self { 198 budget, 199 start, 200 syscalls: 0, 201 object_reads_ok: 0, 202 denials: 0, 203 write_denials: 0, 204 invalid_handle_denials: 0, 205 usage: [GrantUsage { 206 operations: 0, 207 bytes: 0, 208 }; TASK_CAPABILITIES], 209 object: SEED_OBJECT_WORDS, 210 } 211 } 212 213 pub const fn expired(&self, now: u64) -> bool { 214 deadline_expired(self.start, now, self.budget.tick_limit()) 215 } 216 217 /// Decide one `svc` from EL0. `imm` is the SVC immediate (ESR ISS[15:0]), 218 /// `number` is `x8`, `args` are `x0..x2`, `now` the counter value. 219 pub fn syscall( 220 &mut self, 221 caps: &CapTable, 222 grants: &[Option], 223 imm: u16, 224 number: u64, 225 args: [u64; 3], 226 now: u64, 227 ) -> SyscallAction { 228 self.syscalls = self.syscalls.saturating_add(1); 229 if self.syscalls > self.budget.syscalls { 230 return SyscallAction::Terminate(ExecutionStatus::ResourceOverrun); 231 } 232 if self.expired(now) { 233 return SyscallAction::Terminate(ExecutionStatus::Timeout); 234 } 235 if imm != 0 { 236 return SyscallAction::Terminate(ExecutionStatus::BadSyscall(number)); 237 } 238 match number { 239 SYS_EXIT => SyscallAction::Terminate(ExecutionStatus::Exited(args[0])), 240 SYS_OBJECT_READ => { 241 match self.object_access(caps, grants, args[0], Rights::READ, args[1]) { 242 Ok(word) => { 243 self.object_reads_ok = self.object_reads_ok.saturating_add(1); 244 SyscallAction::Return(self.object[word]) 245 } 246 Err(why) => self.deny(why, false), 247 } 248 } 249 SYS_OBJECT_WRITE => { 250 match self.object_access(caps, grants, args[0], Rights::WRITE, args[1]) { 251 Ok(word) => { 252 self.object[word] = args[2]; 253 SyscallAction::Return(0) 254 } 255 Err(why) => self.deny(why, true), 256 } 257 } 258 other => SyscallAction::Terminate(ExecutionStatus::BadSyscall(other)), 259 } 260 } 261 262 fn deny(&mut self, why: Denial, write: bool) -> SyscallAction { 263 self.denials = self.denials.saturating_add(1); 264 if write { 265 self.write_denials = self.write_denials.saturating_add(1); 266 } 267 if why == Denial::InvalidHandle { 268 self.invalid_handle_denials = self.invalid_handle_denials.saturating_add(1); 269 } 270 SyscallAction::Return(SYSCALL_DENIED) 271 } 272 273 /// Resolve and charge one 8-byte object access. Returns the object word 274 /// index, or `None` for any authority, bounds, or budget failure (in 275 /// which case nothing is charged). 276 fn object_access( 277 &mut self, 278 caps: &CapTable, 279 grants: &[Option], 280 raw_handle: u64, 281 right: Rights, 282 offset: u64, 283 ) -> Result { 284 let handle = Handle::from_raw(raw_handle).map_err(|_| Denial::InvalidHandle)?; 285 let index = match caps.lookup(handle, right) { 286 Ok(index) => index as usize, 287 Err(crate::caps::CapError::MissingRights) => return Err(Denial::Authority), 288 Err(_) => return Err(Denial::InvalidHandle), 289 }; 290 let grant = grants 291 .get(index) 292 .copied() 293 .flatten() 294 .ok_or(Denial::Authority)?; 295 if grant.resource.kind() != ResourceKind::Object 296 || grant.resource.id() != SEED_OBJECT_ID 297 || !grant.rights.contains(right) 298 { 299 return Err(Denial::Authority); 300 } 301 let end = offset.checked_add(8).ok_or(Denial::Bounds)?; 302 let grant_end = grant 303 .bounds 304 .byte_offset 305 .checked_add(grant.bounds.byte_length) 306 .ok_or(Denial::Bounds)?; 307 if offset & 7 != 0 308 || offset < grant.bounds.byte_offset 309 || end > grant_end 310 || end > SEED_OBJECT_BYTES 311 { 312 return Err(Denial::Bounds); 313 } 314 let usage = self.usage.get_mut(index).ok_or(Denial::Authority)?; 315 let bytes = usage.bytes.checked_add(8).ok_or(Denial::Budget)?; 316 if usage.operations >= grant.bounds.max_operations || bytes > grant.bounds.max_bytes { 317 return Err(Denial::Budget); 318 } 319 usage.operations += 1; 320 usage.bytes = bytes; 321 Ok((offset / 8) as usize) 322 } 323 324 fn outcome(&self, status: ExecutionStatus, now: u64) -> TaskOutcome { 325 TaskOutcome { 326 status, 327 syscalls: self.syscalls, 328 object_reads_ok: self.object_reads_ok, 329 denials: self.denials, 330 write_denials: self.write_denials, 331 invalid_handle_denials: self.invalid_handle_denials, 332 elapsed_ticks: elapsed_since(self.start, now), 333 } 334 } 335 } 336 337 // ---- Active-task state (EL1, single core) --------------------------------- 338 339 struct Active { 340 state: RuntimeState, 341 caps: *const CapTable, 342 grants: *const Option, 343 grant_count: usize, 344 status: ExecutionStatus, 345 } 346 347 static TASK_ACTIVE: AtomicBool = AtomicBool::new(false); 348 static mut ACTIVE: Option = None; 349 350 /// True while a loaded task owns EL0. Exception dispatchers use this to route 351 /// EL0 exceptions here instead of the M3 demo paths. 352 pub fn is_active() -> bool { 353 TASK_ACTIVE.load(Ordering::Acquire) 354 } 355 356 /// # Safety 357 /// EL1 only, single core; no other live reference to `ACTIVE`. 358 unsafe fn active() -> Option<&'static mut Active> { 359 unsafe { (*core::ptr::addr_of_mut!(ACTIVE)).as_mut() } 360 } 361 362 fn terminate_frame(elr: &mut u64, spsr: &mut u64) { 363 *elr = task_resume_address(); 364 *spsr = SPSR_EL1H_MASKED; 365 } 366 367 fn record_termination(active: &mut Active, status: ExecutionStatus) { 368 if active.status == ExecutionStatus::NotRun { 369 active.status = status; 370 } 371 } 372 373 /// Lower-EL synchronous exception while a task is active. Called from 374 /// `user::aienos_lower_el_sync_dispatcher`. 375 /// 376 /// # Safety 377 /// Called only from the lower-EL synchronous trampoline with a complete frame. 378 pub unsafe fn dispatch_sync(frame: &mut crate::user::TrapFrame, esr: u64, far: u64) { 379 let Some(active) = (unsafe { active() }) else { 380 terminate_frame(&mut frame.elr_el1, &mut frame.spsr_el1); 381 return; 382 }; 383 let now = counter(); 384 let ec = (esr >> 26) & 0x3f; 385 let action = if ec == 0x15 { 386 let caps = unsafe { &*active.caps }; 387 let grants = unsafe { core::slice::from_raw_parts(active.grants, active.grant_count) }; 388 active.state.syscall( 389 caps, 390 grants, 391 (esr & 0xffff) as u16, 392 frame.x[8], 393 [frame.x[0], frame.x[1], frame.x[2]], 394 now, 395 ) 396 } else { 397 SyscallAction::Terminate(ExecutionStatus::Fault { 398 esr, 399 far, 400 elr: frame.elr_el1, 401 }) 402 }; 403 match action { 404 SyscallAction::Return(value) => frame.x[0] = value, 405 SyscallAction::Terminate(status) => { 406 record_termination(active, status); 407 terminate_frame(&mut frame.elr_el1, &mut frame.spsr_el1); 408 } 409 } 410 } 411 412 /// Timer tick taken from EL0 while a task is active. Called from the IRQ 413 /// dispatcher after it acknowledged, re-armed and ended INTID 30. 414 /// 415 /// # Safety 416 /// Called only from the IRQ dispatcher with a complete frame. 417 pub unsafe fn on_timer_tick(frame: &mut crate::thread::TrapFrame) { 418 // Only an interrupted EL0 context (SPSR.M[3:0] == EL0t) is terminated. 419 if frame.spsr_el1 & 0xf != 0 { 420 return; 421 } 422 let Some(active) = (unsafe { active() }) else { 423 return; 424 }; 425 if active.state.expired(counter()) { 426 record_termination(active, ExecutionStatus::Timeout); 427 terminate_frame(&mut frame.elr_el1, &mut frame.spsr_el1); 428 } 429 } 430 431 fn counter() -> u64 { 432 #[cfg(target_arch = "aarch64")] 433 { 434 crate::timer::TimerRegisters::counter(&crate::timer::Aarch64TimerRegisters) 435 } 436 #[cfg(not(target_arch = "aarch64"))] 437 { 438 0 439 } 440 } 441 442 /// Enter EL0 with `task` and return when it ends for any reason. Restores 443 /// `kernel_root` in TTBR0, disables the timer and masks IRQs before returning. 444 /// 445 /// # Safety 446 /// EL1, single core, vectors installed, GIC/timer initialised; `task.root` 447 /// must be a complete private translation tree built by the loader. 448 pub unsafe fn run(task: TaskContext<'_>, kernel_root: usize) -> TaskOutcome { 449 #[cfg(target_arch = "aarch64")] 450 { 451 unsafe { run_inner(task, kernel_root) } 452 } 453 #[cfg(not(target_arch = "aarch64"))] 454 { 455 let _ = (task, kernel_root); 456 TaskOutcome::not_run() 457 } 458 } 459 460 #[cfg(target_arch = "aarch64")] 461 unsafe fn run_inner(task: TaskContext<'_>, kernel_root: usize) -> TaskOutcome { 462 use crate::timer::{Aarch64TimerRegisters, TimerRegisters}; 463 464 let grant_count = task.grants.len().min(TASK_CAPABILITIES); 465 let mut timer = Aarch64TimerRegisters; 466 let hz = timer.frequency(); 467 let interval = if hz >= 100 { hz / 100 } else { 625_000 }; 468 let start = timer.counter(); 469 unsafe { 470 *core::ptr::addr_of_mut!(ACTIVE) = Some(Active { 471 state: RuntimeState::new(task.budget, start), 472 caps: task.capabilities as *const _, 473 grants: task.grants.as_ptr(), 474 grant_count, 475 status: ExecutionStatus::NotRun, 476 }); 477 } 478 TASK_ACTIVE.store(true, Ordering::Release); 479 480 unsafe { set_ttbr0(task.root | (u64::from(TASK_ASID) << 48)) }; 481 timer.set_compare(start.wrapping_add(interval)); 482 timer.enable_timer(true); 483 let args = task.args; 484 unsafe { aienos_task_enter(task.entry_pc, task.stack_pointer, args.as_ptr()) }; 485 // Back at EL1h with DAIF masked (SPSR 0x3c5 on every termination). 486 unsafe { core::arch::asm!("msr daifset, #2", "isb", options(nostack)) }; 487 timer.enable_timer(false); 488 unsafe { set_ttbr0(kernel_root as u64) }; 489 let now = timer.counter(); 490 491 TASK_ACTIVE.store(false, Ordering::Release); 492 let active = unsafe { (*core::ptr::addr_of_mut!(ACTIVE)).take() }; 493 match active { 494 Some(active) => active.state.outcome(active.status, now), 495 None => TaskOutcome::not_run(), 496 } 497 } 498 499 #[cfg(target_arch = "aarch64")] 500 unsafe fn set_ttbr0(value: u64) { 501 unsafe { 502 core::arch::asm!( 503 "dsb ish", 504 "msr ttbr0_el1, {0}", 505 "isb", 506 "tlbi vmalle1", 507 "dsb ish", 508 "isb", 509 in(reg) value, 510 options(nostack) 511 ); 512 } 513 } 514 515 fn task_resume_address() -> u64 { 516 #[cfg(target_arch = "aarch64")] 517 { 518 core::ptr::addr_of!(aienos_task_resume) as u64 519 } 520 #[cfg(not(target_arch = "aarch64"))] 521 { 522 0 523 } 524 } 525 526 // Entry saves the callee-saved GPRs, d8-d15 and FPCR on SP_EL1, then enters 527 // EL0 with only x0-x3 carrying values: every other GPR, every SIMD/FP 528 // register, FPCR/FPSR and TPIDR_EL0 are zeroed so no kernel state leaks. 529 // Every termination returns to `aienos_task_resume` at EL1h with SP_EL1 back 530 // where entry left it, restoring the saved state. 531 #[cfg(target_arch = "aarch64")] 532 core::arch::global_asm!( 533 ".global aienos_task_enter", 534 ".global aienos_task_resume", 535 // x0 = entry, x1 = sp_el0, x2 = pointer to [u64; 4] initial x0..x3 536 "aienos_task_enter:", 537 "sub sp, sp, #176", 538 "stp x19, x20, [sp, #0]", 539 "stp x21, x22, [sp, #16]", 540 "stp x23, x24, [sp, #32]", 541 "stp x25, x26, [sp, #48]", 542 "stp x27, x28, [sp, #64]", 543 "stp x29, x30, [sp, #80]", 544 "stp d8, d9, [sp, #96]", 545 "stp d10, d11, [sp, #112]", 546 "stp d12, d13, [sp, #128]", 547 "stp d14, d15, [sp, #144]", 548 "mrs x9, fpcr", 549 "str x9, [sp, #160]", 550 "msr sp_el0, x1", 551 "msr elr_el1, x0", 552 "msr spsr_el1, xzr", 553 "msr tpidr_el0, xzr", 554 "msr fpcr, xzr", 555 "msr fpsr, xzr", 556 "mov x9, x2", 557 "ldp x0, x1, [x9, #0]", 558 "ldp x2, x3, [x9, #16]", 559 "mov x4, xzr", 560 "mov x5, xzr", 561 "mov x6, xzr", 562 "mov x7, xzr", 563 "mov x8, xzr", 564 "mov x9, xzr", 565 "mov x10, xzr", 566 "mov x11, xzr", 567 "mov x12, xzr", 568 "mov x13, xzr", 569 "mov x14, xzr", 570 "mov x15, xzr", 571 "mov x16, xzr", 572 "mov x17, xzr", 573 "mov x18, xzr", 574 "mov x19, xzr", 575 "mov x20, xzr", 576 "mov x21, xzr", 577 "mov x22, xzr", 578 "mov x23, xzr", 579 "mov x24, xzr", 580 "mov x25, xzr", 581 "mov x26, xzr", 582 "mov x27, xzr", 583 "mov x28, xzr", 584 "mov x29, xzr", 585 "mov x30, xzr", 586 ".irp reg, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31", 587 "movi v\\reg\\().2d, #0", 588 ".endr", 589 "eret", 590 "aienos_task_resume:", 591 "ldr x9, [sp, #160]", 592 "msr fpcr, x9", 593 "msr fpsr, xzr", 594 "ldp d8, d9, [sp, #96]", 595 "ldp d10, d11, [sp, #112]", 596 "ldp d12, d13, [sp, #128]", 597 "ldp d14, d15, [sp, #144]", 598 "ldp x19, x20, [sp, #0]", 599 "ldp x21, x22, [sp, #16]", 600 "ldp x23, x24, [sp, #32]", 601 "ldp x25, x26, [sp, #48]", 602 "ldp x27, x28, [sp, #64]", 603 "ldp x29, x30, [sp, #80]", 604 "add sp, sp, #176", 605 "ret", 606 ); 607 608 #[cfg(target_arch = "aarch64")] 609 extern "C" { 610 fn aienos_task_enter(entry: u64, stack: u64, args: *const u64); 611 static aienos_task_resume: u8; 612 } 613 614 #[cfg(test)] 615 mod tests { 616 use super::*; 617 use crate::abi::ResourceId; 618 use aienos_artifact::capability::CapabilityRequest; 619 620 const BUDGET: TaskBudget = TaskBudget { 621 cpu_ticks: 1_000, 622 elapsed_ticks: 2_000, 623 syscalls: 8, 624 }; 625 626 fn grant(rights: Rights, offset: u64, length: u64, ops: u32, bytes: u64) -> GrantedCapability { 627 GrantedCapability { 628 resource: ResourceId::new(ResourceKind::Object, SEED_OBJECT_ID), 629 rights, 630 bounds: CapabilityRequest { 631 resource_kind: 3, 632 resource_id: SEED_OBJECT_ID, 633 rights: u32::from(rights.bits()), 634 bounds_kind: 1, 635 max_operations: ops, 636 max_bytes: bytes, 637 byte_offset: offset, 638 byte_length: length, 639 }, 640 } 641 } 642 643 /// One READ grant installed at grant index 0; returns its raw handle. 644 fn setup( 645 g: GrantedCapability, 646 ) -> ( 647 CapTable, 648 [Option; 1], 649 u64, 650 ) { 651 let mut caps = CapTable::new(0x5441_534b); 652 let handle = caps.insert(0, g.rights).unwrap(); 653 (caps, [Some(g)], handle.to_raw()) 654 } 655 656 #[test] 657 fn denials_are_classified_from_observed_lookups() { 658 let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 8, 64)); 659 let budget = TaskBudget { 660 syscalls: 32, 661 ..BUDGET 662 }; 663 let mut st = RuntimeState::new(budget, 0); 664 let call = |st: &mut RuntimeState, number: u64, args: [u64; 3]| { 665 st.syscall(&caps, &grants, 0, number, args, 1) 666 }; 667 // Authorized READ. 668 assert_eq!( 669 call(&mut st, SYS_OBJECT_READ, [h, 0, 0]), 670 SyscallAction::Return(SEED_OBJECT_WORDS[0]) 671 ); 672 // WRITE through a READ-only handle: denied for authority, not handle. 673 assert_eq!( 674 call(&mut st, SYS_OBJECT_WRITE, [h, 0, 7]), 675 SyscallAction::Return(SYSCALL_DENIED) 676 ); 677 assert_eq!((st.write_denials, st.invalid_handle_denials), (1, 0)); 678 assert_eq!(st.object, SEED_OBJECT_WORDS, "denied write changed nothing"); 679 // Forged generation, never-issued slot, zero handle: invalid handles. 680 for forged in [h ^ (1 << 32), (1u64 << 32) | 1, 0] { 681 assert_eq!( 682 call(&mut st, SYS_OBJECT_READ, [forged, 0, 0]), 683 SyscallAction::Return(SYSCALL_DENIED) 684 ); 685 } 686 assert_eq!(st.invalid_handle_denials, 3); 687 // Out of the grant's range: a bounds denial, not an invalid handle. 688 assert_eq!( 689 call(&mut st, SYS_OBJECT_READ, [h, 32, 0]), 690 SyscallAction::Return(SYSCALL_DENIED) 691 ); 692 assert_eq!( 693 ( 694 st.denials, 695 st.write_denials, 696 st.invalid_handle_denials, 697 st.object_reads_ok 698 ), 699 (5, 1, 3, 1) 700 ); 701 let outcome = st.outcome(ExecutionStatus::Exited(0), 5); 702 assert_eq!( 703 ( 704 outcome.denials, 705 outcome.write_denials, 706 outcome.invalid_handle_denials 707 ), 708 (5, 1, 3) 709 ); 710 } 711 712 fn read( 713 state: &mut RuntimeState, 714 caps: &CapTable, 715 grants: &[Option], 716 handle: u64, 717 offset: u64, 718 ) -> SyscallAction { 719 state.syscall(caps, grants, 0, SYS_OBJECT_READ, [handle, offset, 0], 10) 720 } 721 722 #[test] 723 fn granted_read_returns_object_word_and_charges_budget() { 724 let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 4, 32)); 725 let mut s = RuntimeState::new(BUDGET, 0); 726 assert_eq!( 727 read(&mut s, &caps, &grants, h, 8), 728 SyscallAction::Return(SEED_OBJECT_WORDS[1]) 729 ); 730 assert_eq!(s.object_reads_ok, 1); 731 assert_eq!( 732 s.usage[0], 733 GrantUsage { 734 operations: 1, 735 bytes: 8 736 } 737 ); 738 assert_eq!(s.denials, 0); 739 } 740 741 #[test] 742 fn read_outside_grant_range_or_object_or_unaligned_is_denied() { 743 let (caps, grants, h) = setup(grant(Rights::READ, 8, 8, 8, 64)); 744 let mut s = RuntimeState::new(BUDGET, 0); 745 for offset in [0, 16, 12, 32, u64::MAX - 3] { 746 assert_eq!( 747 read(&mut s, &caps, &grants, h, offset), 748 SyscallAction::Return(SYSCALL_DENIED), 749 "offset {offset}" 750 ); 751 } 752 assert_eq!(s.denials, 5); 753 assert_eq!(s.usage[0], GrantUsage::default()); 754 // Range past the 32-byte object is denied even if the grant covers it. 755 let (caps, grants, h) = setup(grant(Rights::READ, 0, 64, 8, 64)); 756 let mut s = RuntimeState::new(BUDGET, 0); 757 assert_eq!( 758 read(&mut s, &caps, &grants, h, 32), 759 SyscallAction::Return(SYSCALL_DENIED) 760 ); 761 } 762 763 #[test] 764 fn read_past_operation_budget_is_denied() { 765 let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 2, 32)); 766 let mut s = RuntimeState::new(BUDGET, 0); 767 assert!(matches!( 768 read(&mut s, &caps, &grants, h, 0), 769 SyscallAction::Return(v) if v != SYSCALL_DENIED 770 )); 771 assert!(matches!( 772 read(&mut s, &caps, &grants, h, 0), 773 SyscallAction::Return(v) if v != SYSCALL_DENIED 774 )); 775 assert_eq!( 776 read(&mut s, &caps, &grants, h, 0), 777 SyscallAction::Return(SYSCALL_DENIED) 778 ); 779 assert_eq!(s.object_reads_ok, 2); 780 } 781 782 #[test] 783 fn read_past_byte_budget_is_denied() { 784 let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 8, 12)); 785 let mut s = RuntimeState::new(BUDGET, 0); 786 assert_eq!( 787 read(&mut s, &caps, &grants, h, 0), 788 SyscallAction::Return(SEED_OBJECT_WORDS[0]) 789 ); 790 assert_eq!( 791 read(&mut s, &caps, &grants, h, 8), 792 SyscallAction::Return(SYSCALL_DENIED) 793 ); 794 assert_eq!(s.usage[0].bytes, 8); 795 } 796 797 #[test] 798 fn write_without_write_right_is_denied_and_object_unchanged() { 799 let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 8, 32)); 800 let mut s = RuntimeState::new(BUDGET, 0); 801 assert_eq!( 802 s.syscall(&caps, &grants, 0, SYS_OBJECT_WRITE, [h, 0, 0xbad], 10), 803 SyscallAction::Return(SYSCALL_DENIED) 804 ); 805 assert_eq!(s.denials, 1); 806 assert_eq!(s.object, SEED_OBJECT_WORDS); 807 } 808 809 #[test] 810 fn write_with_write_right_updates_kernel_copy() { 811 let (caps, grants, h) = setup(grant(Rights::READ | Rights::WRITE, 0, 32, 8, 32)); 812 let mut s = RuntimeState::new(BUDGET, 0); 813 assert_eq!( 814 s.syscall(&caps, &grants, 0, SYS_OBJECT_WRITE, [h, 24, 0x77], 10), 815 SyscallAction::Return(0) 816 ); 817 assert_eq!(s.object[3], 0x77); 818 assert_eq!( 819 read(&mut s, &caps, &grants, h, 24), 820 SyscallAction::Return(0x77) 821 ); 822 } 823 824 #[test] 825 fn forged_stale_and_unbacked_handles_are_denied() { 826 let (mut caps, grants, h) = setup(grant(Rights::READ, 0, 32, 8, 32)); 827 let mut s = RuntimeState::new(BUDGET, 0); 828 // Generation 0 never parses; wrong generation and wrong index fail lookup. 829 for forged in [0, h & 0xffff_ffff, h ^ (1 << 32), h + 1] { 830 assert_eq!( 831 read(&mut s, &caps, &grants, forged, 0), 832 SyscallAction::Return(SYSCALL_DENIED), 833 "forged {forged:#x}" 834 ); 835 } 836 // A handle whose resource names no grant is denied. 837 let orphan = caps.insert(5, Rights::READ).unwrap().to_raw(); 838 assert_eq!( 839 read(&mut s, &caps, &grants, orphan, 0), 840 SyscallAction::Return(SYSCALL_DENIED) 841 ); 842 // Revoked (removed) handle is stale. 843 caps.remove(Handle::from_raw(h).unwrap()).unwrap(); 844 assert_eq!( 845 read(&mut s, &caps, &grants, h, 0), 846 SyscallAction::Return(SYSCALL_DENIED) 847 ); 848 assert_eq!(s.denials, 6); 849 assert_eq!(s.object_reads_ok, 0); 850 } 851 852 #[test] 853 fn non_object_or_other_object_grant_is_denied() { 854 let mut g = grant(Rights::READ, 0, 32, 8, 32); 855 g.resource = ResourceId::new(ResourceKind::Channel, SEED_OBJECT_ID); 856 let (caps, grants, h) = setup(g); 857 let mut s = RuntimeState::new(BUDGET, 0); 858 assert_eq!( 859 read(&mut s, &caps, &grants, h, 0), 860 SyscallAction::Return(SYSCALL_DENIED) 861 ); 862 let mut g = grant(Rights::READ, 0, 32, 8, 32); 863 g.resource = ResourceId::new(ResourceKind::Object, 99); 864 let (caps, grants, h) = setup(g); 865 assert_eq!( 866 read(&mut s, &caps, &grants, h, 0), 867 SyscallAction::Return(SYSCALL_DENIED) 868 ); 869 } 870 871 #[test] 872 fn unknown_syscall_and_nonzero_immediate_terminate() { 873 let (caps, grants, _) = setup(grant(Rights::READ, 0, 32, 8, 32)); 874 let mut s = RuntimeState::new(BUDGET, 0); 875 assert_eq!( 876 s.syscall(&caps, &grants, 0, 99, [0; 3], 10), 877 SyscallAction::Terminate(ExecutionStatus::BadSyscall(99)) 878 ); 879 assert_eq!( 880 s.syscall(&caps, &grants, 1, SYS_EXIT, [0; 3], 10), 881 SyscallAction::Terminate(ExecutionStatus::BadSyscall(SYS_EXIT)) 882 ); 883 assert_eq!( 884 s.syscall(&caps, &grants, 0, SYS_EXIT, [0x5a, 0, 0], 10), 885 SyscallAction::Terminate(ExecutionStatus::Exited(0x5a)) 886 ); 887 } 888 889 #[test] 890 fn syscall_budget_overrun_terminates() { 891 let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 100, 800)); 892 let budget = TaskBudget { 893 syscalls: 3, 894 ..BUDGET 895 }; 896 let mut s = RuntimeState::new(budget, 0); 897 for _ in 0..3 { 898 assert!(matches!( 899 read(&mut s, &caps, &grants, h, 0), 900 SyscallAction::Return(_) 901 )); 902 } 903 assert_eq!( 904 read(&mut s, &caps, &grants, h, 0), 905 SyscallAction::Terminate(ExecutionStatus::ResourceOverrun) 906 ); 907 } 908 909 #[test] 910 fn syscall_after_deadline_times_out() { 911 let (caps, grants, _) = setup(grant(Rights::READ, 0, 32, 8, 32)); 912 let mut s = RuntimeState::new(BUDGET, 500); 913 assert_eq!( 914 s.syscall(&caps, &grants, 0, SYS_EXIT, [0; 3], 500 + 1_000), 915 SyscallAction::Terminate(ExecutionStatus::Timeout) 916 ); 917 } 918 919 #[test] 920 fn deadline_uses_tighter_budget_and_survives_counter_wrap() { 921 assert_eq!(BUDGET.tick_limit(), 1_000); 922 let s = RuntimeState::new(BUDGET, u64::MAX - 100); 923 assert!(!s.expired(u64::MAX - 100)); 924 assert!(!s.expired(u64::MAX)); 925 assert!(!s.expired(898)); // 999 ticks after start, across the wrap 926 assert!(s.expired(899)); // exactly 1000 ticks 927 assert_eq!(elapsed_since(u64::MAX - 1, 1), 3); 928 assert!(deadline_expired(0, 5, 5)); 929 assert!(!deadline_expired(0, 4, 5)); 930 } 931 }