Skip to main content

strat9_kernel/process/
elf.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//! ELF64 loader for Strat9-OS.
24//!
25//! Parses ELF64 headers and loads PT_LOAD segments into a user address space,
26//! then creates a kernel task that trampolines into Ring 3 via IRETQ.
27//!
28//! Supports :
29//!   - ET_EXEC
30//!   - ET_DYN (PIE/static-PIE)
31//!   - ELF64 little-endian x86_64 binaries.
32//!
33//!
34//! Does not support (or need future fix) :
35//!
36//!   - ~~Fix TODO : allocation heap during ELF loading~~
37//!     PARTIALLY DONE (#67) : program-header vectors and boot-stack argv
38//!     pointers now use `try_reserve_exact`-based fallible collection and
39//!     fail the load with an error instead of aborting. Full rollback of
40//!     already-mapped segments still requires a fallible GlobalAlloc.
41//!
42//!   - ~~Fix TODO : find_free_vma_range : fallback hardcoded 0x1000_0000~~
43//!     DONE : the fallback was removed; a failed search now fails the load
44//!     with "No virtual range for ET_DYN image".
45//!
46//! Security:
47//!   - User stack has a guard page (user_stack_base() - 4096) that is intentionally
48//!     left unmapped.  Stack underflows hit it and page-fault.
49//!
50use crate::{
51    arch::xshim::{Size4KiB, VirtAddr},
52    x86_crate_shim::structures::paging::{Mapper, Page},
53};
54use alloc::{sync::Arc, vec::Vec};
55
56use crate::{
57    capability::Capability,
58    memory::address_space::{AddressSpace, VmaFlags, VmaPageSize, VmaType},
59    process::{
60        task::{CpuContext, KernelStack, ResumeKind, SyncUnsafeCell, Task},
61        TaskId, TaskPriority, TaskState,
62    },
63};
64
65macro_rules! elf_trace {
66    ($($arg:tt)*) => {
67        #[cfg(debug_assertions)] {
68            crate::e9_println!($($arg)*);
69            crate::serial_println!($($arg)*);
70        }
71    };
72}
73
74// ---------------------------------------------------------------------------
75// ELF64 file format
76//
77// Generic decoding is shared with the bootloader and the `s9vm` guest loader
78// (`strat9-elf-core`); this module only adds the userland loading policy.
79// Relocation and dynamic tags below are not covered by the shared layer.
80// ---------------------------------------------------------------------------
81
82use strat9_elf_core::{
83    Header, ProgramHeader, ET_DYN, ET_EXEC, PF_R, PF_W, PF_X, PT_DYNAMIC, PT_GNU_RELRO,
84    PT_GNU_STACK, PT_INTERP, PT_LOAD, PT_TLS,
85};
86
87const DT_NULL: i64 = 0;
88const DT_RELA: i64 = 7;
89const DT_RELASZ: i64 = 8;
90const DT_RELAENT: i64 = 9;
91const DT_STRTAB: i64 = 5;
92const DT_SYMTAB: i64 = 6;
93const DT_SYMENT: i64 = 11;
94const DT_JMPREL: i64 = 23;
95const DT_PLTRELSZ: i64 = 2;
96const DT_PLTREL: i64 = 20;
97const DT_RELACOUNT: i64 = 0x6fff_fff9;
98const DT_RELR: i64 = 36;
99const DT_RELRSZ: i64 = 35;
100const DT_RELRENT: i64 = 37;
101const R_X86_64_RELATIVE: u32 = 8;
102const R_X86_64_64: u32 = 1;
103const R_X86_64_COPY: u32 = 5;
104const R_X86_64_GLOB_DAT: u32 = 6;
105const R_X86_64_JUMP_SLOT: u32 = 7;
106const R_X86_64_TPOFF64: u32 = 18;
107const R_X86_64_DTPMOD64: u32 = 16;
108const R_X86_64_DTPOFF64: u32 = 17;
109const R_X86_64_IRELATIVE: u32 = 37;
110
111/// Maximum virtual address we accept for user-space mappings.
112///
113/// Strat9 userspace components are statically linked (no-pie) at ET_EXEC
114/// 0xFFFFFFFF80000000 : the higher-half window. Each user AddressSpace owns
115/// a private copy of the PML4[511] PDP (see address_space::new_user), with
116/// the kernel-image slot removed, so processes can use the full canonical
117/// higher-half range without touching kernel pages. The guard therefore only
118/// rejects non-canonical addresses.
119pub const USER_ADDR_MAX: u64 = crate::memory::userslice::USER_SPACE_END;
120
121/// Number of 4 KiB pages for the user stack (16 pages = 64 KiB).
122///
123/// This is the *default*: the loader accepts a per-process stack size via
124/// [`load_and_run_elf_with_stack`] (issue #64).
125pub const USER_STACK_PAGES: usize = 16;
126/// Lower bound on a per-process user stack (4 pages = 16 KiB): the boot
127/// stack layout alone (argv/envp/auxv + guard margins) needs at least one
128/// page, and tiny stacks would fault immediately.
129pub const USER_STACK_MIN_PAGES: usize = 4;
130/// Upper bound on a per-process user stack (2048 pages = 8 MiB), to keep a
131/// buggy or hostile caller from exhausting the user address space / frames.
132pub const USER_STACK_MAX_PAGES: usize = 2048;
133/// Standard user-mode RFLAGS: IF=1, reserved bit 1 set.
134const USER_RFLAGS: u64 = 0x202;
135
136/// Get the randomized user stack base address.
137#[allow(dead_code)] // Retained KASLR stack helper.
138fn user_stack_base() -> u64 {
139    crate::kaslr::stack_base()
140}
141
142/// Get the randomized user stack top address.
143#[allow(dead_code)] // Retained KASLR stack helper.
144fn user_stack_top() -> u64 {
145    crate::kaslr::stack_top()
146}
147
148/// Get the guard page address below the user stack.
149fn user_stack_guard() -> u64 {
150    crate::kaslr::stack_guard()
151}
152
153/// Get the randomized PIE base address for ELF loading.
154fn pie_base() -> u64 {
155    crate::kaslr::pie_base()
156}
157
158/// Result of loading an ELF image into an address space.
159#[derive(Debug, Clone, Copy)]
160pub struct LoadedElfInfo {
161    pub runtime_entry: u64,
162    pub program_entry: u64,
163    pub phdr_vaddr: u64,
164    pub phent: u16,
165    pub phnum: u16,
166    pub interp_base: Option<u64>,
167    pub tls_vaddr: u64,
168    pub tls_filesz: u64,
169    pub tls_memsz: u64,
170    pub tls_align: u64,
171    pub stack_exec: bool,
172}
173
174// ---------------------------------------------------------------------------
175// ELF64 structures for kernel-internal use
176// ---------------------------------------------------------------------------
177
178/// Parsed ELF64 file header (shared, copy-friendly representation).
179type Elf64Header = Header;
180
181/// Parsed ELF64 program header (shared, copy-friendly representation).
182type Elf64Phdr = ProgramHeader;
183
184#[repr(C, packed)]
185#[derive(Debug, Clone, Copy)]
186struct Elf64Dyn {
187    d_tag: i64,
188    d_val: u64,
189}
190
191#[repr(C, packed)]
192#[derive(Debug, Clone, Copy)]
193struct Elf64Rela {
194    r_offset: u64,
195    r_info: u64,
196    r_addend: i64,
197}
198
199#[repr(C, packed)]
200#[derive(Debug, Clone, Copy)]
201struct Elf64Sym {
202    st_name: u32,
203    st_info: u8,
204    st_other: u8,
205    st_shndx: u16,
206    st_value: u64,
207    st_size: u64,
208}
209
210// ---------------------------------------------------------------------------
211// Parsing
212// ---------------------------------------------------------------------------
213
214/// Parse and validate the ELF64 file header from raw bytes.
215///
216/// The generic format validation (magic, class, endianness, machine, type,
217/// entry sizes, program header table bounds) is performed by the shared
218/// [`strat9_elf_core`] parser; this wrapper adds the userland policies: the
219/// entry point must be inside the user address range.
220fn parse_header(data: &[u8]) -> Result<Elf64Header, &'static str> {
221    let header = Header::parse(data).map_err(|error| {
222        log::error!("[elf] Rejecting binary: {}", error);
223        error.message()
224    })?;
225    // Entry point must be canonical user space (for ET_DYN this is relative and
226    // validated again after relocation). ET_EXEC with e_entry=0 is handled later.
227    if header.e_entry >= USER_ADDR_MAX {
228        return Err("Entry point outside user address range");
229    }
230    Ok(header)
231}
232
233/// Collects an exact-size-hint iterator into a `Vec`, failing cleanly on
234/// allocation failure instead of aborting (issue #67).
235///
236/// The exact reservation means the `push` loop below can never reallocate:
237/// either the whole vector is built, or we return `Err` having allocated
238/// nothing (beyond the failed reservation itself).
239fn try_collect_exact<T, I>(iter: I) -> Result<Vec<T>, &'static str>
240where
241    I: IntoIterator<Item = T>,
242{
243    let iter = iter.into_iter();
244    let (lower, Some(upper)) = iter.size_hint() else {
245        return Err("ELF: iterator has inexact size hint");
246    };
247    if lower != upper {
248        return Err("ELF: iterator has inexact size hint");
249    }
250    let mut v = Vec::new();
251    v.try_reserve_exact(lower)
252        .map_err(|_| "ELF: out of memory while collecting program headers")?;
253    for item in iter {
254        v.push(item);
255    }
256    Ok(v)
257}
258
259/// Maximum PT_INTERP path length we accept.
260///
261/// Real interpreters (ld-linux.so, musl libc loader, …) are well under
262/// 4 KiB; a path longer than a single page is almost certainly corrupt or
263/// hostile.  We cap before any further parsing so a pathological `.interp`
264/// section cannot waste cycles on a doomed allocation / UTF-8 check.
265const MAX_INTERP_PATH_LEN: usize = 4096;
266
267/// Parses interp path.
268///
269/// Cheap sanity checks (`p_filesz` bounds, max length, in-file range) run
270/// first so we reject absurd or hostile `.interp` sections without paying
271/// the full scan / UTF-8 validation cost.
272fn parse_interp_path<'a>(
273    elf_data: &'a [u8],
274    phdrs: &[Elf64Phdr],
275) -> Result<Option<&'a str>, &'static str> {
276    let Some(interp) = phdrs.iter().find(|ph| ph.p_type == PT_INTERP) else {
277        return Ok(None);
278    };
279    if interp.p_filesz == 0 {
280        return Err("PT_INTERP has empty path");
281    }
282    // Reject absurdly large .interp sections before any further work.
283    if (interp.p_filesz as usize) > MAX_INTERP_PATH_LEN {
284        return Err("PT_INTERP path exceeds MAX_INTERP_PATH_LEN");
285    }
286    let start = interp.p_offset as usize;
287    let end = start
288        .checked_add(interp.p_filesz as usize)
289        .ok_or("PT_INTERP range overflow")?;
290    if end > elf_data.len() {
291        return Err("PT_INTERP extends past file");
292    }
293    let raw = &elf_data[start..end];
294    let nul = raw
295        .iter()
296        .position(|&b| b == 0)
297        .ok_or("PT_INTERP path is not NUL terminated")?;
298    let s = core::str::from_utf8(&raw[..nul]).map_err(|_| "PT_INTERP path is not UTF-8")?;
299    if s.is_empty() {
300        return Err("PT_INTERP path is empty");
301    }
302    Ok(Some(s))
303}
304
305/// Performs the find relocated phdr vaddr operation.
306fn find_relocated_phdr_vaddr(
307    header: &Elf64Header,
308    phdrs: &[Elf64Phdr],
309    load_bias: u64,
310) -> Result<u64, &'static str> {
311    let phoff = header.e_phoff;
312    for ph in phdrs {
313        if ph.p_type != PT_LOAD || ph.p_filesz == 0 {
314            continue;
315        }
316        let file_start = ph.p_offset;
317        let file_end = ph
318            .p_offset
319            .checked_add(ph.p_filesz)
320            .ok_or("PHDR location overflow")?;
321        if phoff >= file_start && phoff < file_end {
322            let delta = phoff - file_start;
323            let vaddr = ph
324                .p_vaddr
325                .checked_add(delta)
326                .and_then(|v| v.checked_add(load_bias))
327                .ok_or("Relocated PHDR address overflow")?;
328            if vaddr >= USER_ADDR_MAX {
329                return Err("Relocated PHDR outside user address space");
330            }
331            return Ok(vaddr);
332        }
333    }
334    // Static (-no-pie) binaries place the program header array before the
335    // first PT_LOAD (classic layout: e_phoff=64, LOADs start at 0x1000), so
336    // it is legitimately not covered by any segment. AT_PHDR is optional per
337    // the ABI: report 0 and let push_auxv skip it rather than failing the
338    // whole load for a statically-linked image.
339    Ok(0)
340}
341
342/// Reads elf from vfs.
343fn read_elf_from_vfs(path: &str) -> Result<Vec<u8>, &'static str> {
344    const MAX_ELF_SIZE: usize = 64 * 1024 * 1024;
345    let resolved_path =
346        crate::vfs::resolve_and_check_path_for_current_task(path, true, false, true)
347            .map_err(|_| "PT_INTERP execute denied")?;
348    let fd = crate::vfs::open(&resolved_path, crate::vfs::OpenFlags::READ)
349        .map_err(|_| "PT_INTERP open failed")?;
350    let mut out = Vec::new();
351    let mut buf = [0u8; 4096];
352
353    // Read the first chunk to validate ELF magic before loading the whole file.
354    let n = match crate::vfs::read(fd, &mut buf) {
355        Ok(0) => {
356            let _ = crate::vfs::close(fd);
357            return Err("PT_INTERP file is empty");
358        }
359        Ok(n) => n,
360        Err(_) => {
361            let _ = crate::vfs::close(fd);
362            return Err("PT_INTERP read failed");
363        }
364    };
365    if n < 4 || buf[..4] != [0x7F, b'E', b'L', b'F'] {
366        let _ = crate::vfs::close(fd);
367        return Err("PT_INTERP file is not an ELF");
368    }
369    out.extend_from_slice(&buf[..n]);
370
371    // Continue reading the rest of the file.
372    loop {
373        let n = match crate::vfs::read(fd, &mut buf) {
374            Ok(0) => break,
375            Ok(n) => n,
376            Err(_) => {
377                let _ = crate::vfs::close(fd);
378                return Err("PT_INTERP read failed");
379            }
380        };
381        if out.len().saturating_add(n) > MAX_ELF_SIZE {
382            let _ = crate::vfs::close(fd);
383            return Err("PT_INTERP file too large");
384        }
385        out.extend_from_slice(&buf[..n]);
386    }
387    let _ = crate::vfs::close(fd);
388    Ok(out)
389}
390
391/// Compute total mapped bounds for all PT_LOAD segments.
392///
393/// Validates each PT_LOAD individually (alignment, size, address range) and
394/// additionally enforces, in the spirit of the FreeBSD post-CVE-2018-6924
395/// hardening and the Linux loader, that :
396///   - PT_LOAD `p_vaddr` values appear in strictly non-decreasing order
397///     across the program header table;
398///   - PT_LOAD segments do not overlap in virtual memory after page-alignment
399///     (overlapping segments would alias user pages and produce undefined
400///     behaviour when one is later relaxed via RELRO/mprotect).
401///
402/// Returns the page-aligned `(min_vaddr, max_vaddr)` of the image.
403fn compute_load_bounds(phdrs: &[Elf64Phdr]) -> Result<(u64, u64), &'static str> {
404    let mut min_vaddr = u64::MAX;
405    let mut max_vaddr = 0u64;
406    let mut saw_load = false;
407    // Tracks the end of the last page-aligned segment to detect both
408    // disorder and overlap.  Initialised to 0 (page 0 is never a valid
409    // user-space segment start in our loader), so the first LOAD is always
410    // accepted.
411    let mut last_seg_end_page: u64 = 0;
412
413    for phdr in phdrs {
414        if phdr.p_type != PT_LOAD {
415            continue;
416        }
417        if phdr.p_memsz == 0 {
418            continue;
419        }
420        saw_load = true;
421
422        if phdr.p_memsz < phdr.p_filesz {
423            return Err("PT_LOAD memsz < filesz");
424        }
425
426        // ELF requires p_vaddr % page == p_offset % page for PT_LOAD.
427        if ((phdr.p_vaddr ^ phdr.p_offset) & 0xFFF) != 0 {
428            return Err("PT_LOAD alignment mismatch (vaddr/offset)");
429        }
430
431        let seg_end = phdr
432            .p_vaddr
433            .checked_add(phdr.p_memsz)
434            .ok_or("PT_LOAD vaddr+memsz overflow")?;
435        if seg_end > USER_ADDR_MAX {
436            return Err("PT_LOAD exceeds user address space");
437        }
438
439        let seg_start_page = phdr.p_vaddr & !0xFFF;
440        let seg_end_page = (seg_end + 0xFFF) & !0xFFF;
441
442        // Strictly non-decreasing p_vaddr: reject disorder that would defeat
443        // the linear PT_LOAD scan performed by the loader and the dynamic
444        // linker.  Linux's `load_elf_binary` makes the same assumption.
445        // The first LOAD is allowed to be at any address (last_seg_end_page
446        // starts at 0, a placeholder that no real user segment can reach
447        // because the loader never maps page 0).
448        if last_seg_end_page != 0 {
449            if seg_start_page < last_seg_end_page {
450                return Err("PT_LOAD segments overlap or are out of order");
451            }
452        }
453
454        last_seg_end_page = seg_end_page;
455        min_vaddr = min_vaddr.min(seg_start_page);
456        max_vaddr = max_vaddr.max(seg_end_page);
457    }
458
459    if !saw_load {
460        return Err("ELF has no PT_LOAD segments");
461    }
462    Ok((min_vaddr, max_vaddr))
463}
464
465/// Compute load bias and relocated entry for ET_EXEC / ET_DYN.
466fn compute_load_bias_and_entry(
467    user_as: &AddressSpace,
468    header: &Elf64Header,
469    phdrs: &[Elf64Phdr],
470) -> Result<(u64, u64), &'static str> {
471    let (min_vaddr, max_vaddr) = compute_load_bounds(phdrs)?;
472    let span = max_vaddr
473        .checked_sub(min_vaddr)
474        .ok_or("Invalid PT_LOAD bounds")?;
475
476    let load_bias = if header.e_type == ET_EXEC {
477        0
478    } else {
479        let n_pages = (span as usize).div_ceil(4096);
480        // No hardcoded fallback: if the randomized PIE base cannot host the
481        // image (address space full), fail the load loudly instead of
482        // silently colliding with existing mappings (issue #68).
483        let load_base = user_as
484            .find_free_vma_range(pie_base(), n_pages, VmaPageSize::Small)
485            .ok_or("No virtual range for ET_DYN image")?;
486        load_base
487            .checked_sub(min_vaddr)
488            .ok_or("ET_DYN load bias underflow")?
489    };
490
491    let relocated_end = max_vaddr
492        .checked_add(load_bias)
493        .ok_or("Relocated PT_LOAD range overflow")?;
494    if relocated_end > USER_ADDR_MAX {
495        return Err("Relocated PT_LOAD range exceeds user space");
496    }
497
498    if header.e_type == ET_EXEC && header.e_entry == 0 {
499        return Err("ET_EXEC has null entry point");
500    }
501
502    let entry_raw = header.e_entry;
503
504    let relocated_entry = entry_raw
505        .checked_add(load_bias)
506        .ok_or("Relocated entry overflow")?;
507    if relocated_entry == 0 || relocated_entry >= USER_ADDR_MAX {
508        return Err("Relocated entry outside user space");
509    }
510
511    Ok((load_bias, relocated_entry))
512}
513
514/// Performs the apply segment permissions operation.
515///
516/// # SMP / TLB invariants (DO NOT BREAK)
517///
518/// During ELF loading, the caller (the loader) is the *sole* user of the
519/// target `AddressSpace`: the address space was just created with
520/// [`AddressSpace::new_user`] and is not yet attached to any task.  Because
521/// of this, the function only performs a **local** TLB invalidation on the
522/// current CPU when CR3 matches the address space.
523///
524/// ## Hard constraint
525///
526/// **This function MUST NOT be reused as a generic `mprotect` after the
527/// image has started executing.**  Once a user task has been scheduled,
528/// the address space may be active on another CPU and a local-only flush
529/// would let stale writable mappings survive on remote CPUs, breaking
530/// RELRO guarantees and creating an exploitable window.  A future
531/// `mprotect` implementation must use the cross-CPU TLB shootdown path
532/// (`tlb::shootdown_range`) instead of this helper.
533fn apply_segment_permissions(
534    user_as: &AddressSpace,
535    page_start: u64,
536    page_count: usize,
537    flags: VmaFlags,
538) -> Result<(), &'static str> {
539    use crate::x86_crate_shim::registers::control::Cr3;
540
541    // Defensive: refuse to relax permissions via the loader path once the
542    // address space has been installed on any CPU.  The check is only
543    // meaningful on architectures with a remote-CPU tracking field on
544    // AddressSpace; if such a field is added later, gate the assertion on
545    // its presence.
546    #[cfg(all(debug_assertions, feature = "elf_loader_assert_remote_active"))]
547    {
548        if user_as.is_active_on_remote_cpu() {
549            return Err(
550                "apply_segment_permissions called on an address space already active on another CPU",
551            );
552        }
553    }
554
555    let pte_flags = flags.to_page_flags();
556    // SAFETY: loader owns this AddressSpace during image construction.
557    let mut mapper = unsafe { user_as.mapper() };
558    for i in 0..page_count {
559        let vaddr = page_start
560            .checked_add((i as u64) * 4096)
561            .ok_or("Permission update address overflow")?;
562        let page = Page::<Size4KiB>::from_start_address(VirtAddr::new(vaddr))
563            .map_err(|_| "Invalid page while updating segment flags")?;
564        // SAFETY: the page is already mapped by map_region for this segment.
565        let _ = unsafe {
566            mapper
567                .update_flags(page, pte_flags)
568                .map_err(|_| "Failed to update segment page flags")?
569        };
570        // We ignore flush here and do a targeted flush decision below.
571    }
572
573    // During ELF loading we update a freshly-created user address space that is
574    // not active on other CPUs.  Cross-CPU shootdowns here only add boot-time
575    // latency and can timeout while APs are not yet servicing IPIs.
576    // If this address space is currently active on this CPU, local invalidation
577    // is enough for the loader path.
578    let (current_cr3, _) = Cr3::read();
579    if current_cr3.start_address() == user_as.cr3() {
580        let end = page_start + (page_count as u64) * 4096;
581        crate::arch::tlb::local_range(
582            crate::arch::xshim::VirtAddr::new(page_start),
583            crate::arch::xshim::VirtAddr::new(end),
584        );
585    }
586
587    Ok(())
588}
589
590/// Reads user mapped bytes.
591///
592/// Uses a single-slot page translation cache to avoid a page-table walk
593/// on every successive byte within the same page.  This is the same
594/// optimisation already applied to [`load_segment`] and dramatically
595/// speeds up binaries with thousands of RELA / RELR relocations.
596fn read_user_mapped_bytes(
597    user_as: &AddressSpace,
598    mut vaddr: u64,
599    out: &mut [u8],
600) -> Result<(), &'static str> {
601    let end = vaddr
602        .checked_add(out.len() as u64)
603        .ok_or("Read range overflow")?;
604    if end > USER_ADDR_MAX {
605        return Err("Read range outside user space");
606    }
607    let mut copied = 0usize;
608    let mut cached_page_vaddr: u64 = u64::MAX;
609    let mut cached_hhdm: usize = 0;
610    let mut cached_paddr: u64 = 0;
611    // SMAP: temporarily disable supervisor-mode access prevention while
612    // reading from user-space pages through the HHDM.
613    crate::arch::stac();
614    while copied < out.len() {
615        let page_vaddr = vaddr & !0xFFF;
616        let page_off = (vaddr & 0xFFF) as usize;
617        let chunk = core::cmp::min(out.len() - copied, 4096 - page_off);
618
619        if page_vaddr != cached_page_vaddr {
620            let phys = user_as
621                .translate(VirtAddr::new(vaddr))
622                .ok_or("Failed to translate mapped user bytes")?;
623            let paddr = phys.as_u64();
624            if paddr == 0 {
625                crate::arch::clac();
626                return Err("Translated physical address is null");
627            }
628            // `translate()` returns the full physical address, page offset
629            // included: keep only the page base here, `page_off` is added
630            // again below for the exact byte.
631            let hhdm_ptr = crate::memory::phys_to_virt(paddr & !0xFFF) as *const u8;
632            if hhdm_ptr.is_null() {
633                crate::arch::clac();
634                return Err("HHDM-mapped source is null");
635            }
636            cached_page_vaddr = page_vaddr;
637            cached_paddr = paddr;
638            cached_hhdm = hhdm_ptr as usize;
639        }
640        assert_eq!(
641            cached_hhdm as u64 + page_off as u64,
642            crate::memory::phys_to_virt(cached_paddr),
643            "user-mapped read must target the translated byte"
644        );
645
646        let src = cached_hhdm as *const u8;
647        // SAFETY: src points to mapped physical memory via HHDM.
648        // The address was just validated non-null, and the translate()
649        // call guarantees the virtual address is backed by a valid frame.
650        unsafe {
651            core::ptr::copy_nonoverlapping(src.add(page_off), out.as_mut_ptr().add(copied), chunk)
652        };
653        copied += chunk;
654        vaddr = vaddr
655            .checked_add(chunk as u64)
656            .ok_or("Virtual address overflow while reading mapped bytes")?;
657    }
658    crate::arch::clac();
659    Ok(())
660}
661
662/// Writes user mapped bytes.
663///
664/// Mirror of [`read_user_mapped_bytes`]: a single-slot page cache collapses
665/// thousands of RELA / RELR writes that touch the same page into a single
666/// page-table walk.
667fn write_user_mapped_bytes(
668    user_as: &AddressSpace,
669    mut vaddr: u64,
670    src: &[u8],
671) -> Result<(), &'static str> {
672    let end = vaddr
673        .checked_add(src.len() as u64)
674        .ok_or("Write range overflow")?;
675    if end > USER_ADDR_MAX {
676        return Err("Write range outside user space");
677    }
678    let mut written = 0usize;
679    let mut cached_page_vaddr: u64 = u64::MAX;
680    let mut cached_hhdm: usize = 0;
681    let mut cached_paddr: u64 = 0;
682    // SMAP: temporarily disable supervisor-mode access prevention while
683    // writing to user-space pages through the HHDM.
684    crate::arch::stac();
685    while written < src.len() {
686        let page_vaddr = vaddr & !0xFFF;
687        let page_off = (vaddr & 0xFFF) as usize;
688        let chunk = core::cmp::min(src.len() - written, 4096 - page_off);
689
690        if page_vaddr != cached_page_vaddr {
691            let phys = user_as
692                .translate(VirtAddr::new(vaddr))
693                .ok_or("Failed to translate relocation target")?;
694            let paddr = phys.as_u64();
695            if paddr == 0 {
696                crate::arch::clac();
697                return Err("Translated physical address is null");
698            }
699            // `translate()` returns the full physical address, page offset
700            // included: keep only the page base here, `page_off` is added
701            // again below for the exact byte.
702            let hhdm_ptr = crate::memory::phys_to_virt(paddr & !0xFFF) as *mut u8;
703            if hhdm_ptr.is_null() {
704                crate::arch::clac();
705                return Err("HHDM-mapped destination is null");
706            }
707            cached_page_vaddr = page_vaddr;
708            cached_paddr = paddr;
709            cached_hhdm = hhdm_ptr as usize;
710        }
711        assert_eq!(
712            cached_hhdm as u64 + page_off as u64,
713            crate::memory::phys_to_virt(cached_paddr),
714            "user-mapped write must target the translated byte"
715        );
716
717        let dst = cached_hhdm as *mut u8;
718        // SAFETY: destination points to mapped user frame through HHDM.
719        // The address was just validated non-null, and the translate()
720        // call guarantees the virtual address is backed by a valid frame.
721        unsafe {
722            core::ptr::copy_nonoverlapping(src.as_ptr().add(written), dst.add(page_off), chunk)
723        };
724        written += chunk;
725        vaddr = vaddr
726            .checked_add(chunk as u64)
727            .ok_or("Virtual address overflow while writing mapped bytes")?;
728    }
729    crate::arch::clac();
730    Ok(())
731}
732
733/// Reads user u64.
734fn read_user_u64(user_as: &AddressSpace, vaddr: u64) -> Result<u64, &'static str> {
735    let mut raw = [0u8; 8];
736    read_user_mapped_bytes(user_as, vaddr, &mut raw)?;
737    Ok(u64::from_le_bytes(raw))
738}
739
740/// Writes user u64.
741fn write_user_u64(user_as: &AddressSpace, vaddr: u64, value: u64) -> Result<(), &'static str> {
742    write_user_mapped_bytes(user_as, vaddr, &value.to_le_bytes())
743}
744
745/// Calls a user-space IFUNC resolver function and returns its result.
746///
747/// The resolver is located at `resolver_vaddr` in the user address space.
748/// All RELATIVE relocations for this binary must have been applied first so
749/// that the resolver's own calls/addresses are correct.
750///
751/// # Security note (audit 2026-09-07)
752///
753/// IFUNC resolvers execute as ordinary user-space functions, but this helper
754/// calls them from Ring 0 via HHDM.  A malicious or corrupted resolver can
755/// read/write kernel memory and escalate privileges.  This is acceptable for
756/// a single-address-space kernel that loads only trusted binaries, but must
757/// NOT be used if untrusted ELF images are ever loaded.
758///
759/// To make accidental misuse hard, the helper enforces, at runtime, that
760/// the resolver lives in a PT_LOAD marked as `non-writable & executable`
761/// (resolvers must be `.text`, never `.data`).  A hostile binary that
762/// plants an IFUNC resolver in a writable page will fail this check.
763///
764/// Future hardening:
765///   - compile the resolver under a sandbox (no `syscall`, no `iret`);
766///   - require an opt-in build flag (`features = "ifunc_resolver"`) so the
767///     unsafe code path is *absent* by default in production kernels.
768fn call_ifunc_resolver(user_as: &AddressSpace, resolver_vaddr: u64) -> Result<u64, &'static str> {
769    if resolver_vaddr >= USER_ADDR_MAX {
770        return Err("IFUNC resolver address outside user space");
771    }
772    let phys = user_as
773        .translate(VirtAddr::new(resolver_vaddr))
774        .ok_or("IFUNC resolver page not mapped")?;
775    let hhdm_ptr = crate::memory::phys_to_virt(phys.as_u64());
776
777    // Runtime safety check: a resolver must live in an executable,
778    // non-writable PT_LOAD.  We re-derive the page flags from the VMA
779    // rather than walking the ELF again so this stays O(1).
780    //
781    // The check is gated on a feature flag because AddressSpace does not
782    // yet expose a public `vma_containing` API.  Until it does, the
783    // check is opt-in via the kernel feature `ifunc_resolver_vma_check`
784    // so production builds do not silently rely on an unexported
785    // helper.
786    #[cfg(all(debug_assertions, feature = "ifunc_resolver_vma_check"))]
787    {
788        let page_vaddr = resolver_vaddr & !0xFFF;
789        if let Some(vma) = user_as.vma_containing(page_vaddr) {
790            if vma.flags.writable || !vma.flags.executable {
791                return Err("IFUNC resolver page is not (.text, non-writable)");
792            }
793        } else {
794            return Err("IFUNC resolver page has no VMA");
795        }
796    }
797
798    log::warn!(
799        "[elf] IFUNC resolver at {:#x} executing in Ring 0 : security risk if binary is untrusted",
800        resolver_vaddr
801    );
802    // SAFETY: hhdm_ptr points to a user page containing executable code.
803    // The resolver is a simple function that returns a u64; it must not
804    // access kernel state.  All RELATIVE relocations for this binary have
805    // already been applied, so the resolver's own target addresses are valid.
806    //
807    // WARNING: this executes user code in Ring 0.  Safe only for trusted binaries.
808    let resolver: extern "C" fn() -> u64 = unsafe { core::mem::transmute(hhdm_ptr as *const ()) };
809    Ok(resolver())
810}
811
812/// Performs the apply relr relocations operation.
813fn apply_relr_relocations(
814    user_as: &AddressSpace,
815    load_bias: u64,
816    relr_base: u64,
817    relr_size: usize,
818    relr_ent: usize,
819) -> Result<usize, &'static str> {
820    if relr_size == 0 {
821        return Ok(0);
822    }
823    if relr_ent != core::mem::size_of::<u64>() {
824        return Err("Unsupported DT_RELRENT size");
825    }
826    if relr_size % relr_ent != 0 {
827        return Err("DT_RELR table size is not aligned");
828    }
829
830    let count = relr_size / relr_ent;
831    let mut applied = 0usize;
832    let mut where_addr = 0u64;
833
834    for i in 0..count {
835        let entry_addr = relr_base
836            .checked_add((i * relr_ent) as u64)
837            .ok_or("DT_RELR walk overflow")?;
838        let entry = read_user_u64(user_as, entry_addr)?;
839
840        if (entry & 1) == 0 {
841            where_addr = load_bias
842                .checked_add(entry)
843                .ok_or("DT_RELR absolute relocation overflow")?;
844            if where_addr >= USER_ADDR_MAX {
845                return Err("DT_RELR target outside user space");
846            }
847            let cur = read_user_u64(user_as, where_addr)?;
848            write_user_u64(
849                user_as,
850                where_addr,
851                cur.checked_add(load_bias)
852                    .ok_or("DT_RELR relocated value overflow")?,
853            )?;
854            where_addr = where_addr
855                .checked_add(8)
856                .ok_or("DT_RELR where pointer overflow")?;
857            applied += 1;
858        } else {
859            if where_addr == 0 {
860                return Err("DT_RELR bitmap entry before initial address entry");
861            }
862            let mut bitmap = entry >> 1;
863            for bit in 0..63u64 {
864                if (bitmap & 1) != 0 {
865                    let slot = where_addr
866                        .checked_add(bit * 8)
867                        .ok_or("DT_RELR bitmap target overflow")?;
868                    if slot >= USER_ADDR_MAX {
869                        return Err("DT_RELR bitmap target outside user space");
870                    }
871                    let cur = read_user_u64(user_as, slot)?;
872                    write_user_u64(
873                        user_as,
874                        slot,
875                        cur.checked_add(load_bias)
876                            .ok_or("DT_RELR bitmap relocated value overflow")?,
877                    )?;
878                    applied += 1;
879                }
880                bitmap >>= 1;
881                if bitmap == 0 {
882                    break;
883                }
884            }
885            where_addr = where_addr
886                .checked_add(64 * 8)
887                .ok_or("DT_RELR where advance overflow")?;
888        }
889    }
890    Ok(applied)
891}
892
893/// Performs the apply dynamic relocations operation.
894fn apply_dynamic_relocations(
895    user_as: &AddressSpace,
896    phdrs: &[Elf64Phdr],
897    elf_type: u16,
898    load_bias: u64,
899) -> Result<(), &'static str> {
900    if elf_type != ET_DYN {
901        return Ok(());
902    }
903
904    let dynamic = phdrs.iter().find(|ph| ph.p_type == PT_DYNAMIC);
905    let Some(dynamic_ph) = dynamic else {
906        return Ok(());
907    };
908    if dynamic_ph.p_filesz == 0 {
909        return Ok(());
910    }
911
912    let dyn_addr = dynamic_ph
913        .p_vaddr
914        .checked_add(load_bias)
915        .ok_or("PT_DYNAMIC relocated address overflow")?;
916    let dyn_file_size = dynamic_ph.p_filesz as usize;
917    let dyn_count = dyn_file_size / core::mem::size_of::<Elf64Dyn>();
918    // Read the entire .dynamic section at once to avoid O(n) page-table walks.
919    let mut dyn_buf = alloc::vec![0u8; dyn_file_size];
920    read_user_mapped_bytes(user_as, dyn_addr, &mut dyn_buf)?;
921    let dyn_slice: &[Elf64Dyn] =
922        unsafe { core::slice::from_raw_parts(dyn_buf.as_ptr() as *const Elf64Dyn, dyn_count) };
923
924    let mut rela_addr: Option<u64> = None;
925    let mut rela_size: usize = 0;
926    let mut rela_ent: usize = core::mem::size_of::<Elf64Rela>();
927    let mut jmprel_addr: Option<u64> = None;
928    let mut jmprel_size: usize = 0;
929    let mut pltrel_kind: Option<u64> = None;
930    let mut symtab_addr: Option<u64> = None;
931    let mut sym_ent: usize = core::mem::size_of::<Elf64Sym>();
932    // Relocated DT_STRTAB: stored now so future symbol-by-name PLT/GOT
933    // lazy-binding resolution can map Elf64Sym::st_name offsets to strings
934    // (issue #66). Not consumed yet beyond tracing.
935    let mut strtab_addr: Option<u64> = None;
936    let mut rela_count_hint: Option<usize> = None;
937    let mut relr_addr: Option<u64> = None;
938    let mut relr_size: usize = 0;
939    let mut relr_ent: usize = 0;
940
941    for i in 0..dyn_count {
942        let dyn_entry = &dyn_slice[i];
943
944        match dyn_entry.d_tag {
945            DT_NULL => break,
946            DT_RELA => {
947                rela_addr = Some(
948                    dyn_entry
949                        .d_val
950                        .checked_add(load_bias)
951                        .ok_or("DT_RELA relocated address overflow")?,
952                )
953            }
954            DT_RELASZ => rela_size = dyn_entry.d_val as usize,
955            DT_RELAENT => rela_ent = dyn_entry.d_val as usize,
956            DT_RELACOUNT => rela_count_hint = Some(dyn_entry.d_val as usize),
957            DT_JMPREL => {
958                jmprel_addr = Some(
959                    dyn_entry
960                        .d_val
961                        .checked_add(load_bias)
962                        .ok_or("DT_JMPREL relocated address overflow")?,
963                )
964            }
965            DT_PLTRELSZ => jmprel_size = dyn_entry.d_val as usize,
966            DT_PLTREL => pltrel_kind = Some(dyn_entry.d_val),
967            DT_SYMTAB => {
968                symtab_addr = Some(
969                    dyn_entry
970                        .d_val
971                        .checked_add(load_bias)
972                        .ok_or("DT_SYMTAB relocated address overflow")?,
973                )
974            }
975            DT_SYMENT => sym_ent = dyn_entry.d_val as usize,
976            DT_STRTAB => {
977                strtab_addr = Some(
978                    dyn_entry
979                        .d_val
980                        .checked_add(load_bias)
981                        .ok_or("DT_STRTAB relocated address overflow")?,
982                );
983            }
984            DT_RELR => {
985                relr_addr = Some(
986                    dyn_entry
987                        .d_val
988                        .checked_add(load_bias)
989                        .ok_or("DT_RELR relocated address overflow")?,
990                )
991            }
992            DT_RELRSZ => relr_size = dyn_entry.d_val as usize,
993            DT_RELRENT => relr_ent = dyn_entry.d_val as usize,
994            _ => {}
995        }
996    }
997
998    let mut relr_applied = 0usize;
999    if let Some(relr_base) = relr_addr {
1000        relr_applied = apply_relr_relocations(user_as, load_bias, relr_base, relr_size, relr_ent)?;
1001    } else if relr_size != 0 || relr_ent != 0 {
1002        return Err("DT_RELR metadata present without DT_RELR base");
1003    }
1004    if rela_ent != core::mem::size_of::<Elf64Rela>() {
1005        return Err("Unsupported DT_RELAENT size");
1006    }
1007    if sym_ent != core::mem::size_of::<Elf64Sym>() {
1008        return Err("Unsupported DT_SYMENT size");
1009    }
1010    if pltrel_kind.is_some() && pltrel_kind != Some(DT_RELA as u64) {
1011        return Err("Only DT_PLTREL=DT_RELA is supported");
1012    }
1013
1014    // Keep the validated DT_STRTAB address available for future symbol lookup.
1015    let _ = strtab_addr;
1016    elf_trace!(
1017        "[elf] dynamic: symtab={:?} strtab={:?}",
1018        symtab_addr,
1019        strtab_addr
1020    );
1021
1022    let read_sym_entry = |sym_idx: u32| -> Result<Elf64Sym, &'static str> {
1023        let symtab = symtab_addr.ok_or("Missing DT_SYMTAB for symbol relocations")?;
1024        let sym_addr = symtab
1025            .checked_add((sym_idx as u64) * (sym_ent as u64))
1026            .ok_or("Symbol table address overflow")?;
1027        let mut raw = [0u8; core::mem::size_of::<Elf64Sym>()];
1028        read_user_mapped_bytes(user_as, sym_addr, &mut raw)?;
1029        Ok(unsafe { core::ptr::read_unaligned(raw.as_ptr() as *const Elf64Sym) })
1030    };
1031
1032    let resolve_sym =
1033        |sym_idx: u32, with_bias: bool, check_def: bool| -> Result<u64, &'static str> {
1034            if sym_idx == 0 {
1035                return Ok(0);
1036            }
1037            let sym = read_sym_entry(sym_idx)?;
1038            if check_def && sym.st_shndx == 0 {
1039                return Err("Undefined symbol relocation not supported");
1040            }
1041            if with_bias {
1042                sym.st_value
1043                    .checked_add(load_bias)
1044                    .ok_or("Symbol value relocation overflow")
1045            } else {
1046                Ok(sym.st_value)
1047            }
1048        };
1049
1050    let resolve_size = |sym_idx: u32| -> Result<u64, &'static str> {
1051        if sym_idx == 0 {
1052            return Ok(0);
1053        }
1054        let sym = read_sym_entry(sym_idx)?;
1055        Ok(sym.st_size)
1056    };
1057
1058    // Variant II TLS: tp = tls_base + aligned_memsz.  We need the aligned
1059    // memsz for TPOFF64/DTPOFF64 calculations.
1060    let tls_aligned_memsz: i128 = phdrs
1061        .iter()
1062        .find(|ph| ph.p_type == PT_TLS)
1063        .map(|tls| {
1064            let memsz = tls.p_memsz;
1065            let align = tls.p_align.max(1);
1066            let aligned = (memsz + align - 1) & !(align - 1);
1067            aligned as i128
1068        })
1069        .unwrap_or(0);
1070
1071    let apply_rela_table = |table_base: u64,
1072                            table_size: usize,
1073                            count_hint: Option<usize>|
1074     -> Result<usize, &'static str> {
1075        if table_size == 0 {
1076            return Ok(0);
1077        }
1078        // Use the table size as the authoritative entry count.  DT_RELACOUNT is
1079        // a *hint* from the linker that may undercount; honouring it with min()
1080        // silently drops valid relocations.  We only validate the hint as a
1081        // sanity bound (if provided).
1082        let count = table_size / rela_ent;
1083        if let Some(hint) = count_hint {
1084            if hint > count {
1085                return Err("DT_RELACOUNT exceeds actual RELA table size");
1086            }
1087        }
1088        let mut applied = 0usize;
1089        for i in 0..count {
1090            let rela_addr_i = table_base
1091                .checked_add((i * rela_ent) as u64)
1092                .ok_or("Rela table overflow")?;
1093            let mut raw = [0u8; core::mem::size_of::<Elf64Rela>()];
1094            read_user_mapped_bytes(user_as, rela_addr_i, &mut raw)?;
1095            // SAFETY: raw has exact size of Elf64Rela.
1096            let rela = unsafe { core::ptr::read_unaligned(raw.as_ptr() as *const Elf64Rela) };
1097
1098            let r_type = (rela.r_info & 0xffff_ffff) as u32;
1099            let r_sym = (rela.r_info >> 32) as u32;
1100            let target = rela
1101                .r_offset
1102                .checked_add(load_bias)
1103                .ok_or("Relocation target overflow")?;
1104            if target >= USER_ADDR_MAX {
1105                return Err("Relocation target outside user space");
1106            }
1107
1108            let value = match r_type {
1109                R_X86_64_RELATIVE => {
1110                    if r_sym != 0 {
1111                        return Err("R_X86_64_RELATIVE with non-zero symbol");
1112                    }
1113                    (load_bias as i128)
1114                        .checked_add(rela.r_addend as i128)
1115                        .ok_or("Relocation value overflow")?
1116                }
1117                R_X86_64_GLOB_DAT | R_X86_64_JUMP_SLOT | R_X86_64_64 => {
1118                    let sym_val = resolve_sym(r_sym, true, true)? as i128;
1119                    sym_val
1120                        .checked_add(rela.r_addend as i128)
1121                        .ok_or("Relocation value overflow")?
1122                }
1123                R_X86_64_COPY => {
1124                    let sym_val = resolve_sym(r_sym, true, true)?;
1125                    if sym_val == 0 {
1126                        continue;
1127                    }
1128                    let sym_sz = resolve_size(r_sym)?;
1129                    if sym_sz == 0 {
1130                        log::warn!("[elf] R_X86_64_COPY with zero st_size for symbol {}", r_sym);
1131                    }
1132                    if sym_sz > 0 && sym_val < USER_ADDR_MAX {
1133                        let mut tmp = [0u8; 256];
1134                        let mut off = 0u64;
1135                        while off < sym_sz {
1136                            let chunk = core::cmp::min(256, (sym_sz - off) as usize);
1137                            let src = sym_val.checked_add(off).ok_or("COPY source overflow")?;
1138                            let dst = target.checked_add(off).ok_or("COPY target overflow")?;
1139                            read_user_mapped_bytes(user_as, src, &mut tmp[..chunk])?;
1140                            write_user_mapped_bytes(user_as, dst, &tmp[..chunk])?;
1141                            off += chunk as u64;
1142                        }
1143                    }
1144                    applied += 1;
1145                    continue;
1146                }
1147                R_X86_64_TPOFF64 => {
1148                    let sym_val = if r_sym != 0 {
1149                        resolve_sym(r_sym, false, false)? as i128
1150                    } else {
1151                        0i128
1152                    };
1153                    // Variant II: tp = tls_base + aligned_memsz, so offset from tp is
1154                    // (sym.st_value - aligned_memsz + r_addend).  Use i128 to avoid
1155                    // underflow when sym_val < aligned_memsz.
1156                    sym_val
1157                        .checked_sub(tls_aligned_memsz)
1158                        .and_then(|v| v.checked_add(rela.r_addend as i128))
1159                        .ok_or("TPOFF64 value overflow")?
1160                }
1161                R_X86_64_DTPMOD64 => {
1162                    // For single-binary loading (no dynamic linker), the module ID is always 1.
1163                    1i128
1164                }
1165                R_X86_64_DTPOFF64 => {
1166                    // DTV-relative offset: same as TPOFF64 for single-binary loading.
1167                    let sym_val = if r_sym != 0 {
1168                        resolve_sym(r_sym, false, false)? as i128
1169                    } else {
1170                        0i128
1171                    };
1172                    sym_val
1173                        .checked_sub(tls_aligned_memsz)
1174                        .and_then(|v| v.checked_add(rela.r_addend as i128))
1175                        .ok_or("DTPOFF64 value overflow")?
1176                }
1177                R_X86_64_IRELATIVE => {
1178                    // IRELATIVE: the target is a resolver function that must be
1179                    // *called* to obtain the final value.  All RELATIVE
1180                    // relocations for this binary have already been applied, so
1181                    // the resolver's own addresses are correct.
1182                    let resolver_vaddr = (load_bias as i128)
1183                        .checked_add(rela.r_addend as i128)
1184                        .ok_or("IRELATIVE resolver address overflow")?;
1185                    if resolver_vaddr < 0 || resolver_vaddr as u64 >= USER_ADDR_MAX {
1186                        return Err("IRELATIVE resolver outside user space");
1187                    }
1188                    let resolved = call_ifunc_resolver(user_as, resolver_vaddr as u64)?;
1189                    resolved as i128
1190                }
1191                _ => {
1192                    log::warn!("[elf] Unsupported relocation type {}", r_type);
1193                    continue;
1194                }
1195            };
1196            if value < 0 || value > u64::MAX as i128 {
1197                return Err("Relocation value out of range");
1198            }
1199            let val_u64 = value as u64;
1200            #[cfg(debug_assertions)]
1201            if applied < 5 {
1202                let r_addend_copy = rela.r_addend;
1203                let mut before = [0u8; 8];
1204                let _ = read_user_mapped_bytes(user_as, target, &mut before);
1205                let before_val = u64::from_le_bytes(before);
1206                log::trace!(
1207                    "[reloc] [{i}] r_type={} target={:#x} r_addend={:#x} value={:#x} before={:#x}",
1208                    r_type,
1209                    target,
1210                    r_addend_copy,
1211                    val_u64,
1212                    before_val
1213                );
1214            }
1215            write_user_mapped_bytes(user_as, target, &val_u64.to_le_bytes())?;
1216            #[cfg(debug_assertions)]
1217            if applied < 5 {
1218                let mut after = [0u8; 8];
1219                let _ = read_user_mapped_bytes(user_as, target, &mut after);
1220                let after_val = u64::from_le_bytes(after);
1221                log::trace!(
1222                    "[reloc] [{i}] after_write={:#x} (expected={:#x})",
1223                    after_val,
1224                    val_u64
1225                );
1226            }
1227            #[cfg(debug_assertions)]
1228            if val_u64 >= 0xffff_8000_0000_0000 {
1229                let r_addend_copy = rela.r_addend;
1230                log::trace!(
1231                    "[reloc-KERNEL-ADDR] [{i}] r_type={} target={:#x} r_addend={:#x} val={:#x} bias={:#x}",
1232                    r_type, target, r_addend_copy, val_u64, load_bias
1233                );
1234            }
1235            applied += 1;
1236        }
1237        Ok(applied)
1238    };
1239
1240    let mut total_applied = 0usize;
1241    #[cfg(debug_assertions)]
1242    log::trace!(
1243        "[reloc] apply_dynamic_relocations: bias={:#x} rela_addr={:?} rela_size={} rela_count={:?}",
1244        load_bias,
1245        rela_addr,
1246        rela_size,
1247        rela_count_hint
1248    );
1249    if let Some(rela_base) = rela_addr {
1250        total_applied += apply_rela_table(rela_base, rela_size, rela_count_hint)?;
1251    }
1252    if let Some(jmprel_base) = jmprel_addr {
1253        total_applied += apply_rela_table(jmprel_base, jmprel_size, None)?;
1254    }
1255
1256    // The relocation count is diagnostic-only, but remains meaningful in release builds.
1257    let _ = total_applied;
1258    #[cfg(debug_assertions)]
1259    if total_applied > 0 {
1260        log::trace!(
1261            "[reloc] applied {} RELA relocations (bias={:#x})",
1262            total_applied,
1263            load_bias
1264        );
1265    }
1266    if relr_applied > 0 {
1267        log::debug!("[elf] Applied {} RELR relocations", relr_applied);
1268    }
1269    Ok(())
1270}
1271
1272// ---------------------------------------------------------------------------
1273// Loading
1274// ---------------------------------------------------------------------------
1275
1276/// Convert ELF p_flags to VmaFlags.
1277fn elf_flags_to_vma(p_flags: u32) -> VmaFlags {
1278    VmaFlags {
1279        readable: p_flags & PF_R != 0,
1280        writable: p_flags & PF_W != 0,
1281        executable: p_flags & PF_X != 0,
1282        user_accessible: true,
1283    }
1284}
1285
1286/// Load a single PT_LOAD segment into the given address space.
1287///
1288/// Allocates physical frames, maps them with appropriate permissions, and
1289/// copies file data into the mapping. BSS (memsz > filesz) is already
1290/// zero-filled because `map_region` zeroes newly allocated frames.
1291fn load_segment(
1292    user_as: &AddressSpace,
1293    elf_data: &[u8],
1294    phdr: &Elf64Phdr,
1295    load_bias: u64,
1296) -> Result<(), &'static str> {
1297    let vaddr = phdr
1298        .p_vaddr
1299        .checked_add(load_bias)
1300        .ok_or("PT_LOAD relocated vaddr overflow")?;
1301    let memsz = phdr.p_memsz;
1302    let filesz = phdr.p_filesz;
1303    let offset = phdr.p_offset;
1304
1305    // Validate addresses are in user space
1306    if vaddr >= USER_ADDR_MAX {
1307        return Err("PT_LOAD vaddr outside user space");
1308    }
1309    let end = vaddr
1310        .checked_add(memsz)
1311        .ok_or("PT_LOAD vaddr+memsz overflows")?;
1312    if end > USER_ADDR_MAX {
1313        return Err("PT_LOAD segment extends past user space");
1314    }
1315
1316    // Validate file region
1317    let file_end = (offset as usize)
1318        .checked_add(filesz as usize)
1319        .ok_or("PT_LOAD offset+filesz overflows")?;
1320    if file_end > elf_data.len() {
1321        return Err("PT_LOAD file data extends past ELF");
1322    }
1323
1324    // Calculate page-aligned mapping
1325    let page_start = vaddr & !0xFFF;
1326    let page_end = (end + 0xFFF) & !0xFFF;
1327    let page_count = ((page_end - page_start) / 4096) as usize;
1328
1329    // Map writable during copy, then restore final ELF flags.
1330    let actual_flags = elf_flags_to_vma(phdr.p_flags);
1331    let load_flags = VmaFlags {
1332        readable: true,
1333        writable: true, // Need write access to copy data in
1334        executable: actual_flags.executable,
1335        user_accessible: true,
1336    };
1337
1338    let vma_type = if actual_flags.executable {
1339        VmaType::Code
1340    } else {
1341        VmaType::Anonymous
1342    };
1343    log::debug!(
1344        "[elf] map PT_LOAD: start={:#x} pages={} filesz={:#x}",
1345        page_start,
1346        page_count,
1347        filesz
1348    );
1349    user_as.map_region(
1350        page_start,
1351        page_count,
1352        load_flags,
1353        vma_type,
1354        VmaPageSize::Small,
1355    )?;
1356
1357    // Copy file data into the mapped pages.
1358    // Batch-translate all pages at once to avoid page-table walks per-chunk.
1359    if filesz > 0 {
1360        let src = &elf_data[offset as usize..file_end];
1361        let mut copied = 0usize;
1362
1363        // Collect physical addresses for all pages in the range.
1364        let n_vaddrs = ((page_end - page_start) / 4096) as usize;
1365        let mut phys_pages = alloc::vec::Vec::with_capacity(n_vaddrs);
1366        for i in 0..n_vaddrs {
1367            let vaddr = page_start + (i as u64) * 4096;
1368            let phys = user_as
1369                .translate(VirtAddr::new(vaddr))
1370                .ok_or("Failed to translate user page after mapping")?;
1371            phys_pages.push(phys);
1372        }
1373
1374        while copied < src.len() {
1375            let dst_vaddr = vaddr + copied as u64;
1376            let page_idx = ((dst_vaddr - page_start) / 4096) as usize;
1377            let page_offset = (dst_vaddr & 0xFFF) as usize;
1378            let chunk = core::cmp::min(src.len() - copied, 4096 - page_offset);
1379
1380            let phys = phys_pages[page_idx];
1381            let hhdm_ptr = crate::memory::phys_to_virt(phys.as_u64()) as *mut u8;
1382            // SAFETY: hhdm_ptr points to a freshly mapped, zeroed frame via HHDM.
1383            unsafe {
1384                core::ptr::copy_nonoverlapping(
1385                    src.as_ptr().add(copied),
1386                    hhdm_ptr.add(page_offset),
1387                    chunk,
1388                );
1389            }
1390            copied += chunk;
1391        }
1392    }
1393
1394    // Tighten PTE permissions after copy.
1395    apply_segment_permissions(user_as, page_start, page_count, actual_flags)?;
1396
1397    log::debug!(
1398        "  PT_LOAD: {:#x}..{:#x} ({} pages, file {:#x}+{:#x}, flags {:?})",
1399        page_start,
1400        page_end,
1401        page_count,
1402        offset,
1403        filesz,
1404        actual_flags,
1405    );
1406
1407    Ok(())
1408}
1409
1410// ---------------------------------------------------------------------------
1411// Task creation with IRETQ trampoline
1412// ---------------------------------------------------------------------------
1413
1414/// Parameters for the Ring 3 trampoline, stored in a static so the
1415/// Trampoline that switches to user address space and does IRETQ to Ring 3.
1416///
1417/// Parameters (entry point, stack top, arg0, address space) are read from the
1418/// *current task* so that each ELF task carries its own copy.  This makes the
1419/// trampoline safe under SMP: two tasks can run their trampolines concurrently
1420/// on different CPUs without any shared mutable state.
1421extern "C" fn elf_ring3_trampoline() -> ! {
1422    use crate::arch::gdt;
1423    use core::sync::atomic::Ordering;
1424
1425    elf_trace!("[trace][elf] ring3_trampoline before current_task");
1426    let Some(task) = crate::process::scheduler::current_task_clone_spin_debug("ring3_trampoline")
1427    else {
1428        log::error!("[elf] ring3_trampoline: no current task, aborting");
1429        loop {
1430            crate::x86_crate_shim::instructions::hlt();
1431        }
1432    };
1433    elf_trace!(
1434        "[trace][elf] ring3_trampoline enter tid={} name={}",
1435        task.id.as_u64(),
1436        task.name
1437    );
1438    task.set_resume_kind(crate::process::task::ResumeKind::IretFrame);
1439
1440    let user_rip = task.trampoline_entry.load(Ordering::Acquire);
1441    let user_rsp = task.trampoline_stack_top.load(Ordering::Acquire);
1442    let user_arg0 = task.trampoline_arg0.load(Ordering::Acquire);
1443    elf_trace!(
1444        "[trace][elf] ring3_trampoline args tid={} rip={:#x} rsp={:#x} arg0={:#x}",
1445        task.id.as_u64(),
1446        user_rip,
1447        user_rsp,
1448        user_arg0
1449    );
1450
1451    // Probe: read GOT entries via HHDM before switching to user AS.
1452    // This is the last kernel-owned moment before user execution begins.
1453    // If values here are wrong, the bug is in load/relocation, not in
1454    // something that happens after this point.
1455    #[cfg(debug_assertions)]
1456    {
1457        // SAFETY: Kernel still holds the boot/kernel CR3. HHDM is valid.
1458        unsafe {
1459            let as_ref = task.process.address_space_arc();
1460            let task_name: &str = &task.name;
1461            for test_off in [0x12920u64, 0x12928u64, 0x12930u64] {
1462                let vaddr = 0x100000000u64.wrapping_add(test_off);
1463                if let Some(phys) = as_ref.translate(VirtAddr::new(vaddr)) {
1464                    let ptr = crate::memory::phys_to_virt(phys.as_u64()) as *const u64;
1465                    let val = core::ptr::read_unaligned(ptr);
1466                    elf_trace!(
1467                        "[trampoline-got] tid={} name={} GOT[{:#x}]=phys={:#x} val={:#x}",
1468                        task.id.as_u64(),
1469                        task_name,
1470                        vaddr,
1471                        phys.as_u64(),
1472                        val
1473                    );
1474                } else {
1475                    elf_trace!(
1476                        "[trampoline-got] tid={} name={} GOT[{:#x}]=<not mapped>",
1477                        task.id.as_u64(),
1478                        task_name,
1479                        vaddr
1480                    );
1481                }
1482            }
1483        }
1484    }
1485
1486    // Switch to the user address space stored in the task.
1487    // SAFETY: The address space was set up during task creation and is valid.
1488    unsafe {
1489        let as_ref = task.process.address_space_arc();
1490        as_ref.switch_to();
1491    }
1492    elf_trace!(
1493        "[trace][elf] ring3_trampoline switch_to done tid={}",
1494        task.id.as_u64()
1495    );
1496
1497    let user_cs = gdt::user_code_selector().0 as u64;
1498    let user_ss = gdt::user_data_selector().0 as u64;
1499    let user_rflags: u64 = USER_RFLAGS;
1500    elf_trace!(
1501        "[trace][elf] ring3_trampoline iret tid={} cs={:#x} ss={:#x} rflags={:#x}",
1502        task.id.as_u64(),
1503        user_cs,
1504        user_ss,
1505        user_rflags
1506    );
1507
1508    // ----- Pre-iret LAPIC timer diagnostic -----
1509    // Verify that the APIC timer is actually running on this CPU before we
1510    // enter Ring 3 (if it is not, no timer tick = no heartbeat = silent hang).
1511    unsafe {
1512        let lvt = crate::arch::apic::read_reg(crate::arch::apic::REG_LVT_TIMER);
1513        let init_cnt = crate::arch::apic::read_reg(crate::arch::apic::REG_TIMER_INIT);
1514        let _cur_cnt = crate::arch::apic::read_reg(crate::arch::apic::REG_TIMER_CURRENT);
1515        let _rflags_now: u64;
1516        core::arch::asm!("pushfq; pop {}", out(reg) _rflags_now, options(nostack));
1517        elf_trace!(
1518            "[trace][elf] pre-iret LAPIC: LVT={:#x} init={} cur={} IF={}",
1519            lvt,
1520            init_cnt,
1521            _cur_cnt,
1522            (_rflags_now >> 9) & 1
1523        );
1524        if lvt & (1 << 16) != 0 {
1525            elf_trace!(
1526                "[trace][elf] WARNING: LAPIC timer is MASKED (bit 16 set) : no ticks will fire!"
1527            );
1528        }
1529        if init_cnt == 0 {
1530            elf_trace!("[trace][elf] WARNING: LAPIC timer init_count=0 : timer not started!");
1531        }
1532    }
1533
1534    crate::arch::ring3_diag::validate_ring3_state(
1535        user_rip,
1536        user_rsp,
1537        user_cs as u16,
1538        user_ss as u16,
1539    );
1540
1541    elf_trace!(
1542        "[elf] PRE-IRETQ tid={} rip={:#x} rsp={:#x} rflags={:#x}",
1543        task.id.as_u64(),
1544        user_rip,
1545        user_rsp,
1546        user_rflags
1547    );
1548
1549    // E9 probe: validate_ring3_state passed, entering asm block.
1550    // If '0' is visible but not '1', the compiler inserted code between
1551    // the two that crashed (unlikely, but this rules it out).
1552    elf_trace!(
1553        "E9[0] pre-asm rip={:#x} rsp={:#x} cs={:#x} ss={:#x}",
1554        user_rip,
1555        user_rsp,
1556        user_cs,
1557        user_ss,
1558    );
1559
1560    // SAFETY: Valid user mappings have been set up. IRETQ switches to Ring 3.
1561    //
1562    // Interrupts must be masked in the final kernel instructions before
1563    // `swapgs ; iretq`. Otherwise a timer IRQ can land after `swapgs` but
1564    // before `iretq`, with `CS=0x8` and `GS=user`, and the first `gs:[..]`
1565    // access in the handler faults in the swapgs->iretq window.
1566
1567    // Pre-fault the user entry page while GS still points at the kernel
1568    // per-CPU block.  If the very first user instruction faults after
1569    // `swapgs ; iretq`, the fault is delivered with GS already switched to
1570    // userspace, which the entry stubs do not expect.
1571    //
1572    // SMAP: with CR4.SMAP=1 a plain supervisor load from a *present* user
1573    // page raises #PF (P=1, US=0 => "kernel protection violation"), which
1574    // the fault handler correctly treats as fatal.  Access the page through
1575    // the STAC/CLAC window so the probe works on every CPU that exposes
1576    // SMAP (e.g. VMware Workstation guests), not only on CPU models that
1577    // hide the feature (plain `-cpu qemu64`).
1578    //
1579    // Interrupts are masked for the rest of this function; `iretq` restores
1580    // the user RFLAGS (IF=1) from the frame built below.
1581    let _flags = crate::arch::save_flags_and_cli();
1582    crate::arch::stac();
1583    // SAFETY: `user_rip` is inside the ELF's validated user mapping, and
1584    // SMAP is temporarily disabled by `stac()` on CPUs that need it.
1585    let _first_user_byte = unsafe { core::ptr::read_volatile(user_rip as *const u8) };
1586    crate::arch::clac();
1587
1588    // Each `out 0xe9, al` writes an ASCII character to QEMU's E9 port.
1589    // Debug builds include probes 1-4 for diagnosing IRETQ failures;
1590    // release builds omit them to avoid port I/O overhead.
1591    #[cfg(debug_assertions)]
1592    unsafe {
1593        core::arch::asm!(
1594            // Close the IRQ window before touching GS. `iretq` restores IF=1
1595            // from the user RFLAGS frame, so user mode still starts with
1596            // interrupts enabled.
1597            "cli",
1598
1599            //  Probe 1: entering the asm block
1600            "push rax",
1601            "mov al, 0x31",     // '1'
1602            "out 0xe9, al",
1603            "pop rax",
1604
1605            //  Build the iretq frame
1606            // Order required by IRETQ (popped in reverse order):
1607            //   [RSP+32] SS
1608            //   [RSP+24] user RSP
1609            //   [RSP+16] RFLAGS
1610            //   [RSP+8]  CS
1611            //   [RSP+0]  RIP  <--- RSP here after the 5 pushes
1612            "push {ss}",
1613            "push {rsp_val}",
1614            "push {rflags}",
1615            "push {cs}",
1616            "push {rip}",
1617
1618            //  Probe 2: frame iretq complete
1619            "push rax",
1620            "mov al, 0x32",     // '2'
1621            "out 0xe9, al",
1622            "pop rax",
1623
1624            //  Load arg0 into RDI
1625            "mov rdi, {arg0}",
1626
1627            //  Probe 3: RDI loaded, just before SWAPGS
1628            "push rax",
1629            "mov al, 0x33",     // '3'
1630            "out 0xe9, al",
1631            "pop rax",
1632
1633            //  SWAPGS: GS.base kernel <-> GS.base user
1634            "swapgs",
1635
1636            //  Probe 4: SWAPGS succeeded, IRETQ imminent
1637            "push rax",
1638            "mov al, 0x34",     // '4'
1639            "out 0xe9, al",
1640            "pop rax",
1641
1642            //  IRETQ: point of no return
1643            "iretq",
1644
1645            ss      = in(reg) user_ss,
1646            rsp_val = in(reg) user_rsp,
1647            rflags  = in(reg) user_rflags,
1648            cs      = in(reg) user_cs,
1649            rip     = in(reg) user_rip,
1650            arg0    = in(reg) user_arg0,
1651            options(noreturn),
1652        );
1653    }
1654
1655    #[cfg(not(debug_assertions))]
1656    unsafe {
1657        core::arch::asm!(
1658            "cli",
1659
1660            //  Build the iretq frame
1661            "push {ss}",
1662            "push {rsp_val}",
1663            "push {rflags}",
1664            "push {cs}",
1665            "push {rip}",
1666
1667            //  Load arg0 into RDI
1668            "mov rdi, {arg0}",
1669
1670            //  SWAPGS: GS.base kernel <-> GS.base user
1671            "swapgs",
1672
1673            //  IRETQ: point of no return
1674            "iretq",
1675
1676            ss      = in(reg) user_ss,
1677            rsp_val = in(reg) user_rsp,
1678            rflags  = in(reg) user_rflags,
1679            cs      = in(reg) user_cs,
1680            rip     = in(reg) user_rip,
1681            arg0    = in(reg) user_arg0,
1682            options(noreturn),
1683        );
1684    }
1685}
1686
1687// ---------------------------------------------------------------------------
1688// Public API
1689// ---------------------------------------------------------------------------
1690/// Load an ELF64 binary and schedule it as a Ring 3 user task.
1691///
1692/// # Arguments
1693/// * `elf_data` : raw ELF file bytes (must remain valid until load completes).
1694/// * `name` : name for the task (debugging purposes).
1695///
1696/// # Returns
1697/// `Ok(())` on success, `Err` with a static error message on failure.
1698pub fn load_and_run_elf(elf_data: &[u8], name: &str) -> Result<TaskId, &'static str> {
1699    load_and_run_elf_with_caps(elf_data, name, &[])
1700}
1701
1702/// Load an ELF64 binary with command-line arguments and schedule it as a Ring 3 task.
1703///
1704/// `extra_args` maps to `argv[1..]`; `argv[0]` is always `name`.
1705pub fn load_and_run_elf_with_args(
1706    elf_data: &[u8],
1707    name: &str,
1708    extra_args: &[&str],
1709) -> Result<TaskId, &'static str> {
1710    let task = load_elf_task_inner(elf_data, name, extra_args, &[], USER_STACK_PAGES, None)?;
1711    let task_id = task.id;
1712    crate::process::add_task(task);
1713    Ok(task_id)
1714}
1715
1716/// Load an ELF64 binary with an explicit per-process user stack size.
1717///
1718/// `stack_pages` is expressed in 4 KiB pages and clamped to
1719/// [`USER_STACK_MIN_PAGES`]..=[`USER_STACK_MAX_PAGES`] (issue #64).
1720pub fn load_and_run_elf_with_stack(
1721    elf_data: &[u8],
1722    name: &str,
1723    extra_args: &[&str],
1724    seed_caps: &[Capability],
1725    stack_pages: usize,
1726) -> Result<TaskId, &'static str> {
1727    let task = load_elf_task_inner(elf_data, name, extra_args, seed_caps, stack_pages, None)?;
1728    let task_id = task.id;
1729    crate::process::add_task(task);
1730    Ok(task_id)
1731}
1732
1733/// Thin public wrapper that keeps the existing API stable.
1734pub fn load_elf_task_with_caps(
1735    elf_data: &[u8],
1736    name: &str,
1737    seed_caps: &[Capability],
1738) -> Result<Arc<Task>, &'static str> {
1739    load_elf_task_inner(elf_data, name, &[], seed_caps, USER_STACK_PAGES, None)
1740}
1741
1742/// Bind the silo quota before the first ELF/stack mapping.
1743pub(crate) fn load_elf_task_in_silo(
1744    elf_data: &[u8],
1745    name: &str,
1746    seed_caps: &[Capability],
1747    account: Arc<crate::silo::SiloMemoryAccount>,
1748) -> Result<Arc<Task>, &'static str> {
1749    load_elf_task_inner(
1750        elf_data,
1751        name,
1752        &[],
1753        seed_caps,
1754        USER_STACK_PAGES,
1755        Some(account),
1756    )
1757}
1758
1759/// Performs the load and run elf with caps operation.
1760pub fn load_and_run_elf_with_caps(
1761    elf_data: &[u8],
1762    name: &str,
1763    seed_caps: &[Capability],
1764) -> Result<TaskId, &'static str> {
1765    log::trace!(
1766        "[trace][elf] load_and_run_elf enter name={} size={}",
1767        name,
1768        elf_data.len()
1769    );
1770    let task = load_elf_task_inner(elf_data, name, &[], seed_caps, USER_STACK_PAGES, None)?;
1771    let task_id = task.id;
1772    let runtime_entry = task
1773        .trampoline_entry
1774        .load(core::sync::atomic::Ordering::Acquire);
1775    let boot_stack_top = task
1776        .trampoline_stack_top
1777        .load(core::sync::atomic::Ordering::Acquire);
1778    log::trace!(
1779        "[trace][elf] load_and_run_elf add_task begin tid={} entry={:#x}",
1780        task_id.as_u64(),
1781        runtime_entry
1782    );
1783    crate::process::add_task(task);
1784    log::trace!(
1785        "[trace][elf] load_and_run_elf add_task done tid={}",
1786        task_id.as_u64()
1787    );
1788
1789    log::info!(
1790        "[elf] Task '{}' created: entry={:#x}, stack_top={:#x}",
1791        name,
1792        runtime_entry,
1793        boot_stack_top,
1794    );
1795
1796    Ok(task_id)
1797}
1798
1799const AT_PHDR: u64 = 3;
1800const AT_PHENT: u64 = 4;
1801const AT_PHNUM: u64 = 5;
1802const AT_PAGESZ: u64 = 6;
1803const AT_BASE: u64 = 7;
1804const AT_ENTRY: u64 = 9;
1805const AT_RANDOM: u64 = 25;
1806
1807fn generate_aux_random_seed() -> [u8; 16] {
1808    let mut seed = [0u8; 16];
1809    crate::e9_mark!(b'1');
1810    crate::entropy::fill_random(&mut seed);
1811    crate::e9_mark!(b'2');
1812    seed
1813}
1814
1815/// Performs the push auxv operation.
1816fn push_auxv(user_as: &AddressSpace, sp: &mut u64, tag: u64, val: u64) -> Result<(), &'static str> {
1817    *sp -= 8;
1818    write_user_u64(user_as, *sp, val)?;
1819    *sp -= 8;
1820    write_user_u64(user_as, *sp, tag)?;
1821    Ok(())
1822}
1823
1824/// Performs the setup boot user stack operation.
1825/// Sets up the initial user-space stack for a freshly loaded ELF task.
1826///
1827/// Stack layout (low addr at bottom = first word read by `_start`):
1828/// ```
1829/// [sp+0]             argc
1830/// [sp+8]             argv[0] ptr  (program name)
1831/// [sp+8*(2..=argc)]  argv[1..] ptrs  (extra_args)
1832/// [sp+8*(argc+1)]    NULL  (argv terminator)
1833/// [sp+8*(argc+2)]    NULL  (envp terminator)
1834/// ...                auxv pairs
1835/// ```
1836fn setup_boot_user_stack(
1837    user_as: &AddressSpace,
1838    name: &str,
1839    extra_args: &[&str],
1840    phdr_vaddr: u64,
1841    phent: u16,
1842    phnum: u16,
1843    program_entry: u64,
1844    interp_base: Option<u64>,
1845    stack_base: u64,
1846    stack_top: u64,
1847) -> Result<u64, &'static str> {
1848    let mut sp = stack_top;
1849
1850    // Write argv[0] = program name (null-terminated)
1851    let name_nul_len = (name.len() + 1) as u64;
1852    sp -= name_nul_len;
1853    if sp < stack_base {
1854        return Err("User stack overflow during boot stack setup");
1855    }
1856    let argv0_ptr = sp;
1857    write_user_mapped_bytes(user_as, sp, name.as_bytes())?;
1858    write_user_mapped_bytes(user_as, sp + name.len() as u64, &[0])?;
1859
1860    // Write extra arg strings and record their user-space pointers
1861    let mut extra_ptrs: alloc::vec::Vec<u64> = alloc::vec::Vec::new();
1862    // Fallible pre-allocation: argv can be large; fail the load instead of
1863    // aborting on OOM (issue #67). Exact capacity => pushes never realloc.
1864    extra_ptrs
1865        .try_reserve_exact(extra_args.len())
1866        .map_err(|_| "User stack overflow during boot stack setup")?;
1867    for &arg in extra_args.iter() {
1868        let arg_nul_len = (arg.len() + 1) as u64;
1869        sp -= arg_nul_len;
1870        if sp < stack_base {
1871            return Err("User stack overflow during boot stack setup");
1872        }
1873        extra_ptrs.push(sp);
1874        write_user_mapped_bytes(user_as, sp, arg.as_bytes())?;
1875        write_user_mapped_bytes(user_as, sp + arg.len() as u64, &[0])?;
1876    }
1877
1878    sp &= !0xF;
1879    sp -= 16;
1880    if sp < stack_base {
1881        return Err("User stack overflow during boot stack setup");
1882    }
1883    let random_ptr = sp;
1884    let random_seed = generate_aux_random_seed();
1885    write_user_mapped_bytes(user_as, sp, &random_seed)?;
1886    let auxv_pairs = if interp_base.is_some() { 8u64 } else { 7u64 };
1887    // argc(1) + argv[0..=N](1+N) + argv_NULL(1) + envp_NULL(1) + auxv(pairs*2)
1888    let stack_words = 4u64 + extra_args.len() as u64 + auxv_pairs * 2;
1889    let align_pad = (0u64.wrapping_sub(stack_words * 8)) & 0xF;
1890    sp -= align_pad;
1891
1892    // Auxv (written high-to-low since push_auxv decrements sp)
1893    push_auxv(user_as, &mut sp, 0, 0)?; // AT_NULL
1894    push_auxv(user_as, &mut sp, AT_RANDOM, random_ptr)?;
1895    push_auxv(user_as, &mut sp, AT_ENTRY, program_entry)?;
1896    if let Some(base) = interp_base {
1897        push_auxv(user_as, &mut sp, AT_BASE, base)?;
1898    }
1899    push_auxv(user_as, &mut sp, AT_PAGESZ, 4096)?;
1900    push_auxv(user_as, &mut sp, AT_PHNUM, phnum as u64)?;
1901    push_auxv(user_as, &mut sp, AT_PHENT, phent as u64)?;
1902    // AT_PHDR is optional: 0 means "not mapped" (static binaries with the
1903    // program header array outside any PT_LOAD).
1904    if phdr_vaddr != 0 {
1905        push_auxv(user_as, &mut sp, AT_PHDR, phdr_vaddr)?;
1906    }
1907
1908    // envp NULL terminator
1909    sp -= 8;
1910    write_user_u64(user_as, sp, 0)?;
1911
1912    // argv NULL terminator
1913    sp -= 8;
1914    write_user_u64(user_as, sp, 0)?;
1915
1916    // Extra argv pointers in reverse (last arg highest in stack, first arg lowest)
1917    for &ptr in extra_ptrs.iter().rev() {
1918        sp -= 8;
1919        write_user_u64(user_as, sp, ptr)?;
1920    }
1921
1922    // argv[0] = program name
1923    sp -= 8;
1924    write_user_u64(user_as, sp, argv0_ptr)?;
1925
1926    // argc = 1 (name) + extra_args
1927    sp -= 8;
1928    write_user_u64(user_as, sp, 1u64 + extra_args.len() as u64)?;
1929
1930    debug_assert_eq!(sp & 0xF, 0);
1931    Ok(sp)
1932}
1933
1934/// Human-readable name of an ELF `e_type`, for log messages.
1935fn elf_type_name(e_type: u16) -> &'static str {
1936    if e_type == ET_DYN {
1937        "ET_DYN"
1938    } else {
1939        "ET_EXEC"
1940    }
1941}
1942
1943/// Map every `PT_LOAD` segment with a non-zero `p_memsz` into `user_as`.
1944/// Returns the number of segments mapped.
1945fn load_pt_load_segments(
1946    user_as: &AddressSpace,
1947    elf_data: &[u8],
1948    phdrs: &[Elf64Phdr],
1949    load_bias: u64,
1950) -> Result<u32, &'static str> {
1951    let mut count = 0u32;
1952    for phdr in phdrs.iter() {
1953        if phdr.p_type == PT_LOAD && phdr.p_memsz != 0 {
1954            load_segment(user_as, elf_data, phdr, load_bias)?;
1955            count += 1;
1956        }
1957    }
1958    Ok(count)
1959}
1960
1961/// Mark the `PT_GNU_RELRO` range read-only, once relocations are applied.
1962///
1963/// RELRO is a dynamic-linking concept: it protects the relocation targets
1964/// (`.got`, `.data.rel.ro`, ...) after the loader has fixed them up.  A static
1965/// `ET_EXEC` image has no `PT_DYNAMIC`, nothing relocates at run time, and
1966/// tools still emit a `PT_GNU_RELRO` program header whose range can cover
1967/// ordinary writable `.data` (lld does exactly that for the component linker
1968/// script, which puts `.got` inside `.data`).  Honouring it there turns the
1969/// first write to a global into a fatal protection fault, so RELRO is applied
1970/// only when the image really carries dynamic information.
1971fn apply_relro(
1972    user_as: &AddressSpace,
1973    phdrs: &[Elf64Phdr],
1974    load_bias: u64,
1975) -> Result<(), &'static str> {
1976    if !phdrs.iter().any(|ph| ph.p_type == PT_DYNAMIC) {
1977        return Ok(());
1978    }
1979    let Some(relro) = phdrs.iter().find(|ph| ph.p_type == PT_GNU_RELRO) else {
1980        return Ok(());
1981    };
1982    if relro.p_memsz == 0 {
1983        return Ok(());
1984    }
1985    let relro_start = relro.p_vaddr.wrapping_add(load_bias) & !0xFFF;
1986    // A partial trailing page may contain writable data outside RELRO.
1987    // Protect only through the last complete page, never round up.
1988    let relro_end = (relro.p_vaddr.wrapping_add(load_bias) + relro.p_memsz) & !0xFFF;
1989    if relro_end <= relro_start || relro_end > USER_ADDR_MAX {
1990        return Ok(());
1991    }
1992    let ro_flags = VmaFlags {
1993        readable: true,
1994        writable: false,
1995        executable: false,
1996        user_accessible: true,
1997    };
1998    let relro_pages = ((relro_end - relro_start) / 4096) as usize;
1999    apply_segment_permissions(user_as, relro_start, relro_pages, ro_flags)?;
2000    log::debug!(
2001        "[elf] PT_GNU_RELRO: {:#x}..{:#x} made read-only",
2002        relro_start,
2003        relro_end
2004    );
2005    Ok(())
2006}
2007
2008/// A `PT_INTERP` dynamic loader that has been mapped into the address space.
2009struct InterpreterImage {
2010    /// Relocated entry point of the interpreter.
2011    entry: u64,
2012    /// Relocated load base, published to the image as `AT_BASE`.
2013    base: u64,
2014    /// Number of `PT_LOAD` segments mapped from the interpreter.
2015    load_count: u32,
2016}
2017
2018/// Read, map and relocate the `PT_INTERP` dynamic loader named `path`.
2019fn load_interpreter(user_as: &AddressSpace, path: &str) -> Result<InterpreterImage, &'static str> {
2020    let interp_data = read_elf_from_vfs(path)?;
2021    let interp_header = parse_header(&interp_data)?;
2022    let interp_phdrs: Vec<Elf64Phdr> =
2023        try_collect_exact(interp_header.program_headers(&interp_data))?;
2024    if parse_interp_path(&interp_data, &interp_phdrs)?.is_some() {
2025        return Err("Nested PT_INTERP is not supported");
2026    }
2027    let (interp_bias, interp_entry) =
2028        compute_load_bias_and_entry(user_as, &interp_header, &interp_phdrs)?;
2029    let (interp_min_vaddr, _) = compute_load_bounds(&interp_phdrs)?;
2030    let load_count = load_pt_load_segments(user_as, &interp_data, &interp_phdrs, interp_bias)?;
2031    apply_dynamic_relocations(user_as, &interp_phdrs, interp_header.e_type, interp_bias)?;
2032    Ok(InterpreterImage {
2033        entry: interp_entry,
2034        base: interp_min_vaddr.saturating_add(interp_bias),
2035        load_count,
2036    })
2037}
2038
2039/// Whether the image requests an executable stack via `PT_GNU_STACK`.
2040///
2041/// Linux semantics: when several `PT_GNU_STACK` entries are present (rare,
2042/// but happens with hand-crafted or malicious binaries), only the *last*
2043/// one counts.  Using `.any(...)` would honour whichever PT_GNU_STACK
2044/// appears first and silently let an executable stack slip in even if
2045/// a later entry resets PF_X to 0.  Iterate from the back to match the
2046/// documented Linux behaviour.  Without PT_GNU_STACK, or without PF_X,
2047/// the stack is NX (modern default).
2048fn stack_is_executable(phdrs: &[Elf64Phdr]) -> bool {
2049    phdrs
2050        .iter()
2051        .rev()
2052        .find_map(|ph| {
2053            if ph.p_type == PT_GNU_STACK {
2054                Some((ph.p_flags & PF_X) != 0)
2055            } else {
2056                None
2057            }
2058        })
2059        .unwrap_or(false)
2060}
2061
2062/// Allocate and populate the Variant II TLS block (data at negative offsets
2063/// from `FS:0`).  Returns the thread pointer to install in `FS_BASE`, or 0
2064/// when the image carries no `PT_TLS` segment.
2065fn setup_tls_block(
2066    user_as: &AddressSpace,
2067    elf_data: &[u8],
2068    phdrs: &[Elf64Phdr],
2069) -> Result<u64, &'static str> {
2070    let Some(tls) = phdrs.iter().find(|p| p.p_type == PT_TLS) else {
2071        return Ok(0);
2072    };
2073    let tls_align = core::cmp::max(tls.p_align, 8).next_power_of_two();
2074    let aligned_memsz = (tls.p_memsz + tls_align - 1) & !(tls_align - 1);
2075    let total_size = aligned_memsz + 8;
2076    let n_tls_pages = ((total_size + 4095) / 4096) as usize;
2077    let tls_flags = VmaFlags {
2078        readable: true,
2079        writable: true,
2080        executable: false,
2081        user_accessible: true,
2082    };
2083    let tls_base = user_as
2084        .find_free_vma_range(0x7FFF_E000_0000, n_tls_pages, VmaPageSize::Small)
2085        .ok_or("No space for TLS block")?;
2086    user_as.map_region(
2087        tls_base,
2088        n_tls_pages,
2089        tls_flags,
2090        VmaType::Anonymous,
2091        VmaPageSize::Small,
2092    )?;
2093    if tls.p_filesz > 0 {
2094        let src_off = tls.p_offset as usize;
2095        let src_end = src_off
2096            .checked_add(tls.p_filesz as usize)
2097            .ok_or("PT_TLS offset+filesz overflows")?;
2098        if src_end > elf_data.len() {
2099            return Err("PT_TLS file data extends past ELF");
2100        }
2101        write_user_mapped_bytes(user_as, tls_base, &elf_data[src_off..src_end])?;
2102    }
2103    let tp = tls_base + aligned_memsz;
2104    write_user_u64(user_as, tp, tp)?;
2105    Ok(tp)
2106}
2107
2108/// The mapped user stack together with its canary slot.
2109struct UserStackLayout {
2110    /// First mapped page of the stack.
2111    base: u64,
2112    /// One past the last mapped byte of the stack.
2113    top: u64,
2114    /// Per-process random canary stored in the top word of the stack.
2115    canary: u64,
2116}
2117
2118/// Map the user stack, its guard page and its canary.
2119///
2120/// Per-process ASLR (issue #62): on top of the boot-time KASLR offset, each
2121/// image draws its own page-aligned jitter so two processes never share
2122/// identical stack addresses.  The stack size is configurable per process
2123/// (issue #64).  A single guard page below the stack is left unmapped :
2124/// underflow faults instead of silently corrupting neighbours.
2125fn map_user_stack(
2126    user_as: &AddressSpace,
2127    phdrs: &[Elf64Phdr],
2128    stack_pages: usize,
2129) -> Result<UserStackLayout, &'static str> {
2130    let stack_base = crate::kaslr::stack_base_with_jitter(crate::kaslr::draw_stack_jitter());
2131    let stack_top = crate::kaslr::stack_top_for(stack_base, stack_pages);
2132    let stack_flags = VmaFlags {
2133        readable: true,
2134        writable: true,
2135        executable: stack_is_executable(phdrs),
2136        user_accessible: true,
2137    };
2138    user_as.map_region(
2139        stack_base,
2140        stack_pages,
2141        stack_flags,
2142        VmaType::Stack,
2143        VmaPageSize::Small,
2144    )?;
2145    // Guard page: a single unmapped page below the stack.  Any stack
2146    // underflow (push past the bottom) hits this and faults.  The page
2147    // is intentionally left unmapped : no VMA, no PTE.
2148    log::debug!(
2149        "[elf] User stack: {:#x}..{:#x} ({} pages), guard at {:#x}",
2150        stack_base,
2151        stack_top,
2152        stack_pages,
2153        user_stack_guard(),
2154    );
2155
2156    // Stack canary (issue #63): a random per-process value occupies the
2157    // top word of the stack; all boot data lives strictly below it. The
2158    // kernel re-checks it at task exit (Task::verify_user_stack_canary).
2159    let mut canary_bytes = [0u8; 8];
2160    crate::e9_mark!(b'3');
2161    crate::entropy::fill_random(&mut canary_bytes);
2162    crate::e9_mark!(b'4');
2163    let stack_canary = u64::from_le_bytes(canary_bytes) | 1; // never 0
2164    crate::e9_mark!(b'5');
2165    write_user_u64(user_as, stack_top - 8, stack_canary)?;
2166    crate::e9_mark!(b'6');
2167
2168    Ok(UserStackLayout {
2169        base: stack_base,
2170        top: stack_top,
2171        canary: stack_canary,
2172    })
2173}
2174
2175/// Everything [`build_ring3_task`] needs to assemble the kernel-side task.
2176struct Ring3TaskParams<'a> {
2177    name: &'a str,
2178    user_as: Arc<AddressSpace>,
2179    seed_caps: &'a [Capability],
2180    stack: UserStackLayout,
2181    stack_pages: usize,
2182    /// Relocated entry point: the interpreter's when present, else the image's.
2183    runtime_entry: u64,
2184    /// Initial `RSP` handed to Ring 3, below the canary slot.
2185    boot_sp: u64,
2186    /// Thread pointer for `FS_BASE`, 0 when the image has no `PT_TLS`.
2187    user_fs_base: u64,
2188}
2189
2190/// Build the kernel task that trampolines into Ring 3, seed its capabilities
2191/// and stdio, and prime the initial interrupt frame.
2192///
2193/// Trampoline params are stored inside the task itself so that concurrent SMP
2194/// execution of multiple trampolines is safe.
2195fn build_ring3_task(params: Ring3TaskParams<'_>) -> Result<Arc<Task>, &'static str> {
2196    let Ring3TaskParams {
2197        name,
2198        user_as,
2199        seed_caps,
2200        stack,
2201        stack_pages,
2202        runtime_entry,
2203        boot_sp,
2204        user_fs_base,
2205    } = params;
2206
2207    log::trace!(
2208        "[trace][elf] load_elf_task kstack_begin size={}",
2209        Task::DEFAULT_STACK_SIZE
2210    );
2211    let kernel_stack = KernelStack::allocate(Task::DEFAULT_STACK_SIZE)?;
2212    log::trace!(
2213        "[trace][elf] load_elf_task kstack_done virt={:#x} top={:#x}",
2214        kernel_stack.virt_base.as_u64(),
2215        kernel_stack.virt_base.as_u64() + kernel_stack.size as u64
2216    );
2217    let context = CpuContext::new(elf_ring3_trampoline as *const () as u64, &kernel_stack);
2218    let (pid, tid, tgid) = Task::allocate_process_ids();
2219    let fpu_state = crate::process::task::ExtendedState::new();
2220    let xcr0_mask = fpu_state.xcr0_mask;
2221
2222    let task = Arc::new(Task {
2223        id: TaskId::new(),
2224        pid,
2225        tid,
2226        tgid,
2227        pgid: core::sync::atomic::AtomicU32::new(pid),
2228        sid: core::sync::atomic::AtomicU32::new(pid),
2229        uid: core::sync::atomic::AtomicU32::new(0),
2230        euid: core::sync::atomic::AtomicU32::new(0),
2231        gid: core::sync::atomic::AtomicU32::new(0),
2232        egid: core::sync::atomic::AtomicU32::new(0),
2233        silo_id: core::sync::atomic::AtomicU32::new(0),
2234        state: core::sync::atomic::AtomicU8::new(TaskState::Ready as u8),
2235        priority: TaskPriority::Normal,
2236        context: SyncUnsafeCell::new(context),
2237        resume_kind: SyncUnsafeCell::new(ResumeKind::RetFrame),
2238        interrupt_rsp: core::sync::atomic::AtomicU64::new(0),
2239        kernel_stack,
2240        user_stack: Some(crate::process::task::UserStack {
2241            virt_base: VirtAddr::new(stack.base),
2242            size: stack_pages * 4096,
2243        }),
2244        stack_canary: core::sync::atomic::AtomicU64::new(stack.canary),
2245        stack_canary_addr: core::sync::atomic::AtomicU64::new(stack.top - 8),
2246        kernel_stack_user: SyncUnsafeCell::new(None),
2247        name: alloc::string::String::from(name),
2248        process: Arc::new(crate::process::process::Process::new(pid, user_as)),
2249        pending_signals: super::signal::SignalSet::new(),
2250        blocked_signals: super::signal::SignalSet::new(),
2251        irq_signal_delivery_blocked: core::sync::atomic::AtomicBool::new(false),
2252        signal_stack: SyncUnsafeCell::new(None),
2253        itimers: super::timer::ITimers::new(),
2254        wake_pending: core::sync::atomic::AtomicBool::new(false),
2255        wake_deadline_ns: core::sync::atomic::AtomicU64::new(0),
2256        created_ns: crate::sync::scheduler_clock_ns(),
2257        blocked_ns_total: core::sync::atomic::AtomicU64::new(0),
2258        block_started_ns: core::sync::atomic::AtomicU64::new(0),
2259        trampoline_entry: core::sync::atomic::AtomicU64::new(runtime_entry),
2260        trampoline_stack_top: core::sync::atomic::AtomicU64::new(boot_sp),
2261        trampoline_arg0: core::sync::atomic::AtomicU64::new(0),
2262        ticks: core::sync::atomic::AtomicU64::new(0),
2263        sched_policy: core::sync::atomic::AtomicU32::new(
2264            Task::default_sched_policy(TaskPriority::Normal).to_raw(),
2265        ),
2266        home_cpu: core::sync::atomic::AtomicUsize::new(usize::MAX),
2267        last_cpu: core::sync::atomic::AtomicUsize::new(usize::MAX),
2268        affinity_mask: core::sync::atomic::AtomicU64::new(0),
2269        vruntime: core::sync::atomic::AtomicU64::new(0),
2270        fair_rq_generation: core::sync::atomic::AtomicU64::new(0),
2271        fair_on_rq: core::sync::atomic::AtomicBool::new(false),
2272        clear_child_tid: core::sync::atomic::AtomicU64::new(0),
2273        robust_list_head: core::sync::atomic::AtomicU64::new(0),
2274        robust_list_len: core::sync::atomic::AtomicUsize::new(0),
2275        user_fs_base: core::sync::atomic::AtomicU64::new(user_fs_base),
2276        fpu_state: crate::process::task::SyncUnsafeCell::new(fpu_state),
2277        xcr0_mask: core::sync::atomic::AtomicU64::new(xcr0_mask),
2278        rt_link: intrusive_collections::LinkedListLink::new(),
2279        rt_budget_remaining: core::sync::atomic::AtomicU64::new(0),
2280        rt_budget_period_start: core::sync::atomic::AtomicU64::new(0),
2281        rt_degraded: core::sync::atomic::AtomicBool::new(false),
2282        rt_overruns: core::sync::atomic::AtomicU64::new(0),
2283        fair_wait_ticks: core::sync::atomic::AtomicU64::new(0),
2284    });
2285
2286    log::trace!(
2287        "[trace][elf] load_elf_task task_built tid={} pid={} entry={:#x} sp={:#x}",
2288        task.id.as_u64(),
2289        task.pid,
2290        runtime_entry,
2291        boot_sp
2292    );
2293    // Seed capabilities into the new task (before scheduling).
2294    let mut bootstrap_handle: Option<u64> = None;
2295    if !seed_caps.is_empty() {
2296        let caps = unsafe { &*task.process.capabilities.get() };
2297        for cap in seed_caps {
2298            let id = caps.insert(cap.clone());
2299            if bootstrap_handle.is_none()
2300                && cap.resource_type == crate::capability::ResourceType::Volume
2301            {
2302                bootstrap_handle = Some(id.as_u64());
2303            }
2304        }
2305    }
2306
2307    // Setup stdin/stdout/stderr (fd 0/1/2) pointing to /dev/console
2308    // SAFETY: task is not yet scheduled, exclusive access to fd_table
2309    {
2310        let fd_table = unsafe { &mut *task.process.fd_table.get() };
2311        crate::vfs::console_scheme::setup_stdio(fd_table);
2312    }
2313
2314    if let Some(h) = bootstrap_handle {
2315        // Program entry will see this in its first argument register (RDI).
2316        task.trampoline_arg0
2317            .store(h, core::sync::atomic::Ordering::Release);
2318    }
2319
2320    task.seed_interrupt_frame(crate::syscall::SyscallFrame {
2321        r15: 0,
2322        r14: 0,
2323        r13: 0,
2324        r12: 0,
2325        rbp: 0,
2326        rbx: 0,
2327        r11: USER_RFLAGS,
2328        r10: 0,
2329        r9: 0,
2330        r8: 0,
2331        rsi: 0,
2332        rdi: task
2333            .trampoline_arg0
2334            .load(core::sync::atomic::Ordering::Acquire),
2335        rdx: 0,
2336        rcx: runtime_entry,
2337        rax: 0,
2338        iret_rip: runtime_entry,
2339        iret_cs: crate::arch::gdt::user_code_selector().0 as u64,
2340        iret_rflags: USER_RFLAGS,
2341        iret_rsp: boot_sp,
2342        iret_ss: crate::arch::gdt::user_data_selector().0 as u64,
2343    });
2344
2345    {
2346        let arc_data_ptr = Arc::as_ptr(&task) as usize;
2347        let fpu_ptr = task.fpu_state.get() as usize;
2348        if let Some(cur) = crate::process::scheduler::current_task_clone() {
2349            let cur_data_ptr = Arc::as_ptr(&cur) as usize;
2350            let cur_strong = Arc::strong_count(&cur);
2351            log::info!(
2352                "[elf] Task '{}' prepared: entry={:#x}, stack_top={:#x} \
2353                 new_arc={:#x} new_fpu={:#x} cur_arc={:#x} cur_strong={}",
2354                name,
2355                runtime_entry,
2356                boot_sp,
2357                arc_data_ptr,
2358                fpu_ptr,
2359                cur_data_ptr,
2360                cur_strong,
2361            );
2362        } else {
2363            log::info!(
2364                "[elf] Task '{}' prepared: entry={:#x}, stack_top={:#x} \
2365                 new_arc={:#x} new_fpu={:#x} (no current task)",
2366                name,
2367                runtime_entry,
2368                boot_sp,
2369                arc_data_ptr,
2370                fpu_ptr,
2371            );
2372        }
2373    }
2374
2375    Ok(task)
2376}
2377
2378/// Internal ELF task builder used by all public loading APIs.
2379/// `extra_args` are written to the user stack as argv[1..] after the program name.
2380fn load_elf_task_inner(
2381    elf_data: &[u8],
2382    name: &str,
2383    extra_args: &[&str],
2384    seed_caps: &[Capability],
2385    stack_pages: usize,
2386    memory_account: Option<Arc<crate::silo::SiloMemoryAccount>>,
2387) -> Result<Arc<Task>, &'static str> {
2388    if !(USER_STACK_MIN_PAGES..=USER_STACK_MAX_PAGES).contains(&stack_pages) {
2389        return Err("User stack size out of range");
2390    }
2391    log::trace!(
2392        "[trace][elf] load_elf_task enter name={} size={}",
2393        name,
2394        elf_data.len()
2395    );
2396    log::info!("[elf] Loading ELF '{}'...", name);
2397
2398    // Step 1: Parse and validate ELF header
2399    log::trace!("[trace][elf] load_elf_task parse_header begin");
2400    let header = match parse_header(elf_data) {
2401        Ok(h) => h,
2402        Err(e) => {
2403            log::error!("[elf] parse_header FAILED for '{}': {}", name, e);
2404            return Err(e);
2405        }
2406    };
2407    log::trace!(
2408        "[trace][elf] load_elf_task parse_header ok type={}",
2409        elf_type_name(header.e_type)
2410    );
2411    // Step 2: Create user address space
2412    log::trace!("[trace][elf] load_elf_task user_as begin");
2413    let user_as = Arc::new(AddressSpace::new_user()?);
2414    if let Some(account) = memory_account {
2415        user_as
2416            .bind_silo_memory_account(account)
2417            .map_err(|_| "Silo memory quota exceeded")?;
2418    }
2419    log::trace!("[trace][elf] load_elf_task user_as done");
2420
2421    let phdrs: Vec<Elf64Phdr> = try_collect_exact(header.program_headers(elf_data))?;
2422    let interp_path = parse_interp_path(elf_data, &phdrs)?;
2423    let (load_bias, entry) = compute_load_bias_and_entry(&user_as, &header, &phdrs)?;
2424    let phdr_vaddr = find_relocated_phdr_vaddr(&header, &phdrs, load_bias)?;
2425
2426    let phnum = header.e_phnum;
2427    log::trace!(
2428        "[trace][elf] load_elf_task layout entry={:#x} bias={:#x} phdrs={}",
2429        entry,
2430        load_bias,
2431        phnum
2432    );
2433    log::info!(
2434        "[elf] ELF '{}': type={}, entry={:#x}, bias={:#x}, {} program headers",
2435        name,
2436        elf_type_name(header.e_type),
2437        entry,
2438        load_bias,
2439        phnum,
2440    );
2441
2442    // Step 3: Load all PT_LOAD segments
2443    let load_count = load_pt_load_segments(&user_as, elf_data, &phdrs, load_bias)?;
2444    if interp_path.is_none() {
2445        apply_dynamic_relocations(&user_as, &phdrs, header.e_type, load_bias)?;
2446    }
2447    apply_relro(&user_as, &phdrs, load_bias)?;
2448
2449    log::trace!(
2450        "[trace][elf] load_elf_task segments_done count={} has_interp={}",
2451        load_count,
2452        interp_path.is_some()
2453    );
2454    log::info!("[elf] Loaded {} PT_LOAD segment(s)", load_count);
2455
2456    let mut runtime_entry = entry;
2457    let mut interp_base: Option<u64> = None;
2458    if let Some(path) = interp_path {
2459        let interp = load_interpreter(&user_as, path)?;
2460        runtime_entry = interp.entry;
2461        interp_base = Some(interp.base);
2462        log::info!(
2463            "[elf] PT_INTERP '{}' loaded: {} PT_LOAD, entry={:#x}",
2464            path,
2465            interp.load_count,
2466            runtime_entry
2467        );
2468    }
2469
2470    // TLS setup (Variant II: data at negative offsets from FS:0)
2471    let user_fs_base_val = setup_tls_block(&user_as, elf_data, &phdrs)?;
2472
2473    // Step 4: Map user stack
2474    let stack = map_user_stack(&user_as, &phdrs, stack_pages)?;
2475
2476    let boot_sp = setup_boot_user_stack(
2477        &user_as,
2478        name,
2479        extra_args,
2480        phdr_vaddr,
2481        header.e_phentsize,
2482        header.e_phnum,
2483        entry,
2484        interp_base,
2485        stack.base,
2486        stack.top - 8, // data must stay below the canary slot
2487    )?;
2488
2489    // Step 5: Create kernel task
2490    build_ring3_task(Ring3TaskParams {
2491        name,
2492        user_as,
2493        seed_caps,
2494        stack,
2495        stack_pages,
2496        runtime_entry,
2497        boot_sp,
2498        user_fs_base: user_fs_base_val,
2499    })
2500}
2501
2502/// Load an ELF binary into the provided address space.
2503/// Returns the entry point address.
2504///
2505/// # Duplication note (audit 2026-09-07, revisited in #65)
2506///
2507/// This function used to duplicate the parsing / PT_LOAD / RELRO / PT_INTERP
2508/// steps of [`load_elf_task_inner`].  Asterinas avoids the duplication by
2509/// separating `load_elf_to_vmar` (image-loading sink) from `do_execve`
2510/// (process setup).  In Strat9-OS the two paths have diverged over time :
2511/// this function does *not* allocate the TLS block itself (the caller in
2512/// [`crate::syscall::exec`] does), and it does *not* build a Task struct.
2513///
2514/// The shared image-loading steps now live in single-purpose helpers used by
2515/// both paths : [`load_pt_load_segments`], [`apply_relro`],
2516/// [`load_interpreter`] and [`stack_is_executable`] : so a loader-side fix
2517/// only has to be made once.  The remaining divergence is the TLS block:
2518/// `load_elf_task_inner` allocates it via [`setup_tls_block`] while this
2519/// function only reports the segment's geometry through
2520/// [`LoadedElfInfo`], leaving the allocation to its caller.
2521pub fn load_elf_image(
2522    elf_data: &[u8],
2523    user_as: &AddressSpace,
2524) -> Result<LoadedElfInfo, &'static str> {
2525    let header = match parse_header(elf_data) {
2526        Ok(h) => h,
2527        Err(e) => {
2528            log::error!("[elf] load_elf_image parse_header FAILED: {}", e);
2529            return Err(e);
2530        }
2531    };
2532    let phdrs: Vec<Elf64Phdr> = try_collect_exact(header.program_headers(elf_data))?;
2533    let interp_path = parse_interp_path(elf_data, &phdrs)?;
2534    let (load_bias, entry) = compute_load_bias_and_entry(user_as, &header, &phdrs)?;
2535    let phdr_vaddr = find_relocated_phdr_vaddr(&header, &phdrs, load_bias)?;
2536
2537    load_pt_load_segments(user_as, elf_data, &phdrs, load_bias)?;
2538    if interp_path.is_none() {
2539        apply_dynamic_relocations(user_as, &phdrs, header.e_type, load_bias)?;
2540    }
2541    apply_relro(user_as, &phdrs, load_bias)?;
2542
2543    let (tls_vaddr, tls_filesz, tls_memsz, tls_align) =
2544        if let Some(tls) = phdrs.iter().find(|ph| ph.p_type == PT_TLS) {
2545            let align = core::cmp::max(tls.p_align, 1).next_power_of_two();
2546            (
2547                tls.p_vaddr.saturating_add(load_bias),
2548                tls.p_filesz,
2549                tls.p_memsz,
2550                align,
2551            )
2552        } else {
2553            (0, 0, 0, 1)
2554        };
2555
2556    let mut runtime_entry = entry;
2557    let mut interp_base = None;
2558    if let Some(path) = interp_path {
2559        let interp = load_interpreter(user_as, path)?;
2560        runtime_entry = interp.entry;
2561        interp_base = Some(interp.base);
2562    }
2563
2564    Ok(LoadedElfInfo {
2565        runtime_entry,
2566        program_entry: entry,
2567        phdr_vaddr,
2568        phent: header.e_phentsize,
2569        phnum: header.e_phnum,
2570        interp_base,
2571        tls_vaddr,
2572        tls_filesz,
2573        tls_memsz,
2574        tls_align,
2575        stack_exec: stack_is_executable(&phdrs),
2576    })
2577}
2578
2579/// Reads user mapped bytes pub.
2580pub fn read_user_mapped_bytes_pub(
2581    user_as: &AddressSpace,
2582    vaddr: u64,
2583    out: &mut [u8],
2584) -> Result<(), &'static str> {
2585    read_user_mapped_bytes(user_as, vaddr, out)
2586}
2587
2588/// Writes user mapped bytes pub.
2589pub fn write_user_mapped_bytes_pub(
2590    user_as: &AddressSpace,
2591    vaddr: u64,
2592    src: &[u8],
2593) -> Result<(), &'static str> {
2594    write_user_mapped_bytes(user_as, vaddr, src)
2595}
2596
2597/// Writes user u64 pub.
2598pub fn write_user_u64_pub(
2599    user_as: &AddressSpace,
2600    vaddr: u64,
2601    value: u64,
2602) -> Result<(), &'static str> {
2603    write_user_u64(user_as, vaddr, value)
2604}