Skip to main content

strat9_kernel/syscall/
exec.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//! `execve()` syscall implementation.
24//! Replaces the current process image with a new one.
25
26use crate::{
27    memory::{AddressSpace, UserSliceRead, VmaFlags, VmaPageSize, VmaType},
28    process::{
29        current_task_clone,
30        elf::{load_elf_image, LoadedElfInfo, USER_STACK_PAGES},
31        get_task_ids_in_tgid,
32    },
33    syscall::{error::SyscallError, SyscallFrame},
34    vfs,
35};
36use alloc::vec::Vec;
37
38const AT_NULL: u64 = 0;
39const AT_PHDR: u64 = 3;
40const AT_PHENT: u64 = 4;
41const AT_PHNUM: u64 = 5;
42const AT_PAGESZ: u64 = 6;
43const AT_BASE: u64 = 7;
44const AT_ENTRY: u64 = 9;
45const AT_RANDOM: u64 = 25;
46const AT_EXECFN: u64 = 31;
47
48/// Read an executable image, borrowing static initfs bytes when available.
49fn read_exec_image(path: &str) -> Result<Option<Vec<u8>>, SyscallError> {
50    if crate::vfs::get_initfs_file_bytes(path).is_some() {
51        return Ok(None);
52    }
53
54    let fd = vfs::open(path, vfs::OpenFlags::READ)?;
55
56    const MAX_EXEC_SIZE: usize = 64 * 1024 * 1024;
57    let mut elf_data = Vec::new();
58    let mut buf = [0u8; 4096];
59    loop {
60        match vfs::read(fd, &mut buf) {
61            Ok(n) => {
62                if n == 0 {
63                    break;
64                }
65                if elf_data.len() + n > MAX_EXEC_SIZE {
66                    let _ = vfs::close(fd);
67                    return Err(SyscallError::OutOfMemory);
68                }
69                elf_data.extend_from_slice(&buf[..n]);
70            }
71            Err(e) => {
72                let _ = vfs::close(fd);
73                return Err(e);
74            }
75        }
76    }
77    let _ = vfs::close(fd);
78
79    Ok(Some(elf_data))
80}
81
82/// SYS_PROC_EXECVE (301): replace current process image.
83/// On success, does not return. On failure, returns an appropriate error code.
84/// This is the main syscall handler for execve, which performs the entire execve sequence:
85/// 1. Validate and read the executable image from the given path.
86/// 2. Create a new address space and load the ELF segments.
87/// 3. Set up the user stack with arguments, environment variables, and auxiliary vector.
88/// 4. Perform cleanup of the current process state (close fds, reset signals,
89///   clear TLS and TID pointer, etc) according to POSIX exec semantics.
90/// 5. Switch to the new address space and transfer control to the new image's entry point.
91/// The `setup_user_stack` function is a helper that performs step 3, which is complex enough to warrant its own function.
92/// The implementation assumes a simple model where sibling threads are not runnable during execve, which allows it to replace the entire address space without complex synchronization. This is a common approach in many kernels, but it does mean that multithreaded execve is not supported until the kernel can safely handle it.
93/// It also includes robust error handling to ensure that any failure during the execve sequence results in an appropriate error code without leaving the process in an inconsistent state.
94/// Note: This implementation does not currently support some features like setuid binaries, but it lays the groundwork for a full execve implementation with proper ELF loading and stack setup.
95///
96pub fn sys_execve(
97    frame: &mut SyscallFrame,
98    path_ptr: u64,
99    argv_ptr: u64,
100    envp_ptr: u64,
101) -> Result<u64, SyscallError> {
102    let current = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
103
104    // Replacing a shared address space while sibling threads are still runnable
105    // is unsafe in the current model. Refuse multithreaded exec until the
106    // kernel can synchronize and reap sibling threads atomically.
107    if get_task_ids_in_tgid(current.tgid).len() > 1 {
108        return Err(SyscallError::NotSupported);
109    }
110
111    let mut path_buf = [0u8; 4096];
112    let path_slice = UserSliceRead::new(path_ptr, 4096).map_err(|_| SyscallError::Fault)?;
113
114    let mut len = 0;
115
116    loop {
117        if len >= 4096 {
118            return Err(SyscallError::ArgumentListTooLong);
119        } // Reused error code
120        let b = path_slice.read_u8(len).map_err(|_| SyscallError::Fault)?;
121        if b == 0 {
122            break;
123        }
124        path_buf[len] = b;
125        len += 1;
126    }
127    let path_str =
128        core::str::from_utf8(&path_buf[..len]).map_err(|_| SyscallError::InvalidArgument)?;
129
130    let exec_path = vfs::resolve_and_check_path_for_current_task(path_str, true, false, true)?;
131
132    let owned_elf_data = read_exec_image(&exec_path)?;
133    let elf_data = owned_elf_data
134        .as_deref()
135        .or_else(|| crate::vfs::get_initfs_file_bytes(&exec_path))
136        .ok_or(SyscallError::NotFound)?;
137
138    if elf_data.len() < 4 {
139        return Err(SyscallError::ExecFormatError);
140    }
141
142    let new_as = AddressSpace::new_user().map_err(|_| SyscallError::OutOfMemory)?;
143    let new_as_arc = alloc::sync::Arc::new(new_as);
144    new_as_arc.set_owner_pid(current.pid);
145    if let Some(account) = current.process.address_space_arc().silo_memory_account() {
146        new_as_arc.bind_silo_memory_account(account)?;
147    }
148
149    let load_info = match load_elf_image(elf_data, &new_as_arc) {
150        Ok(info) => info,
151        Err("PT_INTERP execute denied") => return Err(SyscallError::PermissionDenied),
152        Err(_) => return Err(SyscallError::ExecFormatError),
153    };
154
155    let stack_flags = VmaFlags {
156        readable: true,
157        writable: true,
158        executable: false,
159        user_accessible: true,
160    };
161    // Per-process stack ASLR (issue #62): draw this image's own jitter and
162    // use it consistently for both the mapping and the initial SP.
163    let stack_base = crate::kaslr::stack_base_with_jitter(crate::kaslr::draw_stack_jitter());
164    let stack_top = crate::kaslr::stack_top_for(stack_base, USER_STACK_PAGES);
165    new_as_arc
166        .map_region(
167            stack_base,
168            USER_STACK_PAGES,
169            stack_flags,
170            VmaType::Stack,
171            VmaPageSize::Small,
172        )
173        .map_err(|_| SyscallError::OutOfMemory)?;
174
175    // Stack canary (issue #63): random per-image value at the top word.
176    let mut canary_bytes = [0u8; 8];
177    crate::entropy::fill_random(&mut canary_bytes);
178    let stack_canary = u64::from_le_bytes(canary_bytes) | 1; // never 0
179    write_bytes_to_as(&new_as_arc, stack_top - 8, &stack_canary.to_le_bytes())?;
180    current
181        .stack_canary
182        .store(stack_canary, core::sync::atomic::Ordering::Relaxed);
183    current
184        .stack_canary_addr
185        .store(stack_top - 8, core::sync::atomic::Ordering::Relaxed);
186
187    let sp = setup_user_stack(
188        &new_as_arc,
189        argv_ptr,
190        envp_ptr,
191        &load_info,
192        path_str.as_bytes(),
193        stack_base,
194        stack_top - 8, // data must stay below the canary slot
195    )?;
196
197    // TLS setup (Variant II) if the ELF has a PT_TLS segment.
198    let mut new_fs_base = 0u64;
199    if load_info.tls_memsz > 0 {
200        let tls_align = core::cmp::max(load_info.tls_align, 8).next_power_of_two();
201        let aligned_memsz = (load_info.tls_memsz + tls_align - 1) & !(tls_align - 1);
202        let total_size = aligned_memsz + 8;
203        let n_pages = ((total_size + 4095) / 4096) as usize;
204        let tls_flags = VmaFlags {
205            readable: true,
206            writable: true,
207            executable: false,
208            user_accessible: true,
209        };
210        let tls_base = new_as_arc
211            .find_free_vma_range(0x7FFF_E000_0000, n_pages, VmaPageSize::Small)
212            .ok_or(SyscallError::OutOfMemory)?;
213        new_as_arc
214            .map_region(
215                tls_base,
216                n_pages,
217                tls_flags,
218                VmaType::Anonymous,
219                VmaPageSize::Small,
220            )
221            .map_err(|_| SyscallError::OutOfMemory)?;
222        if load_info.tls_filesz > 0 && load_info.tls_vaddr != 0 {
223            let src_vaddr = load_info.tls_vaddr;
224            let mut off = 0u64;
225            let mut tmp = [0u8; 256];
226            while off < load_info.tls_filesz {
227                let chunk = core::cmp::min(256, (load_info.tls_filesz - off) as usize);
228                crate::process::elf::read_user_mapped_bytes_pub(
229                    &new_as_arc,
230                    src_vaddr + off,
231                    &mut tmp[..chunk],
232                )
233                .map_err(|_| SyscallError::Fault)?;
234                crate::process::elf::write_user_mapped_bytes_pub(
235                    &new_as_arc,
236                    tls_base + off,
237                    &tmp[..chunk],
238                )
239                .map_err(|_| SyscallError::Fault)?;
240                off += chunk as u64;
241            }
242        }
243        let tp = tls_base + aligned_memsz;
244        crate::process::elf::write_user_u64_pub(&new_as_arc, tp, tp)
245            .map_err(|_| SyscallError::Fault)?;
246        new_fs_base = tp;
247    }
248
249    // === EXECVE CLEANUP (POSIX semantics) ===
250    // Now that ELF is valid and loaded, perform cleanup before switching address space.
251
252    // 1. Close all file descriptors with CLOEXEC flag
253    unsafe {
254        let fd_table = &mut *current.process.fd_table.get();
255        fd_table.close_cloexec();
256    }
257
258    // 2. Reset all signal handlers to SIG_DFL
259    current.reset_signals();
260
261    // 2b. POSIX: exec disables the alternate signal stack for the new image.
262    unsafe {
263        *current.signal_stack.get() = None;
264    }
265
266    // 3. Clear thread-local storage address and TID pointer : POSIX exec semantics.
267    current
268        .clear_child_tid
269        .store(0, core::sync::atomic::Ordering::Relaxed);
270    current
271        .user_fs_base
272        .store(new_fs_base, core::sync::atomic::Ordering::Relaxed);
273
274    // 4. Reset memory layout: brk and mmap_hint belong to the old image.
275    current
276        .process
277        .brk
278        .store(0, core::sync::atomic::Ordering::Relaxed);
279    current.process.mmap_hint.store(
280        crate::kaslr::mmap_base(),
281        core::sync::atomic::Ordering::Relaxed,
282    );
283    // Set FS.base MSR for the new image TLS (or 0 if no PT_TLS).
284    #[cfg(target_arch = "x86_64")]
285    unsafe {
286        let lo = new_fs_base as u32;
287        let hi = (new_fs_base >> 32) as u32;
288        core::arch::asm!(
289            "mov ecx, 0xC0000100", // MSR_FS_BASE
290            "wrmsr",
291            in("eax") lo,
292            in("edx") hi,
293            options(nostack, preserves_flags),
294        );
295    }
296    #[cfg(not(target_arch = "x86_64"))]
297    let _ = new_fs_base; // riscv64: TLS base lives in tp (set at context switch, R3)
298
299    let old_as = current.process.replace_address_space(new_as_arc.clone());
300
301    unsafe {
302        current.process.address_space_arc().switch_to();
303    }
304
305    frame.iret_rip = load_info.runtime_entry;
306    frame.iret_rsp = sp;
307    frame.iret_rflags = 0x200; // IF=1, clean slate for the new image
308
309    frame.rdi = 0;
310    frame.rsi = 0;
311    frame.rdx = 0;
312    frame.rcx = 0;
313    frame.r8 = 0;
314    frame.r9 = 0;
315    frame.r10 = 0;
316    frame.r11 = 0;
317    frame.rbx = 0;
318    frame.rbp = 0;
319    frame.r12 = 0;
320    frame.r13 = 0;
321    frame.r14 = 0;
322    frame.r15 = 0;
323    frame.rax = 0;
324
325    // Safely drop the old address space now that the new CR3 is loaded
326    drop(old_as);
327
328    Ok(0)
329}
330
331/// Performs the setup user stack operation.
332fn setup_user_stack(
333    new_as: &AddressSpace,
334    argv_ptr: u64,
335    envp_ptr: u64,
336    elf_info: &LoadedElfInfo,
337    exec_path: &[u8],
338    stack_base: u64,
339    stack_top: u64,
340) -> Result<u64, SyscallError> {
341    let args = read_string_array(argv_ptr)?;
342    let envs = read_string_array(envp_ptr)?;
343
344    let mut sp = stack_top;
345    let mut str_ptrs: Vec<u64> = Vec::with_capacity(args.len()); // stores pointers to arguments
346    let mut env_ptrs: Vec<u64> = Vec::with_capacity(envs.len()); // stores pointers to env vars
347
348    // Push strings to stack (highest addresses)
349    // We push them in reverse order so they appear in memory roughly sequentially for cache locality?
350    // Actually standard is to put them at very top. Order doesn't strictly matter as long as pointers are correct.
351    // We'll push ENV strings first (highest), then ARG strings.
352
353    // Push ENV strings
354    for env in envs.iter().rev() {
355        let len = (env.len() + 1) as u64;
356        sp = sp
357            .checked_sub(len)
358            .ok_or(SyscallError::ArgumentListTooLong)?;
359        if sp < stack_base {
360            return Err(SyscallError::ArgumentListTooLong);
361        }
362        write_bytes_to_as(new_as, sp, env)?;
363        write_bytes_to_as(new_as, sp + env.len() as u64, &[0])?;
364        env_ptrs.push(sp);
365    }
366    // env_ptrs: [ptr_to_highest_env, ptr_to_second_highest...] which corresponds to [env[last], env[last-1]...]
367    // Userspace expects envp[0] to point to first env string.
368    // So we need to reverse env_ptrs to match original order.
369    env_ptrs.reverse();
370
371    // Push ARG strings
372    for arg in args.iter().rev() {
373        let len = (arg.len() + 1) as u64;
374        sp = sp
375            .checked_sub(len)
376            .ok_or(SyscallError::ArgumentListTooLong)?;
377        if sp < stack_base {
378            return Err(SyscallError::ArgumentListTooLong);
379        }
380        write_bytes_to_as(new_as, sp, arg)?;
381        write_bytes_to_as(new_as, sp + arg.len() as u64, &[0])?;
382        str_ptrs.push(sp);
383    }
384    str_ptrs.reverse();
385
386    // Push exec path (for AT_EXECFN).
387    let mut execfn_ptr = 0u64;
388    if !exec_path.is_empty() {
389        let len = (exec_path.len() + 1) as u64;
390        sp -= len;
391        write_bytes_to_as(new_as, sp, exec_path)?;
392        write_bytes_to_as(new_as, sp + exec_path.len() as u64, &[0])?;
393        execfn_ptr = sp;
394    }
395
396    // Push 16 bytes of random seed for AT_RANDOM (deterministic fallback source).
397    sp -= 16;
398    let rand_ptr = sp;
399    let seed = generate_aux_random_seed();
400    write_bytes_to_as(new_as, rand_ptr, &seed)?;
401
402    // Align SP to 16 bytes for System V ABI
403    sp &= !0xF;
404
405    // Phase 2: Push auxv, pointer arrays, then argc.
406    let size_ptr = 8u64;
407
408    // auxv entries end with AT_NULL.
409    let mut auxv: Vec<(u64, u64)> = Vec::with_capacity(10);
410    auxv.push((AT_PHDR, elf_info.phdr_vaddr));
411    auxv.push((AT_PHENT, elf_info.phent as u64));
412    auxv.push((AT_PHNUM, elf_info.phnum as u64));
413    auxv.push((AT_PAGESZ, 4096));
414    if let Some(base) = elf_info.interp_base {
415        auxv.push((AT_BASE, base));
416    }
417    auxv.push((AT_ENTRY, elf_info.program_entry));
418    auxv.push((AT_RANDOM, rand_ptr));
419    if execfn_ptr != 0 {
420        auxv.push((AT_EXECFN, execfn_ptr));
421    }
422
423    // Reserve padding above auxv so the final entry RSP still points at argc
424    // while satisfying the SysV x86_64 16-byte alignment requirement.
425    let stack_words = 1u64
426        + (str_ptrs.len() as u64 + 1)
427        + (env_ptrs.len() as u64 + 1)
428        + ((auxv.len() as u64 + 1) * 2);
429    let align_pad = (0u64.wrapping_sub(stack_words * size_ptr)) & 0xF;
430    sp -= align_pad;
431
432    // AT_NULL terminator.
433    sp -= size_ptr;
434    write_u64_to_as(new_as, sp, 0)?;
435    sp -= size_ptr;
436    write_u64_to_as(new_as, sp, AT_NULL)?;
437    for &(key, val) in auxv.iter().rev() {
438        sp -= size_ptr;
439        write_u64_to_as(new_as, sp, val)?;
440        sp -= size_ptr;
441        write_u64_to_as(new_as, sp, key)?;
442    }
443
444    // Push ENVP array
445    // [NULL]
446    // [envp[n]]
447    // ...
448    // [envp[0]]
449    sp -= size_ptr;
450    write_u64_to_as(new_as, sp, 0)?; // NULL terminator
451
452    for &ptr in env_ptrs.iter().rev() {
453        sp -= size_ptr;
454        write_u64_to_as(new_as, sp, ptr)?;
455    }
456    // Note: sp now points to envp[0]
457
458    // Push ARGV array
459    // [NULL]
460    // [argv[n]]
461    // ...
462    // [argv[0]]
463    sp -= size_ptr;
464    write_u64_to_as(new_as, sp, 0)?; // NULL terminator
465
466    for &ptr in str_ptrs.iter().rev() {
467        sp -= size_ptr;
468        write_u64_to_as(new_as, sp, ptr)?;
469    }
470    // Note: sp now points to argv[0]
471
472    // Push ARGC
473    sp -= size_ptr;
474    write_u64_to_as(new_as, sp, args.len() as u64)?;
475
476    debug_assert_eq!(sp & 0xF, 0);
477
478    Ok(sp)
479}
480
481/// Reads string array.
482fn read_string_array(ptr: u64) -> Result<Vec<Vec<u8>>, SyscallError> {
483    let mut res = Vec::new();
484    if ptr == 0 {
485        return Ok(res);
486    }
487
488    let mut arr_off = 0;
489    loop {
490        // Read string pointer from user memory (current AS)
491        let str_ptr = match UserSliceRead::new(ptr + arr_off, 8) {
492            Ok(slice) => match slice.read_u64(0) {
493                Ok(p) => p,
494                Err(_) => return Err(SyscallError::Fault),
495            },
496            Err(_) => return Err(SyscallError::Fault),
497        };
498
499        if str_ptr == 0 {
500            break;
501        }
502        if res.len() > 1024 {
503            return Err(SyscallError::ArgumentListTooLong);
504        }
505
506        let mut s = Vec::new();
507        let mut i = 0;
508        loop {
509            if i > 4096 {
510                return Err(SyscallError::ArgumentListTooLong);
511            }
512            let b = match UserSliceRead::new(str_ptr + i, 1) {
513                Ok(slice) => match slice.read_u8(0) {
514                    Ok(byte) => byte,
515                    Err(_) => return Err(SyscallError::Fault),
516                },
517                Err(_) => return Err(SyscallError::Fault),
518            };
519            if b == 0 {
520                break;
521            }
522            s.push(b);
523            i += 1;
524        }
525        res.push(s);
526        arr_off += 8;
527    }
528    Ok(res)
529}
530
531/// Writes bytes to as.
532fn write_bytes_to_as(as_ref: &AddressSpace, vaddr: u64, data: &[u8]) -> Result<(), SyscallError> {
533    use crate::arch::xshim::VirtAddr;
534    let mut written = 0;
535    // We assume data is small enough or we loop? Using unsafe pointer arithmetic.
536    // The `AddressSpace` methods like `translate` are needed.
537
538    // Since `load_elf_image` in `elf.rs` used `translate`, we should verify visibility.
539    // `AddressSpace` is usually public. `translate` is on `Mapper` trait?
540    // `AddressSpace` in `strat9` likely implements `Mapper` or has it.
541    // `elf.rs` used `user_as.translate(...)`.
542
543    // I need to import Translate? `AddressSpace` usually has `translate`.
544
545    while written < data.len() {
546        let curr_vaddr = vaddr + written as u64;
547        let page_offset = (curr_vaddr & 0xFFF) as usize;
548        let chunk_size = core::cmp::min(data.len() - written, 4096 - page_offset);
549
550        // translate might fail if page not mapped.
551        // `stack_base()`..`stack_top()` is mapped.
552        let phys = as_ref
553            .translate(VirtAddr::new(curr_vaddr))
554            .ok_or(SyscallError::Fault)?;
555        let virt = crate::memory::phys_to_virt(phys.as_u64()) as *mut u8;
556
557        unsafe {
558            core::ptr::copy_nonoverlapping(data.as_ptr().add(written), virt, chunk_size);
559        }
560        written += chunk_size;
561    }
562    Ok(())
563}
564
565/// Writes u64 to as.
566fn write_u64_to_as(as_ref: &AddressSpace, vaddr: u64, val: u64) -> Result<(), SyscallError> {
567    let bytes = val.to_ne_bytes();
568    write_bytes_to_as(as_ref, vaddr, &bytes)
569}
570
571/// Performs the generate aux random seed operation.
572fn generate_aux_random_seed() -> [u8; 16] {
573    let mut seed = [0u8; 16];
574    crate::entropy::fill_random(&mut seed);
575    seed
576}