interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-boot / src / rollback_mock.rs

419 lines · 13226 bytes Raw Blame History
1#![no_std]
2// SPDX-License-Identifier: Apache-2.0
3// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16#![no_main]
17
18// Links the `wcslen` definition (see wcslen.rs); rustc 1.99 emits calls to it.
19extern crate aienos_boot as _;
20
21extern crate alloc;
22
23use alloc::vec::Vec;
24use uefi::prelude::*;
25use uefi::proto::device_path::{DeviceSubType, DeviceType, LoadedImageDevicePath};
26use uefi::proto::media::file::{File, FileAttribute, FileMode};
27use uefi::runtime::{ResetType, VariableAttributes, VariableVendor};
28use uefi::{cstr16, CStr16};
29
30#[global_allocator]
31static ALLOCATOR: uefi::allocator::Allocator = uefi::allocator::Allocator;
32
33#[panic_handler]
34fn panic(info: &core::panic::PanicInfo) -> ! {
35 uefi::println!("ROLLBACK_MOCK_PANIC: {}", info);
36 uefi::runtime::reset(ResetType::COLD, Status::ABORTED, None)
37}
38
39const CYCLE_VAR: &CStr16 = cstr16!("AienosRollbackCycle");
40const CYCLE_VENDOR: uefi::runtime::VariableVendor =
41 VariableVendor(uefi::guid!("a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a38"));
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44enum Role {
45 Stager,
46 Candidate,
47 DefaultOs,
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51enum Mode {
52 Normal,
53 Fault,
54 Timeout,
55 Absent,
56 Malformed,
57 RealAienos,
58}
59
60fn detect_role() -> Role {
61 let handle = uefi::boot::image_handle();
62 let Ok(loaded_dp) = uefi::boot::open_protocol_exclusive::<LoadedImageDevicePath>(handle) else {
63 return Role::Stager;
64 };
65
66 for node in loaded_dp.node_iter() {
67 if node.device_type() == DeviceType::MEDIA
68 && node.sub_type() == DeviceSubType::MEDIA_FILE_PATH
69 {
70 let data = node.data();
71 let (chunks, _) = data.as_chunks::<2>();
72 let s = chunks
73 .iter()
74 .map(|c| u16::from_le_bytes([c[0], c[1]]) as u8 as char)
75 .collect::<alloc::string::String>();
76 let lower = s.to_lowercase();
77 if lower.contains("default") {
78 return Role::DefaultOs;
79 } else if lower.contains("candidate") {
80 return Role::Candidate;
81 }
82 }
83 }
84 Role::Stager
85}
86
87fn read_mode_file() -> Mode {
88 let mut buf = [0u8; 64];
89 if let Ok(mut fs) = uefi::boot::get_image_file_system(uefi::boot::image_handle()) {
90 if let Ok(mut root) = fs.open_volume() {
91 if let Ok(handle) = root.open(
92 cstr16!("\\EFI\\AIENOS\\ROLLBACK_MODE.TXT"),
93 FileMode::Read,
94 FileAttribute::empty(),
95 ) {
96 if let Some(mut file) = handle.into_regular_file() {
97 let _ = file.read(&mut buf);
98 }
99 }
100 }
101 }
102
103 let text = core::str::from_utf8(&buf).unwrap_or("");
104 if text.contains("fault") {
105 Mode::Fault
106 } else if text.contains("timeout") {
107 Mode::Timeout
108 } else if text.contains("absent") {
109 Mode::Absent
110 } else if text.contains("malformed") {
111 Mode::Malformed
112 } else if text.contains("real_aienos") {
113 Mode::RealAienos
114 } else {
115 Mode::Normal
116 }
117}
118
119fn build_load_option(description: &str, partition_dp_prefix: &[u8], file_path: &str) -> Vec<u8> {
120 let mut full_dp = Vec::new();
121 full_dp.extend_from_slice(partition_dp_prefix);
122
123 // Media FilePath node: Type = 0x04, SubType = 0x04
124 // Length: 4 + 2 * (chars + 1)
125 let utf16_chars: Vec<u16> = file_path.encode_utf16().collect();
126 let node_len = (4 + 2 * (utf16_chars.len() + 1)) as u16;
127 full_dp.push(0x04);
128 full_dp.push(0x04);
129 full_dp.extend_from_slice(&node_len.to_le_bytes());
130 for &ch in &utf16_chars {
131 full_dp.extend_from_slice(&ch.to_le_bytes());
132 }
133 full_dp.extend_from_slice(&0u16.to_le_bytes()); // null terminator
134
135 // End-Entire node: 0x7F, 0xFF, 0x04, 0x00
136 full_dp.push(0x7F);
137 full_dp.push(0xFF);
138 full_dp.extend_from_slice(&4u16.to_le_bytes());
139
140 let mut opt = Vec::new();
141 // 1. Attributes: LOAD_OPTION_ACTIVE = 0x00000001
142 opt.extend_from_slice(&1u32.to_le_bytes());
143 // 2. FilePathListLength
144 opt.extend_from_slice(&(full_dp.len() as u16).to_le_bytes());
145 // 3. Description null-terminated UTF-16
146 for c in description.encode_utf16() {
147 opt.extend_from_slice(&c.to_le_bytes());
148 }
149 opt.extend_from_slice(&0u16.to_le_bytes());
150 // 4. FilePathList
151 opt.extend_from_slice(&full_dp);
152
153 opt
154}
155
156#[entry]
157fn main() -> Status {
158 let role = detect_role();
159 let mode = read_mode_file();
160
161 match role {
162 Role::Stager => run_stager(mode),
163 Role::Candidate => run_candidate(mode),
164 Role::DefaultOs => run_default(mode),
165 }
166}
167
168fn run_stager(mode: Mode) -> Status {
169 uefi::println!("=== M0_ROLLBACK_HARNESS: STAGER STARTING ===");
170 uefi::println!("stager_mode: {:?}", mode);
171
172 let handle = uefi::boot::image_handle();
173 let Ok(loaded_dp) = uefi::boot::open_protocol_exclusive::<LoadedImageDevicePath>(handle) else {
174 uefi::println!("FAIL: cannot get LoadedImageDevicePath");
175 return Status::UNSUPPORTED;
176 };
177
178 // Extract partition device path prefix (everything before the first MEDIA_FILE_PATH node)
179 let mut prefix_len = 0;
180 for node in loaded_dp.node_iter() {
181 if node.device_type() == DeviceType::MEDIA
182 && node.sub_type() == DeviceSubType::MEDIA_FILE_PATH
183 {
184 break;
185 }
186 prefix_len += usize::from(node.length());
187 }
188
189 if prefix_len == 0 {
190 uefi::println!("FAIL: partition device path prefix empty");
191 return Status::UNSUPPORTED;
192 }
193
194 let prefix = &loaded_dp.as_bytes()[..prefix_len];
195
196 // Build Boot0001 (Default Linux OS -> \EFI\DEFAULT\default.efi)
197 let opt_default = build_load_option("Default Linux OS", prefix, "\\EFI\\DEFAULT\\default.efi");
198
199 // Build Boot0000 (Candidate)
200 let candidate_path = match mode {
201 Mode::Absent => "\\EFI\\AIENOS\\missing_candidate.efi",
202 Mode::RealAienos => "\\EFI\\AIENOS\\aienos-handoff.efi",
203 _ => "\\EFI\\AIENOS\\candidate.efi",
204 };
205 let opt_candidate = build_load_option("AIENOS Candidate", prefix, candidate_path);
206
207 let var_attrs = VariableAttributes::NON_VOLATILE
208 | VariableAttributes::BOOTSERVICE_ACCESS
209 | VariableAttributes::RUNTIME_ACCESS;
210
211 // Set Boot0001
212 if uefi::runtime::set_variable(
213 cstr16!("Boot0001"),
214 &VariableVendor::GLOBAL_VARIABLE,
215 var_attrs,
216 &opt_default,
217 )
218 .is_err()
219 {
220 uefi::println!("FAIL: set Boot0001");
221 return Status::DEVICE_ERROR;
222 }
223
224 // Set BootOrder = [0x0001]
225 let boot_order = [0x0001u16];
226 let boot_order_bytes =
227 unsafe { core::slice::from_raw_parts(boot_order.as_ptr() as *const u8, 2) };
228 if uefi::runtime::set_variable(
229 cstr16!("BootOrder"),
230 &VariableVendor::GLOBAL_VARIABLE,
231 var_attrs,
232 boot_order_bytes,
233 )
234 .is_err()
235 {
236 uefi::println!("FAIL: set BootOrder");
237 return Status::DEVICE_ERROR;
238 }
239
240 // Set Boot0000
241 if uefi::runtime::set_variable(
242 cstr16!("Boot0000"),
243 &VariableVendor::GLOBAL_VARIABLE,
244 var_attrs,
245 &opt_candidate,
246 )
247 .is_err()
248 {
249 uefi::println!("FAIL: set Boot0000");
250 return Status::DEVICE_ERROR;
251 }
252
253 // Set BootNext = 0x0000
254 let boot_next = 0x0000u16;
255 if uefi::runtime::set_variable(
256 cstr16!("BootNext"),
257 &VariableVendor::GLOBAL_VARIABLE,
258 var_attrs,
259 &boot_next.to_le_bytes(),
260 )
261 .is_err()
262 {
263 uefi::println!("FAIL: set BootNext");
264 return Status::DEVICE_ERROR;
265 }
266
267 // Reset cycle counter to 0
268 let zero = 0u32;
269 let _ = uefi::runtime::set_variable(CYCLE_VAR, &CYCLE_VENDOR, var_attrs, &zero.to_le_bytes());
270
271 uefi::println!(
272 "PASS M0_ROLLBACK_STAGED: boot_order=0001 boot_next=0000 candidate={}",
273 candidate_path
274 );
275 uefi::println!("M0_ROLLBACK_HARNESS: RESETTING SYSTEM FOR CANDIDATE BOOT");
276
277 // Initiate Cold Reset to execute BootNext
278 uefi::runtime::reset(ResetType::COLD, Status::SUCCESS, None)
279}
280
281fn run_candidate(mode: Mode) -> Status {
282 uefi::println!("=== AIENOS CANDIDATE STARTING ===");
283 uefi::println!("AIENOS_CANDIDATE: RUNNING");
284 uefi::println!("NATIVE_CONTROL_ACQUIRED: PASS");
285
286 // Check BootCurrent
287 let mut current_buf = [0u8; 4];
288 if let Ok((data, _)) = uefi::runtime::get_variable(
289 cstr16!("BootCurrent"),
290 &VariableVendor::GLOBAL_VARIABLE,
291 &mut current_buf,
292 ) {
293 if data.len() >= 2 {
294 let cur = u16::from_le_bytes([data[0], data[1]]);
295 uefi::println!("AIENOS_CANDIDATE: BOOT_CURRENT={:04X}", cur);
296 }
297 }
298
299 match mode {
300 Mode::Normal => {
301 uefi::println!("AIENOS_CANDIDATE: NORMAL_TERMINATION_REQUESTED");
302 uefi::println!("AIENOS_CANDIDATE: RESETTING");
303 uefi::runtime::reset(ResetType::COLD, Status::SUCCESS, None)
304 }
305 Mode::Fault => {
306 uefi::println!("AIENOS_CANDIDATE: INDUCED_FAULT_PANIC");
307 uefi::println!("AIENOS_CANDIDATE: RESETTING WITH FAULT");
308 uefi::runtime::reset(ResetType::COLD, Status::ABORTED, None)
309 }
310 Mode::Timeout => {
311 uefi::println!("AIENOS_CANDIDATE: ENTERING_HANG_SPIN_LOOP");
312 loop {
313 core::hint::spin_loop();
314 }
315 }
316 _ => {
317 uefi::println!("AIENOS_CANDIDATE: DEFAULT_TERMINATION");
318 uefi::runtime::reset(ResetType::COLD, Status::SUCCESS, None)
319 }
320 }
321}
322
323fn run_default(_mode: Mode) -> Status {
324 uefi::println!("=== DEFAULT OS BOOT (LINUX REFERENCE MOCK) ===");
325 uefi::println!("DEFAULT_BOOT: ALIVE");
326
327 // Read BootCurrent
328 let mut current_buf = [0u8; 4];
329 let cur = if let Ok((data, _)) = uefi::runtime::get_variable(
330 cstr16!("BootCurrent"),
331 &VariableVendor::GLOBAL_VARIABLE,
332 &mut current_buf,
333 ) {
334 if data.len() >= 2 {
335 u16::from_le_bytes([data[0], data[1]])
336 } else {
337 0xFFFF
338 }
339 } else {
340 0xFFFF
341 };
342 uefi::println!("DEFAULT_OS: BOOT_CURRENT={:04X}", cur);
343
344 // Read BootOrder
345 let mut order_buf = [0u8; 32];
346 let order_ok = if let Ok((data, _)) = uefi::runtime::get_variable(
347 cstr16!("BootOrder"),
348 &VariableVendor::GLOBAL_VARIABLE,
349 &mut order_buf,
350 ) {
351 if data.len() >= 2 {
352 let first = u16::from_le_bytes([data[0], data[1]]);
353 uefi::println!("DEFAULT_OS: BOOT_ORDER[0]={:04X}", first);
354 first == 0x0001
355 } else {
356 false
357 }
358 } else {
359 false
360 };
361
362 // Check BootNext (must be absent / consumed)
363 let mut next_buf = [0u8; 4];
364 let next_result = uefi::runtime::get_variable(
365 cstr16!("BootNext"),
366 &VariableVendor::GLOBAL_VARIABLE,
367 &mut next_buf,
368 );
369 let next_consumed = next_result.is_err();
370
371 if next_consumed {
372 uefi::println!("DEFAULT_OS: BOOT_NEXT=CONSUMED_PASS");
373 uefi::println!("PASS NATIVE_ROLLBACK_BOOTNEXT_CONSUMED");
374 } else {
375 uefi::println!("FAIL NATIVE_ROLLBACK_BOOTNEXT_STILL_PRESENT");
376 }
377
378 if order_ok {
379 uefi::println!("PASS NATIVE_ROLLBACK_DEFAULT_UNCHANGED");
380 } else {
381 uefi::println!("FAIL NATIVE_ROLLBACK_DEFAULT_ORDER_ALTERED");
382 }
383
384 // Check cycle count
385 let mut cycle_buf = [0u8; 4];
386 let cycle = if let Ok((data, _)) =
387 uefi::runtime::get_variable(CYCLE_VAR, &CYCLE_VENDOR, &mut cycle_buf)
388 {
389 if data.len() >= 4 {
390 u32::from_le_bytes([data[0], data[1], data[2], data[3]])
391 } else {
392 0
393 }
394 } else {
395 0
396 };
397
398 let var_attrs = VariableAttributes::NON_VOLATILE
399 | VariableAttributes::BOOTSERVICE_ACCESS
400 | VariableAttributes::RUNTIME_ACCESS;
401
402 if cycle == 0 {
403 uefi::println!("DEFAULT_OS: FIRST_RETURN_VERIFIED");
404 let next_cycle = 1u32;
405 let _ = uefi::runtime::set_variable(
406 CYCLE_VAR,
407 &CYCLE_VENDOR,
408 var_attrs,
409 &next_cycle.to_le_bytes(),
410 );
411 uefi::println!("DEFAULT_OS: TRIGGERING_REPEAT_BOOT_TEST");
412 uefi::runtime::reset(ResetType::COLD, Status::SUCCESS, None)
413 } else {
414 uefi::println!("DEFAULT_OS: REPEAT_BOOT_VERIFIED (cycle={})", cycle);
415 uefi::println!("PASS NATIVE_ROLLBACK_REPEAT_BOOT");
416 uefi::println!("DEFAULT_OS: ALL ROLLBACK INVARIANTS SATISFIED");
417 uefi::runtime::reset(ResetType::SHUTDOWN, Status::SUCCESS, None)
418 }
419}