sel4_ctors_dtors/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//
// Copyright 2024, Colias Group, LLC
//
// SPDX-License-Identifier: BSD-2-Clause
//

// See:
// - https://github.com/ARM-software/abi-aa/blob/main/sysvabi64/sysvabi64.rst
// - https://maskray.me/blog/2021-11-07-init-ctors-init-array

#![no_std]
#![feature(linkage)]

use core::mem;
use core::ptr;
use core::slice;

type ArrayEntry = unsafe extern "C" fn();

extern "C" {
    static __preinit_array_start: ArrayEntry;
    static __preinit_array_end: ArrayEntry;
    static __init_array_start: ArrayEntry;
    static __init_array_end: ArrayEntry;
    static __fini_array_start: ArrayEntry;
    static __fini_array_end: ArrayEntry;

    fn _init();
    fn _fini();
}

mod _weak {
    #[linkage = "weak"]
    #[no_mangle]
    extern "C" fn _init() {}

    #[linkage = "weak"]
    #[no_mangle]
    extern "C" fn _fini() {}
}

unsafe fn run_array(start_addr: usize, end_addr: usize, section_name: &str) {
    if start_addr != end_addr {
        if start_addr % mem::size_of::<ArrayEntry>() != 0
            || end_addr % mem::size_of::<ArrayEntry>() != 0
        {
            panic!("{section_name:?} section is not properly aligned");
        }

        let len = (end_addr - start_addr) / mem::size_of::<ArrayEntry>();
        let array = slice::from_raw_parts(start_addr as *const ArrayEntry, len);
        for entry in array {
            (entry)();
        }
    }
}

fn run_preinit_array() {
    unsafe {
        run_array(
            ptr::addr_of!(__preinit_array_start) as usize,
            ptr::addr_of!(__preinit_array_end) as usize,
            ".preinit_array",
        )
    }
}

fn run_init_array() {
    unsafe {
        run_array(
            ptr::addr_of!(__init_array_start) as usize,
            ptr::addr_of!(__init_array_end) as usize,
            ".init_array",
        )
    }
}

fn run_fini_array() {
    unsafe {
        run_array(
            ptr::addr_of!(__fini_array_start) as usize,
            ptr::addr_of!(__fini_array_end) as usize,
            ".fini_array",
        )
    }
}

fn run_init() {
    unsafe { _init() }
}

fn run_fini() {
    unsafe { _fini() }
}

pub fn run_ctors() {
    run_preinit_array();
    run_init();
    run_init_array();
}

pub fn run_dtors() {
    run_fini_array();
    run_fini();
}