Skip to main content

c/
startup.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// Startup: __libc_start_main
6//
7// musl crt1.o _start_c calls:
8//   __libc_start_main(main, argc, argv, _init, _fini, rtld_fini, stack_end)
9// ============================================================
10
11// Auxiliary vector pointer, populated by the dynamic linker before
12// constructors run so getauxval() works during early startup.
13#[no_mangle]
14pub static mut __auxv: *const usize = core::ptr::null();
15#[no_mangle]
16pub static mut __keel_static_base: usize = 0;
17static mut RC_STATIC_EXEC: bool = false;
18
19#[no_mangle]
20pub static mut __progname: *mut c_char = core::ptr::null_mut();
21#[no_mangle]
22pub static mut __progname_full: *mut c_char = core::ptr::null_mut();
23#[no_mangle]
24pub static mut program_invocation_name: *mut c_char = core::ptr::null_mut();
25#[no_mangle]
26pub static mut program_invocation_short_name: *mut c_char = core::ptr::null_mut();
27
28#[no_mangle]
29pub static in6addr_any: [u32; 4] = [0; 4];
30#[no_mangle]
31pub static in6addr_loopback: [u32; 4] = [0, 0, 0, 0x0100_0000];
32
33#[no_mangle]
34pub static mut __daylight: c_int = 0;
35#[no_mangle]
36pub static mut __timezone: c_long = 0;
37#[no_mangle]
38pub static mut __tzname: [*mut c_char; 2] = [core::ptr::null_mut(); 2];
39
40#[no_mangle]
41pub unsafe extern "C" fn getauxval(type_: c_ulong) -> c_ulong {
42    let mut p = __auxv;
43    if p.is_null() {
44        return 0;
45    }
46    loop {
47        let tag = *p;
48        if tag == 0 {
49            return 0;
50        }
51        if tag == type_ as usize {
52            return *p.add(1) as c_ulong;
53        }
54        p = p.add(2);
55    }
56}
57
58
59unsafe fn run_static_init() {
60    if !RC_STATIC_EXEC {
61        return;
62    }
63    extern "C" {
64        static __preinit_array_start: usize;
65        static __preinit_array_end: usize;
66        static __init_array_start: usize;
67        static __init_array_end: usize;
68    }
69    let mut p = core::ptr::addr_of!(__preinit_array_start) as usize;
70    let end = core::ptr::addr_of!(__preinit_array_end) as usize;
71    while p < end {
72        let f = core::ptr::read_unaligned(p as *const usize);
73        if f != 0 {
74            let f: unsafe extern "C" fn() = core::mem::transmute(f);
75            f();
76        }
77        p += core::mem::size_of::<usize>();
78    }
79    p = core::ptr::addr_of!(__init_array_start) as usize;
80    let end = core::ptr::addr_of!(__init_array_end) as usize;
81    while p < end {
82        let f = core::ptr::read_unaligned(p as *const usize);
83        if f != 0 {
84            let f: unsafe extern "C" fn() = core::mem::transmute(f);
85            f();
86        }
87        p += core::mem::size_of::<usize>();
88    }
89}
90
91type MainFn = unsafe extern "C" fn(c_int, *const *const c_char, *const *const c_char) -> c_int;
92type InitFn = unsafe extern "C" fn();
93
94#[cfg(target_arch = "x86_64")]
95unsafe fn static_tls_tp() -> usize {
96    let mut fs: u64 = 0;
97    if arch_prctl(0x1003, &mut fs as *mut u64 as u64) != 0 {
98        0
99    } else {
100        fs as usize
101    }
102}
103
104#[cfg(target_arch = "x86_64")]
105unsafe fn set_static_tls_tp(tp: usize) {
106    let _ = arch_prctl(0x1002, tp as u64);
107}
108
109#[cfg(target_arch = "aarch64")]
110unsafe fn static_tls_tp() -> usize {
111    let tp: usize;
112    core::arch::asm!("mrs {}, tpidr_el0", out(reg) tp, options(nostack));
113    tp
114}
115
116#[cfg(target_arch = "aarch64")]
117unsafe fn set_static_tls_tp(tp: usize) {
118    core::arch::asm!("msr tpidr_el0, {}", in(reg) tp, options(nostack));
119}
120
121#[cfg(target_arch = "riscv64")]
122unsafe fn static_tls_tp() -> usize {
123    let tp: usize;
124    core::arch::asm!("mv {}, tp", out(reg) tp, options(nostack));
125    tp
126}
127
128#[cfg(target_arch = "powerpc64")]
129unsafe fn static_tls_tp() -> usize {
130    let tp: usize;
131    core::arch::asm!("mr {}, 13", out(reg) tp, options(nostack));
132    tp
133}
134
135#[cfg(target_arch = "powerpc64")]
136unsafe fn set_static_tls_tp(tp: usize) {
137    core::arch::asm!("mr 13, {}", in(reg) tp, options(nostack));
138}
139
140#[cfg(target_arch = "loongarch64")]
141unsafe fn static_tls_tp() -> usize {
142    let tp: usize;
143    core::arch::asm!("move {}, $tp", out(reg) tp, options(nostack));
144    tp
145}
146
147#[cfg(target_arch = "loongarch64")]
148unsafe fn set_static_tls_tp(tp: usize) {
149    core::arch::asm!("move $tp, {}", in(reg) tp, options(nostack));
150}
151
152#[cfg(target_arch = "riscv64")]
153unsafe fn set_static_tls_tp(tp: usize) {
154    core::arch::asm!("mv tp, {}", in(reg) tp, options(nostack));
155}
156
157static mut STATIC_TLS_BLOCK_SIZE: usize = 0;
158static mut STATIC_TLS_TP_OFFSET: usize = 0;
159static mut STATIC_TLS_VAR_OFFSET: usize = 0;
160static mut STATIC_TLS_TLS_SIZE: usize = 0;
161static mut STATIC_TLS_IMAGE: *const u8 = core::ptr::null();
162static mut STATIC_TLS_FILESZ: usize = 0;
163static mut STATIC_TLS_CANARY: u64 = 0;
164
165// Word indices in the 256-byte TCB. Keep in sync with libc/src/ldso/mod.rs.
166const TCB_GENERATION: usize = 1;
167const TCB_TLS_SIZE: usize = 2;
168const TCB_MODULE_COUNT: usize = 3;
169const TCB_TLSDESC: usize = 4;
170const TCB_CANARY: usize = 5;
171const TCB_ERRNO: usize = 6;
172const TCB_GETRANDOM: usize = 7;
173const TCB_THREAD: usize = 8;
174
175unsafe fn static_tls_init_block(block: *mut u8) -> *mut u8 {
176    if block.is_null() || STATIC_TLS_BLOCK_SIZE == 0 {
177        return core::ptr::null_mut();
178    }
179    let var_base = block.add(STATIC_TLS_VAR_OFFSET);
180    if STATIC_TLS_TLS_SIZE > 0 {
181        core::ptr::write_bytes(var_base, 0, STATIC_TLS_TLS_SIZE);
182    }
183    if STATIC_TLS_FILESZ > 0 && !STATIC_TLS_IMAGE.is_null() {
184        core::ptr::copy_nonoverlapping(STATIC_TLS_IMAGE, var_base, STATIC_TLS_FILESZ);
185    }
186    let tp = block.add(STATIC_TLS_TP_OFFSET);
187    let tcb = if cfg!(target_arch = "x86_64") {
188        tp as usize
189    } else {
190        block as usize
191    };
192    core::ptr::write_unaligned(tcb as *mut u64, tcb as u64);
193    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_GENERATION), 1);
194    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_TLS_SIZE), STATIC_TLS_TLS_SIZE as u64);
195    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_MODULE_COUNT), 1);
196    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_TLSDESC), 0);
197    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_CANARY), STATIC_TLS_CANARY);
198    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_ERRNO), 0);
199    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_GETRANDOM), 0);
200    core::ptr::write_unaligned((tcb as *mut u64).add(TCB_THREAD), 0);
201    tp
202}
203
204unsafe fn static_tls_create_block() -> *mut u8 {
205    if STATIC_TLS_BLOCK_SIZE == 0 {
206        return core::ptr::null_mut();
207    }
208    let block = sys_mmap(
209        core::ptr::null_mut(),
210        STATIC_TLS_BLOCK_SIZE,
211        PROT_READ | PROT_WRITE,
212        MAP_PRIVATE | MAP_ANONYMOUS,
213        -1,
214        0,
215    );
216    if block.is_null() || block == MMAP_FAILED {
217        return core::ptr::null_mut();
218    }
219    static_tls_init_block(block)
220}
221
222#[repr(C)]
223pub struct TlsIndex {
224    pub ti_module: usize,
225    pub ti_offset: usize,
226}
227
228/// Global-dynamic TLS access.  The dynamic loader intercepts this symbol for
229/// dynamically linked programs and uses its own multi-module implementation.
230/// A static executable has only module 0, so resolve directly against the
231/// static TLS block created by `init_static_tls()`.
232static mut TLS_GET_ADDR_IMPL: usize = 0;
233
234/// The dynamic loader installs its multi-module TLS resolver here before
235/// running constructors.  Keeping a dispatch pointer means a program that
236/// obtains `__tls_get_addr` through `dlsym` still reaches the loader's
237/// implementation rather than the static fallback below.
238#[no_mangle]
239pub unsafe extern "C" fn __keel_set_tls_get_addr(f: usize) {
240    TLS_GET_ADDR_IMPL = f;
241}
242
243#[no_mangle]
244pub unsafe extern "C" fn __tls_get_addr(ti: *const TlsIndex) -> *mut u8 {
245    if TLS_GET_ADDR_IMPL != 0 {
246        let f: unsafe extern "C" fn(*const TlsIndex) -> *mut u8 =
247            core::mem::transmute(TLS_GET_ADDR_IMPL);
248        return f(ti);
249    }
250    if ti.is_null() || (*ti).ti_module != 0 || !RC_STATIC_EXEC {
251        return core::ptr::null_mut();
252    }
253    let tp = static_tls_tp();
254    if tp == 0 {
255        return core::ptr::null_mut();
256    }
257    #[cfg(target_arch = "powerpc64")]
258    let dtp_bias = 0x8000usize;
259    #[cfg(not(target_arch = "powerpc64"))]
260    let dtp_bias = 0usize;
261    (tp - STATIC_TLS_TP_OFFSET + STATIC_TLS_VAR_OFFSET + (*ti).ti_offset + dtp_bias) as *mut u8
262}
263
264/// Static executables have no dynamic loader to build a TCB.  Allocate one
265/// from PT_TLS so that `%fs`/TP-relative TLS accesses and errno work.
266unsafe fn init_static_tls() {
267    if static_tls_tp() != 0 {
268        return;
269    }
270    let phdr = getauxval(3) as usize; // AT_PHDR
271    let phnum = getauxval(5) as usize; // AT_PHNUM
272    let phent = getauxval(4) as usize; // AT_PHENT
273    if phdr == 0 || phnum == 0 || phent < 56 {
274        return;
275    }
276
277    let mut tls_vaddr = 0usize;
278    let mut tls_filesz = 0usize;
279    let mut tls_memsz = 0usize;
280    let mut tls_align = 1usize;
281    let mut exec_base = __keel_static_base;
282    let mut i = 0usize;
283    while i < phnum {
284        let ph = phdr + i * phent;
285        let p_type = core::ptr::read_unaligned(ph as *const u32);
286        if p_type == 3 {
287            // PT_INTERP means the dynamic loader already owns TLS.
288            return;
289        }
290        if p_type == 6 {
291            // PT_PHDR
292            if exec_base == 0 {
293                let p_vaddr = core::ptr::read_unaligned((ph + 16) as *const u64) as usize;
294                exec_base = phdr.wrapping_sub(p_vaddr);
295            }
296        } else if p_type == 7 {
297            // PT_TLS
298            tls_vaddr = core::ptr::read_unaligned((ph + 16) as *const u64) as usize;
299            tls_filesz = core::ptr::read_unaligned((ph + 32) as *const u64) as usize;
300            tls_memsz = core::ptr::read_unaligned((ph + 40) as *const u64) as usize;
301            let align = core::ptr::read_unaligned((ph + 48) as *const u64) as usize;
302            if align > 1 {
303                tls_align = align;
304            }
305        }
306        i += 1;
307    }
308
309    let tcb_size = 256usize;
310    #[cfg(target_arch = "x86_64")]
311    let gap = 0usize;
312    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
313    let gap = if cfg!(target_arch = "aarch64") { 16usize } else { 0usize };
314    #[cfg(any(target_arch = "powerpc64", target_arch = "loongarch64"))]
315    let gap = 0usize;
316
317    let tls_size = if tls_align > 1 {
318        (tls_memsz + tls_align - 1) & !(tls_align - 1)
319    } else {
320        tls_memsz
321    };
322    let total = tcb_size + gap + tls_size + tls_align;
323    STATIC_TLS_BLOCK_SIZE = total;
324    STATIC_TLS_TP_OFFSET = if cfg!(target_arch = "x86_64") {
325        tls_size
326    } else if cfg!(target_arch = "powerpc64") {
327        // ELFv2 encodes TP-relative offsets with a -0x7000 bias, so TP sits
328        // 0x7000 bytes above the TLS variable area.
329        tcb_size + 0x7000
330    } else {
331        tcb_size
332    };
333    STATIC_TLS_VAR_OFFSET = if cfg!(target_arch = "x86_64") {
334        0
335    } else {
336        tcb_size + gap
337    };
338    STATIC_TLS_TLS_SIZE = tls_size;
339    STATIC_TLS_IMAGE = (exec_base + tls_vaddr) as *const u8;
340    STATIC_TLS_FILESZ = tls_filesz;
341    let random = getauxval(25) as *const u8; // AT_RANDOM
342    STATIC_TLS_CANARY = if random.is_null() {
343        0xdefaced_cafebeefu64
344    } else {
345        core::ptr::read_unaligned(random as *const u64)
346            ^ core::ptr::read_unaligned(random.add(8) as *const u64)
347    };
348
349    let block = sys_mmap(
350        core::ptr::null_mut(),
351        total,
352        PROT_READ | PROT_WRITE,
353        MAP_PRIVATE | MAP_ANONYMOUS,
354        -1,
355        0,
356    );
357    if block.is_null() || block == MMAP_FAILED {
358        return;
359    }
360    let tp = static_tls_init_block(block);
361    if tp.is_null() {
362        return;
363    }
364    set_static_tls_tp(tp as usize);
365    RC_STATIC_EXEC = true;
366}
367
368
369#[no_mangle]
370pub unsafe extern "C" fn __libc_start_main(
371    main: MainFn,
372    argc: c_int,
373    argv: *const *const c_char,
374    _init: *const c_void,
375    _fini: *const c_void,
376    _rtld_fini: *const c_void,
377    _stack_end: *const c_void,
378) -> ! {
379    let envp = argv.add((argc + 1) as usize);
380    let mut aux = envp;
381    while !(*aux).is_null() {
382        aux = aux.add(1);
383    }
384    __auxv = aux.add(1) as *const usize;
385    init_static_tls();
386    errno_init();
387    // Register the main thread during startup.  pthread_exit() uses the
388    // thread table to decide whether it is the last thread; if the main
389    // thread only registered lazily, a worker exiting first could call
390    // exit() while the main thread was still alive.  Register slot 0
391    // directly: pthread_self() would otherwise scan the whole static thread
392    // table and fault in roughly 1 MiB on every process start.
393    register_main_thread();
394
395    __environ = envp as *mut *mut c_char;
396    environ = __environ; // sync environ alias
397    ___environ = __environ;
398    _environ = __environ;
399
400    // glibc-compatible program name globals.
401    if !argv.is_null() && argc > 0 {
402        let argv0 = *argv;
403        __progname_full = argv0 as *mut c_char;
404        program_invocation_name = argv0 as *mut c_char;
405        let mut base = argv0;
406        let mut p = argv0;
407        while *p != 0 {
408            if *p == b'/' as c_char { base = p.add(1); }
409            p = p.add(1);
410        }
411        __progname = base as *mut c_char;
412        program_invocation_short_name = base as *mut c_char;
413    }
414
415    __stdio_init();
416    run_static_init();
417
418    let mut set: SigSetT = 0;
419    sigemptyset(&mut set);
420    sigaddset(&mut set, SIGCANCEL);
421    sigprocmask(SIG_UNBLOCK, &set, core::ptr::null_mut());
422
423    if !_init.is_null() {
424        let init_fn: InitFn = core::mem::transmute(_init);
425        init_fn();
426    }
427
428    // aarch64/riscv64/loongarch64 GCC reads __stack_chk_guard as a global
429    // (GOT-based for PIE) and powerpc64 through its TOC, so initialize it
430    // from AT_RANDOM before calling main.  x86_64 uses %fs:0x28, which the
431    // kernel already set up.
432    #[cfg(any(
433        target_arch = "aarch64",
434        target_arch = "riscv64",
435        target_arch = "powerpc64",
436        target_arch = "loongarch64"
437    ))]
438    {
439        let random_ptr = getauxval(25) as *const u8; // AT_RANDOM = 25
440        if !random_ptr.is_null() {
441            let a = core::ptr::read_unaligned(random_ptr as *const u64);
442            let b = core::ptr::read_unaligned(random_ptr.add(8) as *const u64);
443            __stack_chk_guard = (a ^ b) as usize;
444        } else {
445            // Linux always supplies AT_RANDOM; keep a nonzero fallback for
446            // the unlikely case where the auxiliary vector is absent.
447            __stack_chk_guard = 0xdefaced_cafebeef;
448        }
449    }
450
451    let result = main(argc, argv, envp);
452
453    if !_fini.is_null() {
454        let fini_fn: InitFn = core::mem::transmute(_fini);
455        fini_fn();
456    }
457
458    exit(result);
459}
460
461type LdsoDlopenFn = unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void;
462type LdsoDlsymFn = unsafe extern "C" fn(*mut c_void, *const c_char, *mut c_void) -> *mut c_void;
463type LdsoDlcloseFn = unsafe extern "C" fn(*mut c_void) -> c_int;
464type LdsoDlerrorFn = unsafe extern "C" fn() -> *const c_char;
465
466static mut LDSO_DLOPEN: Option<LdsoDlopenFn> = None;
467static mut LDSO_DLSYM: Option<LdsoDlsymFn> = None;
468static mut LDSO_DLCLOSE: Option<LdsoDlcloseFn> = None;
469static mut LDSO_DLERROR: Option<LdsoDlerrorFn> = None;
470
471#[no_mangle]
472pub unsafe extern "C" fn __ldso_register_dlopen(f: LdsoDlopenFn) {
473    LDSO_DLOPEN = Some(f);
474}
475
476#[no_mangle]
477pub unsafe extern "C" fn __ldso_register_dlsym(f: LdsoDlsymFn) {
478    LDSO_DLSYM = Some(f);
479}
480
481#[no_mangle]
482pub unsafe extern "C" fn __ldso_register_dlclose(f: LdsoDlcloseFn) {
483    LDSO_DLCLOSE = Some(f);
484}
485
486#[no_mangle]
487pub unsafe extern "C" fn __ldso_register_dlerror(f: LdsoDlerrorFn) {
488    LDSO_DLERROR = Some(f);
489}
490
491#[no_mangle]
492pub unsafe extern "C" fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void {
493    if let Some(f) = LDSO_DLOPEN {
494        f(filename, flags)
495    } else {
496        null_mut()
497    }
498}
499
500#[no_mangle]
501pub unsafe extern "C" fn dlsym_impl(
502    handle: *mut c_void,
503    symbol: *const c_char,
504    ra: *mut c_void,
505) -> *mut c_void {
506    if let Some(f) = LDSO_DLSYM {
507        f(handle, symbol, ra)
508    } else {
509        null_mut()
510    }
511}
512
513// dlsym() must pass its own return address to the loader so that
514// RTLD_NEXT can identify the calling object.  Keep the public entry
515// point in assembly and tail-jump into the Rust implementation.
516#[no_mangle]
517#[unsafe(naked)]
518#[cfg(target_arch = "x86_64")]
519pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
520    core::arch::naked_asm!("mov rdx, [rsp]", "jmp dlsym_impl");
521}
522
523#[no_mangle]
524#[unsafe(naked)]
525#[cfg(target_arch = "aarch64")]
526pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
527    core::arch::naked_asm!("mov x2, x30", "b dlsym_impl");
528}
529
530#[no_mangle]
531#[unsafe(naked)]
532#[cfg(target_arch = "riscv64")]
533pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
534    core::arch::naked_asm!("mv a2, ra", "la t0, dlsym_impl", "jr t0");
535}
536
537#[no_mangle]
538#[unsafe(naked)]
539#[cfg(target_arch = "powerpc64")]
540pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
541    core::arch::naked_asm!(
542        "addis 2, 12, .TOC.-dlsym@ha",
543        "addi 2, 2, .TOC.-dlsym@l",
544        "mflr 5",
545        "b dlsym_impl",
546    );
547}
548
549#[no_mangle]
550#[unsafe(naked)]
551#[cfg(target_arch = "loongarch64")]
552pub unsafe extern "C" fn dlsym(_handle: *mut c_void, _symbol: *const c_char) -> *mut c_void {
553    core::arch::naked_asm!("move $a2, $ra", "b dlsym_impl");
554}
555
556#[no_mangle]
557pub unsafe extern "C" fn dlclose(handle: *mut c_void) -> c_int {
558    if let Some(f) = LDSO_DLCLOSE {
559        f(handle)
560    } else {
561        0
562    }
563}
564
565#[no_mangle]
566pub unsafe extern "C" fn dlerror() -> *const c_char {
567    if let Some(f) = LDSO_DLERROR {
568        f()
569    } else {
570        core::ptr::null()
571    }
572}
573