Skip to main content

strate_init/
main.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23#![no_std]
24#![no_main]
25#![feature(alloc_error_handler)]
26
27extern crate alloc;
28
29//
30// The boot configuration parser, policy validation and SID allocation live in
31// the host-testable `init-config` crate. This file only maps the resulting
32// `BootPlan` onto the kernel ABI at the execution boundary. Launching lives in
33// `launcher.rs` and child supervision in `supervisor.rs`.
34//
35
36use alloc::{string::String, vec::Vec};
37use core::{alloc::Layout, panic::PanicInfo};
38use init_config::{
39    BootPlan, Diagnostic, PlannedKind, PlannedSilo, Policy, Selection, SiloDef,
40    build_plan_with_policy, build_plan_with_reserved, merge_overlay, parse_config,
41};
42use strat9_syscall::{
43    call,
44    data::{
45        SILO_GRANT_ACCESS_WRITE, SILO_GRANT_DMA, SILO_GRANT_IRQ, SILO_GRANT_PATH, SILO_GRANT_PCI,
46        SiloConfig, SiloGrantDesc,
47    },
48};
49mod control;
50pub mod fmt;
51mod launcher;
52mod supervisor;
53use fmt::log_u32;
54
55const EAGAIN: usize = 11;
56const MAX_READ_BYTES: usize = 64 * 1024 * 1024;
57const MAX_READ_EAGAIN: usize = 256;
58
59// ---------------------------------------------------------------------------
60// GLOBAL ALLOCATOR (BUMP + BRK)
61// ---------------------------------------------------------------------------
62
63alloc_freelist::define_freelist_brk_allocator!(
64    pub struct BumpAllocator;
65    brk = strat9_syscall::call::brk;
66    heap_max = 64 * 1024 * 1024;
67);
68
69#[global_allocator]
70static ALLOCATOR: BumpAllocator = BumpAllocator;
71
72#[alloc_error_handler]
73/// Implements alloc error.
74fn alloc_error(_layout: Layout) -> ! {
75    let _ = call::debug_log(b"[init] OOM Fatal\n");
76    call::exit(12);
77}
78
79// ---------------------------------------------------------------------------
80// Utils
81// ---------------------------------------------------------------------------
82
83/// Writes `msg` to the kernel debug log.
84fn log(msg: &str) {
85    let _ = call::debug_log(msg.as_bytes());
86}
87
88/// Writes a configuration diagnostic, reproducing the historic log line.
89fn log_diagnostic(diagnostic: &Diagnostic) {
90    log("[init] ");
91    log(&diagnostic.message);
92}
93
94/// Reads file.
95///
96/// Returns an error when the file is larger than [`MAX_READ_BYTES`] instead of
97/// silently truncating it: a truncated ELF blob must never reach
98/// `SYS_MODULE_LOAD`.
99fn read_file(path: &str) -> Result<Vec<u8>, &'static str> {
100    let fd = call::openat(0, path, 0x1, 0).map_err(|_| "open failed")?;
101    let mut out = Vec::new();
102
103    let mut chunk = [0u8; 8192]; // 8 KiB scratch buffer, keeps the stack small
104
105    let mut eagain = 0usize;
106    loop {
107        match call::read(fd as usize, &mut chunk) {
108            Ok(0) => break,
109            Ok(n) => {
110                if out.len() + n > MAX_READ_BYTES {
111                    let _ = call::close(fd as usize);
112                    log("[init] read_file: file exceeds MAX_READ_BYTES\n");
113                    return Err("file too large");
114                }
115                out.extend_from_slice(&chunk[..n]);
116                eagain = 0;
117            }
118            Err(e) if e.to_errno() == EAGAIN => {
119                eagain += 1;
120                if eagain > MAX_READ_EAGAIN {
121                    let _ = call::close(fd as usize);
122                    return Err("read timeout");
123                }
124                let _ = call::sched_yield();
125            }
126            Err(_) => {
127                let _ = call::close(fd as usize);
128                return Err("read failed");
129            }
130        }
131    }
132    let _ = call::close(fd as usize);
133    Ok(out)
134}
135
136// ---------------------------------------------------------------------------
137// CONFIGURATION LOADING
138// ---------------------------------------------------------------------------
139
140// Keep the fallback identical to the configuration shipped in the UEFI image.
141const DEFAULT_SILO_TOML: &str = include_str!("../../../assets/boot/silo.toml");
142
143/// Parses the embedded default silo config.
144fn default_silos() -> init_config::ParsedConfig {
145    parse_config(DEFAULT_SILO_TOML)
146}
147
148/// Loads the primary silo config, falling back to the embedded defaults.
149///
150/// The parsed `[policy]` section is returned with the silos so the same
151/// admin allowlist and target/profile selection drive the plan and later
152/// `reload` calls.
153fn load_primary_silos() -> (Vec<SiloDef>, Vec<Diagnostic>, Policy) {
154    log("[init] load_primary_silos: begin\n");
155    let parsed = match read_file("/initfs/silo.toml") {
156        Ok(data_vec) => match core::str::from_utf8(&data_vec) {
157            Ok(data_str) => {
158                log("[init] load_primary_silos: parse /initfs/silo.toml\n");
159                Some(parse_config(data_str))
160            }
161            Err(_) => {
162                log("[init] Invalid UTF-8 in /initfs/silo.toml, using embedded defaults\n");
163                None
164            }
165        },
166        Err(_) => {
167            log("[init] Missing /initfs/silo.toml, using embedded defaults\n");
168            None
169        }
170    };
171
172    match parsed {
173        Some(parsed) if !parsed.silos.is_empty() => {
174            log("[init] load_primary_silos: parsed file count=");
175            log_u32(parsed.silos.len() as u32);
176            log("\n");
177            (parsed.silos, parsed.diagnostics, parsed.policy)
178        }
179        _ => {
180            log("[init] Empty or unusable /initfs/silo.toml, using embedded defaults\n");
181            let parsed = default_silos();
182            log("[init] load_primary_silos: parsed embedded defaults count=");
183            log_u32(parsed.silos.len() as u32);
184            log("\n");
185            (parsed.silos, parsed.diagnostics, parsed.policy)
186        }
187    }
188}
189
190/// Applies `/initfs/init.target` over the configured selection.
191///
192/// The file's first non-empty line is a `Selection` spec; on any error the
193/// configured policy is kept unchanged.
194fn apply_init_target(policy: &mut Policy) {
195    let data = match read_file("/initfs/init.target") {
196        Ok(data) => data,
197        Err(_) => return,
198    };
199    let text = match core::str::from_utf8(&data) {
200        Ok(text) => text,
201        Err(_) => {
202            log("[init] CONFIG ERROR: init.target: invalid UTF-8\n");
203            return;
204        }
205    };
206    let spec = text
207        .lines()
208        .find(|line| !line.trim().is_empty())
209        .unwrap_or("")
210        .trim();
211    match Selection::from_spec(spec) {
212        Ok(selection) => {
213            policy.selection.profile = selection.profile;
214            for name in selection.disabled {
215                if !policy.selection.is_disabled(&name) {
216                    policy.selection.disabled.push(name);
217                }
218            }
219            log("[init] target=");
220            log(policy.selection.profile.as_str());
221            log(" disable=");
222            log_u32(policy.selection.disabled.len() as u32);
223            log("\n");
224        }
225        Err(e) => {
226            log("[init] CONFIG ERROR: init.target: ");
227            log(&e);
228            log("\n");
229        }
230    }
231}
232
233/// True when the kernel command line explicitly selects a boot profile.
234fn cmdline_sets_target(cmdline: &str) -> bool {
235    cmdline
236        .split(|c: char| c == '\0' || c.is_whitespace())
237        .any(|token| token.starts_with("init.target="))
238}
239
240/// Applies `init.target=` / `init.disable=` from the kernel command line.
241///
242/// Runs after `/initfs/init.target` so precedence is kernel cmdline >
243/// `/initfs/init.target` > `[policy] target`. A kernel `target` overrides only
244/// when explicitly present; `disable` lists are always unioned. Unrelated
245/// kernel keys are ignored.
246fn apply_kernel_cmdline(policy: &mut Policy) {
247    let mut buf = [0u8; 2048];
248    let n = match call::getcmdline(&mut buf) {
249        Ok(n) => n,
250        Err(e) => {
251            log("[init] cmdline: read failed: ");
252            log(e.name());
253            log("\n");
254            return;
255        }
256    };
257    let len = n.min(buf.len());
258    let cmdline = match core::str::from_utf8(&buf[..len]) {
259        Ok(text) => text,
260        Err(_) => {
261            log("[init] cmdline: invalid UTF-8, ignored\n");
262            return;
263        }
264    };
265
266    let selection = Selection::from_kernel_cmdline(cmdline);
267    if !cmdline_sets_target(cmdline) && selection.disabled.is_empty() {
268        return;
269    }
270    if cmdline_sets_target(cmdline) {
271        policy.selection.profile = selection.profile;
272    }
273    for name in selection.disabled {
274        if !policy.selection.is_disabled(&name) {
275            policy.selection.disabled.push(name);
276        }
277    }
278    log("[init] cmdline target=");
279    log(policy.selection.profile.as_str());
280    log(" disable=");
281    log_u32(policy.selection.disabled.len() as u32);
282    log("\n");
283}
284
285///
286/// `reserved` holds the SIDs of live children so a reload cannot hand one of
287/// them to a newly added silo. Shared by `_start` and the `/srv/init` `reload`
288/// command so both apply the same parse, overlay merge and policy rules.
289pub(crate) fn rebuild_plan(reserved: &[u32]) -> BootPlan {
290    let (mut silos, mut diagnostics, policy) = load_primary_silos();
291    diagnostics.extend(merge_wasm_test_overlay(&mut silos));
292    build_plan_with_reserved(silos, diagnostics, policy, reserved)
293}
294
295/// Merges `/initfs/wasm-test.toml` silos that are not already declared.
296fn merge_wasm_test_overlay(silos: &mut Vec<SiloDef>) -> Vec<Diagnostic> {
297    let data = match read_file("/initfs/wasm-test.toml") {
298        Ok(data) => data,
299        Err(_) => return Vec::new(),
300    };
301    let text = match core::str::from_utf8(&data) {
302        Ok(text) => text,
303        Err(_) => {
304            log("[init] Invalid UTF-8 in /initfs/wasm-test.toml, skipping overlay\n");
305            return Vec::new();
306        }
307    };
308    let parsed = parse_config(text);
309    if parsed.silos.is_empty() {
310        return parsed.diagnostics;
311    }
312
313    let added = merge_overlay(silos, parsed.silos);
314    if added > 0 {
315        log("[init] Applied wasm-test overlay silos: ");
316        log_u32(added as u32);
317        log("\n");
318    }
319    parsed.diagnostics
320}
321
322// ---------------------------------------------------------------------------
323// EXECUTION LOGIC
324// ---------------------------------------------------------------------------
325
326const SILO_FLAG_ADMIN: u64 = 1 << 0;
327const SILO_FLAG_GRAPHICS: u64 = 1 << 1;
328const SILO_FLAG_WEBRTC_NATIVE: u64 = 1 << 2;
329const SILO_FLAG_GRAPHICS_READ_ONLY: u64 = 1 << 3;
330const SILO_FLAG_WEBRTC_TURN_FORCE: u64 = 1 << 4;
331
332/// Builds the kernel [`SiloConfig`] for one planned silo.
333fn build_silo_config(silo: &init_config::PlannedSilo) -> SiloConfig {
334    let mut flags = 0u64;
335    // The admin policy was already validated: only SYS may request it.
336    if silo.admin {
337        flags |= SILO_FLAG_ADMIN;
338    }
339    if silo.graphics.enabled {
340        flags |= SILO_FLAG_GRAPHICS;
341        if silo.graphics.mode == "webrtc-native" {
342            flags |= SILO_FLAG_WEBRTC_NATIVE;
343        }
344        if silo.graphics.read_only {
345            flags |= SILO_FLAG_GRAPHICS_READ_ONLY;
346        }
347        if silo.graphics.turn_policy == "force" {
348            flags |= SILO_FLAG_WEBRTC_TURN_FORCE;
349        }
350    }
351
352    let mut config = SiloConfig::zero();
353    config.sid = silo.sid;
354    config.mode = silo.mode.0;
355    config.family = silo.family_id;
356    config.flags = flags;
357    config.graphics_max_sessions = if silo.graphics.enabled {
358        if silo.graphics.max_sessions == 0 {
359            1
360        } else {
361            silo.graphics.max_sessions
362        }
363    } else {
364        0
365    };
366    config.graphics_session_ttl_sec = if silo.graphics.enabled {
367        if silo.graphics.session_ttl_sec == 0 {
368            1800
369        } else {
370            silo.graphics.session_ttl_sec
371        }
372    } else {
373        0
374    };
375    config.dma_max_domains = silo.dma.max_domains;
376    config.dma_max_bytes = silo.dma.max_bytes;
377    config.dma_iova_base = silo.dma.iova_base;
378    config.dma_iova_limit = silo.dma.iova_limit;
379    config.dma_fault_policy = silo.dma.fault_policy.to_u8();
380    config
381}
382
383/// Waits until `path` resolves through `ipc_connect`, with bounded backoff.
384///
385/// Probes with a closed handle immediately: connecting is the readiness signal,
386/// not a handle we intend to keep. Backoff doubles from 10 ms to 250 ms and the
387/// total wait is capped at ~10 s.
388fn wait_for_service(path: &str) -> bool {
389    let mut delay = 10u32;
390    let mut waited = 0u32;
391    loop {
392        if let Ok(handle) = call::ipc_connect(path.as_bytes()) {
393            let _ = call::handle_close(handle);
394            return true;
395        }
396        if waited >= 10_000 {
397            return false;
398        }
399        supervisor::sleep_ms(delay);
400        waited += delay;
401        delay = (delay * 2).min(250);
402    }
403}
404
405/// Runtime binding of one planned silo, preserved after boot.
406pub(crate) struct SiloRuntime {
407    pub name: String,
408    pub sid: u32,
409    pub handle: usize,
410    pub desired: PlannedSilo,
411}
412
413/// Implements boot silos.
414fn boot_silos(
415    plan: BootPlan,
416    supervised: &mut Vec<supervisor::SupervisedChild>,
417    runtimes: &mut Vec<SiloRuntime>,
418) {
419    for s_def in plan.silos {
420        boot_silo(s_def, supervised, runtimes);
421    }
422}
423
424/// Converts declared grants into wire descriptors.
425///
426/// Path grants need their bytes to stay alive until the syscall returns, so the
427/// caller keeps the returned buffer vector in scope.
428fn grant_descriptors(grants: &[init_config::Grant]) -> (Vec<SiloGrantDesc>, Vec<Vec<u8>>) {
429    let mut descs = Vec::with_capacity(grants.len());
430    let mut buffers: Vec<Vec<u8>> = Vec::new();
431    for grant in grants {
432        let desc = match &grant.kind {
433            init_config::GrantKind::Path { service, write } => {
434                let bytes = service.as_str().as_bytes().to_vec();
435                let desc = SiloGrantDesc {
436                    kind: SILO_GRANT_PATH,
437                    access: if *write { SILO_GRANT_ACCESS_WRITE } else { 0 },
438                    id: bytes.as_ptr() as u64,
439                    len: bytes.len() as u64,
440                    _reserved: 0,
441                };
442                buffers.push(bytes);
443                desc
444            }
445            init_config::GrantKind::Irq(line) => SiloGrantDesc {
446                kind: SILO_GRANT_IRQ,
447                access: 0,
448                id: *line as u64,
449                len: 0,
450                _reserved: 0,
451            },
452            init_config::GrantKind::Pci(addr) => SiloGrantDesc {
453                kind: SILO_GRANT_PCI,
454                access: 0,
455                id: ((addr.bus as u64) << 16)
456                    | ((addr.device as u64) << 8)
457                    | (addr.function as u64),
458                len: 0,
459                _reserved: 0,
460            },
461            init_config::GrantKind::Dma(bytes) => SiloGrantDesc {
462                kind: SILO_GRANT_DMA,
463                access: 0,
464                id: *bytes,
465                len: 0,
466                _reserved: 0,
467            },
468        };
469        descs.push(desc);
470    }
471    (descs, buffers)
472}
473
474/// Applies `grants` to an editable silo.
475///
476/// The path buffers stay alive until `silo_grant` returns. Returns the kernel
477/// error name on failure so the caller can decide whether to keep the silo.
478fn apply_grants(silo_handle: usize, grants: &[init_config::Grant]) -> Result<(), &'static str> {
479    if grants.is_empty() {
480        return Ok(());
481    }
482    let (descs, _buffers) = grant_descriptors(grants);
483    // The syscall returns 0 on success; report the descriptor count.
484    call::silo_grant(silo_handle, &descs).map_err(|e| e.name())?;
485    log("[init] GRANTS: applied ");
486    log_u32(descs.len() as u32);
487    log("\n");
488    if grants
489        .iter()
490        .any(|g| matches!(g.kind, init_config::GrantKind::Irq(_)))
491    {
492        log(
493            "[init] NOTE: irq grants are stored by the kernel but no subsystem consumes them yet\n",
494        );
495    }
496    Ok(())
497}
498
499/// Starts every strate of `s_def` inside `silo_handle`.
500///
501/// Returns the number of strates that became active and registers each
502/// launched module with the supervisor. Shared by boot and in-place reload.
503fn start_strates(
504    silo_handle: usize,
505    s_def: &PlannedSilo,
506    supervised: &mut Vec<supervisor::SupervisedChild>,
507) -> u32 {
508    let mut active_strates = 0u32;
509
510    if s_def.strates.is_empty() {
511        log("[init] No strates declared for silo ");
512        log(&s_def.name);
513        log("\n");
514    }
515
516    for str_def in &s_def.strates {
517        match &str_def.kind {
518            PlannedKind::Elf | PlannedKind::WasmRuntime => {
519                log("[init]   -> Strate: ");
520                log(&str_def.name);
521                log("\n");
522                if let Some(launched) = launcher::launch_module(
523                    silo_handle,
524                    &str_def.name,
525                    &str_def.binary,
526                    str_def.sha256,
527                ) {
528                    supervisor::register(
529                        supervised,
530                        &str_def.name,
531                        launched.pid,
532                        silo_handle,
533                        launched.module_handle,
534                        &s_def.name,
535                        s_def.admin,
536                        str_def.restart,
537                        str_def.critical,
538                        str_def.max_restarts,
539                    );
540                    active_strates += 1;
541                }
542            }
543            PlannedKind::WasmApp { service_label } => {
544                log("[init]   -> Wasm-App: ");
545                log(&str_def.name);
546                log("\n");
547                // `init-config` already resolved the runtime service label.
548                let service_path = alloc::format!("/srv/strate-wasm/{}", service_label);
549                match launcher::run_wasm_app(&service_path, &str_def.binary) {
550                    Ok(()) => {
551                        log("[init]     wasm app started: ");
552                        log(&str_def.binary);
553                        log("\n");
554                        active_strates += 1;
555                    }
556                    Err(code) => {
557                        log("[init]     wasm app failed: status=0x");
558                        log_u32(code);
559                        log(" (service=");
560                        log(&service_path);
561                        log(", path=");
562                        log(&str_def.binary);
563                        log(")\n");
564                    }
565                }
566            }
567        }
568    }
569
570    active_strates
571}
572
573/// Creates and starts every strate of one planned silo.
574///
575/// A silo whose `requires` service is not reachable within the readiness budget
576/// is skipped: `init-config` already dropped its dependents from the plan.
577/// Returns the silo handle when at least one strate became active, and records
578/// the binding in `runtimes` so a later `reload` can reconfigure it in place.
579pub(crate) fn boot_silo(
580    s_def: PlannedSilo,
581    supervised: &mut Vec<supervisor::SupervisedChild>,
582    runtimes: &mut Vec<SiloRuntime>,
583) -> Option<usize> {
584    for path in &s_def.requires {
585        if !wait_for_service(path.as_str()) {
586            log("[init] DEGRADED: silo ");
587            log(&s_def.name);
588            log(" missing required service ");
589            log(path.as_str());
590            log(", skipping\n");
591            return None;
592        }
593    }
594
595    log("[init] Creating Silo: ");
596    log(&s_def.name);
597    log(" (SID=");
598    log_u32(s_def.sid);
599    log(")\n");
600
601    let config = build_silo_config(&s_def);
602
603    let silo_handle = match call::silo_create((&config as *const SiloConfig) as usize) {
604        Ok(h) => h,
605        Err(e) => {
606            log("[init] silo_create failed: ");
607            log(e.name());
608            log("\n");
609            return None;
610        }
611    };
612
613    // Apply declared grants before any strate is attached or started. With the
614    // kernel's deny-by-default-when-declared rule, a silo whose grants failed to
615    // apply must not run: it would silently run unrestricted.
616    if let Err(e) = apply_grants(silo_handle, &s_def.grants) {
617        log("[init] silo_grant failed: ");
618        log(&s_def.name);
619        log(" ");
620        log(e);
621        log("\n");
622        if let Err(e) = call::silo_destroy(silo_handle) {
623            log("[init] silo_destroy failed: ");
624            log(e.name());
625            log(", stopping it instead\n");
626            let _ = call::silo_stop(silo_handle);
627        }
628        let _ = call::handle_close(silo_handle);
629        return None;
630    }
631
632    if let Some(ref lbl) = s_def.label {
633        if let Err(e) = call::silo_rename(silo_handle, lbl.as_ptr() as usize, lbl.len()) {
634            log("[init] silo_rename failed: ");
635            log(e.name());
636            log("\n");
637        }
638    }
639
640    let active_strates = start_strates(silo_handle, &s_def, supervised);
641
642    // A silo whose strates all failed must not stay open: a task-less
643    // `Ready` silo (and the module it still references) would be kept for
644    // the rest of the boot. Destroy it, then release our handle.
645    if active_strates == 0 {
646        log("[init] No active strate in silo ");
647        log(&s_def.name);
648        log(", destroying it\n");
649        if let Err(e) = call::silo_destroy(silo_handle) {
650            log("[init] silo_destroy failed: ");
651            log(e.name());
652            log(", stopping it instead\n");
653            let _ = call::silo_stop(silo_handle);
654        }
655        let _ = call::handle_close(silo_handle);
656        return None;
657    }
658
659    runtimes.push(SiloRuntime {
660        name: s_def.name.clone(),
661        sid: s_def.sid,
662        handle: silo_handle,
663        desired: s_def,
664    });
665    Some(silo_handle)
666}
667
668/// Reconfigures an existing (stopped) silo in place and restarts its strates.
669///
670/// `s_def` must carry the live SID (the reload path forces it). Config and the
671/// grant set are replaced on the same handle; no silo is created or destroyed.
672/// Returns the number of strates that became active.
673pub(crate) fn reconfigure_silo(
674    handle: usize,
675    s_def: &PlannedSilo,
676    supervised: &mut Vec<supervisor::SupervisedChild>,
677) -> Result<u32, &'static str> {
678    let config = build_silo_config(s_def);
679    call::silo_config(handle, (&config as *const SiloConfig) as usize).map_err(|e| e.name())?;
680    call::silo_grant_reset(handle).map_err(|e| e.name())?;
681    apply_grants(handle, &s_def.grants)?;
682
683    if let Some(ref lbl) = s_def.label {
684        if let Err(e) = call::silo_rename(handle, lbl.as_ptr() as usize, lbl.len()) {
685            log("[init] silo_rename failed: ");
686            log(e.name());
687            log("\n");
688        }
689    }
690
691    Ok(start_strates(handle, s_def, supervised))
692}
693
694#[unsafe(no_mangle)]
695/// Implements start.
696pub unsafe extern "C" fn _start() -> ! {
697    log("[init] Strat9 hierarchical boot starting\n");
698    log("[init] Stage: load primary silos\n");
699    let (mut silos, mut diagnostics, mut policy) = load_primary_silos();
700    log("[init] Stage: apply init.target\n");
701    apply_init_target(&mut policy);
702    log("[init] Stage: apply kernel cmdline\n");
703    apply_kernel_cmdline(&mut policy);
704    log("[init] Stage: merge wasm overlay\n");
705    diagnostics.extend(merge_wasm_test_overlay(&mut silos));
706    log("[init] Stage: ensure required silos\n");
707    let plan = build_plan_with_policy(silos, diagnostics, policy);
708    for diagnostic in &plan.diagnostics {
709        log_diagnostic(diagnostic);
710    }
711    for silo in &plan.silos {
712        if !silo.grants.is_empty() {
713            log("[init] GRANTS: ");
714            log(&silo.name);
715            log(" declares ");
716            log_u32(silo.grants.len() as u32);
717            log(" grant(s)\n");
718        }
719    }
720    log("[init] Stage: boot silos\n");
721    let mut supervised = Vec::with_capacity(supervisor::CAPACITY);
722    // The plan is already in dependency order: the supervisor reuses it to stop
723    // children in reverse order on shutdown.
724    let plan_order: Vec<alloc::string::String> =
725        plan.silos.iter().map(|s| s.name.clone()).collect();
726    let mut runtimes = Vec::new();
727    boot_silos(plan, &mut supervised, &mut runtimes);
728    log("[init] Boot complete.\n");
729    let control_port = control::init_port();
730    supervisor::run(supervised, control_port, plan_order, runtimes);
731}
732
733#[panic_handler]
734fn panic(info: &PanicInfo) -> ! {
735    call::handle_panic("init", info)
736}