dldota 0.1.3

Load shared libraries from statically linked programs by bootstrapping the system's own dynamic loader
Documentation
//! 32-bit ARM (EABI, hard-float): thread pointer access, the boot jump into
//! `ld.so`, and the call trampolines that switch the thread pointer.
//!
//! The thread pointer is TPIDRURO, which user space reads (`mrc`) but only
//! the kernel writes: every switch is a `set_tls` system call.
//!
//! The return address travels in lr, so the trampolines never touch the
//! caller's stack: they save r0-r3 and d0-d7 below sp, and call the target
//! with every argument register and stack argument as the caller left them.
//! The code is ARM (A32); foreign code is often Thumb-2, so every call and
//! return goes through an interworking branch (`blx`, `bx`, `ldr pc`).

use crate::gate;
use crate::loader::BOOT_STATE;
use crate::sys;

pub(crate) const BOOT_SUPPORTED: bool = true;
pub(crate) const R_GLOB_DAT: u32 = 21; // R_ARM_GLOB_DAT
pub(crate) const THUNK_SIZE: usize = 40;

pub(crate) fn init(_hwcap2: usize) {}

/// Current thread pointer (TPIDRURO).
#[inline(always)]
pub(crate) fn thread_pointer() -> usize {
    let tp: usize;
    // SAFETY: TPIDRURO is readable from user mode.
    unsafe {
        core::arch::asm!("mrc p15, 0, {}, c13, c0, 3", out(reg) tp, options(nomem, nostack, preserves_flags))
    };
    tp
}

/// Nothing to prepare before booting `ld.so` on this thread.
pub(crate) fn before_boot() {}

pub(crate) fn after_boot() -> Result<(), &'static str> {
    Ok(())
}

unsafe extern "C" {
    fn __dldota_arm_boot(state: *mut crate::loader::BootState, entry: usize, sp: usize);
    fn __dldota_arm_entry();
    fn __dldota_arm_tramp_out();
    fn __dldota_arm_tramp_in();
}

/// Jump into `ld.so` at `entry` with the initial stack `sp`; returns once the
/// foreign libc reached our `main`, with the host thread pointer restored.
///
/// # Safety
/// `entry` and `sp` must be a mapped loader and a stack built for it, and
/// `state` must be published in `BOOT_STATE` for the entry code.
pub(crate) unsafe fn boot(state: *mut crate::loader::BootState, entry: usize, sp: usize) {
    // SAFETY: forwarded to the caller.
    unsafe { __dldota_arm_boot(state, entry, sp) }
}

pub(crate) fn entry_address() -> usize {
    __dldota_arm_entry as *const () as usize
}

pub(crate) fn tramp_out_address() -> usize {
    __dldota_arm_tramp_out as *const () as usize
}

pub(crate) fn tramp_in_address() -> usize {
    __dldota_arm_tramp_in as *const () as usize
}

fn put(code: &mut [u8], at: usize, word: u32) {
    code[at..at + 4].copy_from_slice(&word.to_le_bytes());
}

/// Write a thunk that points r12 at its data `{target, data, tramp}` and
/// jumps to `tramp`. r12 (ip) is the intra-procedure-call scratch register,
/// which no argument travels in.
///
/// # Safety
/// `dst` must be writable for `THUNK_SIZE` bytes.
pub(crate) unsafe fn write_thunk(dst: *mut u8, target: usize, data: usize, tramp: usize) {
    let mut code = [0u8; THUNK_SIZE];
    put(&mut code, 0, 0xe28f_c000); // add r12, pc, #0 (-> 8)
    put(&mut code, 4, 0xe59c_f008); // ldr pc, [r12, #8]
    put(&mut code, 8, target as u32);
    put(&mut code, 12, data as u32);
    put(&mut code, 16, tramp as u32);
    put(&mut code, 20, 0xe7f0_00f0); // udf
    // SAFETY: forwarded to the caller.
    unsafe { std::ptr::copy_nonoverlapping(code.as_ptr(), dst, THUNK_SIZE) };
}

/// Write a thunk that calls `func(data, a0, a1, a2, a3)` for a C call `(a0,
/// a1, a2, a3)`: shifts r0-r2 up, passes a3 (r3) on the stack as the fifth
/// argument, and prepends `data`.
///
/// # Safety
/// `dst` must be writable for `THUNK_SIZE` bytes.
pub(crate) unsafe fn write_bind_thunk(dst: *mut u8, func: usize, data: usize) {
    let mut code = [0u8; THUNK_SIZE];
    put(&mut code, 0, 0xe92d_4008); // push {r3, lr}: a3 becomes [sp]
    put(&mut code, 4, 0xe1a0_3002); // mov r3, r2
    put(&mut code, 8, 0xe1a0_2001); // mov r2, r1
    put(&mut code, 12, 0xe1a0_1000); // mov r1, r0
    put(&mut code, 16, 0xe59f_0008); // ldr r0, [pc, #8] (-> 32)
    put(&mut code, 20, 0xe59f_c008); // ldr r12, [pc, #8] (-> 36)
    put(&mut code, 24, 0xe12f_ff3c); // blx r12
    put(&mut code, 28, 0xe8bd_8008); // pop {r3, pc}
    put(&mut code, 32, data as u32);
    put(&mut code, 36, func as u32);
    // SAFETY: forwarded to the caller.
    unsafe { std::ptr::copy_nonoverlapping(code.as_ptr(), dst, THUNK_SIZE) };
}

/// Make thunks written through the `rw` view executable from the `rx` view.
pub(crate) fn flush_code(rw: usize, rx: usize, len: usize) {
    sys::cacheflush(rw, rw + len);
    sys::cacheflush(rx, rx + len);
}

/// Crash immediately, without touching std or any libc.
pub(crate) fn trap() -> ! {
    // SAFETY: raises SIGILL.
    unsafe { core::arch::asm!("udf #0", options(noreturn, nomem, nostack)) }
}

// Set the thread pointer to r0 (`set_tls`), keeping r7 in $tmp. Clobbers r0.
macro_rules! set_tp_r0 {
    ($tmp:literal) => {
        concat!(
            "mov ",
            $tmp,
            ", r7\n",
            "movw r7, #5\n",
            "movt r7, #15\n", // __ARM_NR_set_tls = 0xf0005
            "svc #0\n",
            "mov r7, ",
            $tmp,
            "\n",
        )
    };
}

// r4 = the BootState of the boot in progress, position-independently.
macro_rules! load_state {
    () => {
        concat!(
            "ldr r4, 21f\n",
            "22:\n",
            "add r4, pc, r4\n",
            "ldr r4, [r4]\n",
            "b 23f\n",
            "21:\n",
            ".word {state} - (22b + 8)\n",
            "23:\n",
        )
    };
}

core::arch::global_asm!(
    ".pushsection .text.dldota_arm,\"ax\",%progbits",
    ".arm",

    // void __dldota_arm_boot(BootState *state, entry, sp)
    // Saves the host's callee-saved registers and stack in `state`, then
    // enters ld.so exactly as the kernel would.
    ".p2align 4",
    ".globl __dldota_arm_boot",
    ".hidden __dldota_arm_boot",
    ".type __dldota_arm_boot, %function",
    "__dldota_arm_boot:",
    "push {{r4-r12, lr}}",
    "vpush {{d8-d15}}",
    "str sp, [r0]",             // state.host_sp
    "mov sp, r2",
    "mov r0, #0",
    "mov r11, #0",
    "mov lr, #0",
    "bx r1",

    // The program entry ld.so jumps to (AT_ENTRY), shaped like crt1's _start:
    // sp -> argc, r0 = ld.so's fini function (glibc). Calls the foreign
    // __libc_start_main, which initializes libc and calls our "main".
    ".p2align 4",
    ".globl __dldota_arm_entry",
    ".hidden __dldota_arm_entry",
    ".type __dldota_arm_entry, %function",
    "__dldota_arm_entry:",
    load_state!(),
    "str r0, [r4, #16]",        // state.rtld_fini
    "mov r11, #0",
    "mov lr, #0",
    "pop {{r1}}",               // argc
    "mov r2, sp",               // argv
    "push {{r2}}",              // stack_end
    "push {{r0}}",              // rtld_fini
    "mov r3, #0",
    "push {{r3}}",              // fini
    "adr r0, 34f",              // main
    "ldr r12, [r4, #8]",        // state.start_main_slot
    "ldr r12, [r12]",
    "blx r12",
    "udf #0",
    // "main": the foreign libc is up. Record its thread pointer, restore the
    // host's, and return from __dldota_arm_boot. This frame stays on the
    // boot stack, which the context keeps.
    ".p2align 2",
    "34:",
    load_state!(),
    "mrc p15, 0, r1, c13, c0, 3",
    "str r1, [r4, #12]",        // state.foreign_tp
    "ldr r0, [r4, #4]",         // state.host_tp
    set_tp_r0!("r5"),
    "ldr sp, [r4]",             // state.host_sp
    "vpop {{d8-d15}}",
    "pop {{r4-r12, lr}}",
    "bx lr",

    // Host -> foreign. Entered from a thunk: r12 -> {target, gate}, lr =
    // the host caller's return address, TP = host. The return address and
    // the caller's r4/r5 are parked in a host-side frame stack; r4 carries
    // the host TP across the call.
    ".p2align 4",
    ".globl __dldota_arm_tramp_out",
    ".hidden __dldota_arm_tramp_out",
    ".type __dldota_arm_tramp_out, %function",
    "__dldota_arm_tramp_out:",
    "push {{r0-r3}}",
    "vpush {{d0-d7}}",
    "push {{r12, lr}}",
    "ldr r0, [r12, #4]",        // gate
    "mov r1, lr",               // return address
    "mov r2, r4",
    "mov r3, r5",
    "bl {enter_foreign}",       // -> r0 = foreign TP
    "mrc p15, 0, r4, c13, c0, 3", // host TP
    set_tp_r0!("r5"),
    "pop {{r12, lr}}",
    "vpop {{d0-d7}}",
    "pop {{r0-r3}}",
    "ldr r12, [r12]",           // target
    "blx r12",
    "push {{r0-r3}}",
    "vpush {{d0-d7}}",
    "sub sp, sp, #16",          // out[3] + padding
    "mov r0, r4",
    set_tp_r0!("r5"),
    "mov r0, sp",
    "bl {leave_foreign}",       // out = [ret, r4, r5]
    "ldr lr, [sp]",
    "ldr r4, [sp, #4]",
    "ldr r5, [sp, #8]",
    "add sp, sp, #16",
    "vpop {{d0-d7}}",
    "pop {{r0-r3}}",
    "bx lr",

    // Foreign -> host (callbacks). Entered from a thunk: r12 -> {host
    // function, gate}, TP = foreign. The host thread pointer to switch to is
    // the first word of the record the foreign thread holds under the gate's
    // thread-specific key: a donor's, or the gate's `cur_host_tp` for the
    // bootstrap TCB. Threads created by foreign code have none.
    ".p2align 4",
    ".globl __dldota_arm_tramp_in",
    ".hidden __dldota_arm_tramp_in",
    ".type __dldota_arm_tramp_in, %function",
    "__dldota_arm_tramp_in:",
    "push {{r0-r3}}",
    "vpush {{d0-d7}}",
    "push {{r12, lr}}",
    "sub sp, sp, #8",           // [sp] = foreign TP, [sp + 4] = r7
    "mrc p15, 0, r0, c13, c0, 3",
    "str r0, [sp]",
    "ldr r1, [r12, #4]",        // gate
    "ldr r2, [r1, #8]",         // gate.getspecific
    "cmp r2, #0",
    "beq 38f",
    "ldr r0, [r1, #12]",        // gate.key
    "blx r2",                   // -> r0 = this thread's record
    "cmp r0, #0",
    "beq 39f",
    "b 37f",
    "38:",                      // no donors: only the bootstrap TCB has a host
    "ldr r3, [r1]",             // gate.boot_tp
    "cmp r0, r3",
    "bne 39f",
    "add r0, r1, #4",           // gate.cur_host_tp
    "37:",
    "ldr r0, [r0]",             // host TP
    "str r7, [sp, #4]",
    "movw r7, #5",
    "movt r7, #15",
    "svc #0",
    "ldr r7, [sp, #4]",
    "ldr r12, [sp, #8]",        // thunk data
    "ldr r0, [r12, #4]",        // gate
    "ldr r1, [sp, #12]",        // return address
    "mov r2, r4",
    "mov r3, r5",
    "ldr r4, [sp]",             // foreign TP: the fifth argument
    "sub sp, sp, #8",
    "str r4, [sp]",
    "bl {enter_host}",
    "add sp, sp, #16",
    "pop {{r12, lr}}",
    "vpop {{d0-d7}}",
    "pop {{r0-r3}}",
    "ldr r12, [r12]",           // host function
    "blx r12",
    "push {{r0-r3}}",
    "vpush {{d0-d7}}",
    "sub sp, sp, #16",          // out[4]
    "mov r0, sp",
    "bl {leave_host}",          // out = [ret, r4, r5, foreign TP]
    "ldr r0, [sp, #12]",
    set_tp_r0!("r5"),
    "ldr lr, [sp]",
    "ldr r4, [sp, #4]",
    "ldr r5, [sp, #8]",
    "add sp, sp, #16",
    "vpop {{d0-d7}}",
    "pop {{r0-r3}}",
    "bx lr",
    "39:",
    "mov r0, #2",
    "adr r1, 46f",
    "adr r2, 47f",
    "sub r2, r2, r1",
    "mov r7, #4",               // SYS_write
    "svc #0",
    "udf #0",
    "46:",
    ".ascii \"dldota: callback called on a thread that has no host thread (created by foreign code, or exiting)\\n\"",
    "47:",
    ".p2align 2",
    ".popsection",

    state = sym BOOT_STATE,
    enter_foreign = sym gate::enter_foreign,
    leave_foreign = sym gate::leave_foreign,
    enter_host = sym gate::enter_host,
    leave_host = sym gate::leave_host,
);