dldota 0.1.3

Load shared libraries from statically linked programs by bootstrapping the system's own dynamic loader
Documentation
//! aarch64: thread pointer access (`tpidr_el0`), the boot jump into `ld.so`,
//! and the call trampolines that switch the thread pointer at the boundary.
//!
//! The return address travels in x30, so unlike x86 the trampolines never
//! touch the caller's stack: they save what they need below sp and call the
//! target with every argument register (x0-x8, q0-q7) and stack argument
//! as the caller left them.

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

pub(crate) const BOOT_SUPPORTED: bool = true;
pub(crate) const R_GLOB_DAT: u32 = 1025; // R_AARCH64_GLOB_DAT
pub(crate) const THUNK_SIZE: usize = 48;

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

/// Current thread pointer (`tpidr_el0`).
#[inline(always)]
pub(crate) fn thread_pointer() -> usize {
    let tp: usize;
    // SAFETY: tpidr_el0 is always readable from EL0.
    unsafe {
        core::arch::asm!("mrs {}, tpidr_el0", out(reg) tp, options(nomem, nostack, preserves_flags))
    };
    tp
}

unsafe extern "C" {
    fn __dldota_aarch64_boot(state: *mut crate::loader::BootState, entry: usize, sp: usize);
    fn __dldota_aarch64_entry();
    fn __dldota_aarch64_tramp_out();
    fn __dldota_aarch64_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_aarch64_boot(state, entry, sp) }
}

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

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

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

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

/// Write a thunk that points x17 at its data `{target, data}` and jumps to
/// `tramp`. x16/x17 are the intra-procedure-call scratch registers, 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, 0x1000_0091); // adr x17, #16
    put(&mut code, 4, 0xf940_0a30); // ldr x16, [x17, #16]
    put(&mut code, 8, 0xd61f_0200); // br x16
    put(&mut code, 12, 0xd420_0000); // brk #0
    code[16..24].copy_from_slice(&target.to_le_bytes());
    code[24..32].copy_from_slice(&data.to_le_bytes());
    code[32..40].copy_from_slice(&tramp.to_le_bytes());
    // 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 up to four integer arguments 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, 0xaa03_03e4); // mov x4, x3
    put(&mut code, 4, 0xaa02_03e3); // mov x3, x2
    put(&mut code, 8, 0xaa01_03e2); // mov x2, x1
    put(&mut code, 12, 0xaa00_03e1); // mov x1, x0
    put(&mut code, 16, 0x5800_0080); // ldr x0, #16 (-> 32)
    put(&mut code, 20, 0x5800_00b0); // ldr x16, #20 (-> 40)
    put(&mut code, 24, 0xd61f_0200); // br x16
    put(&mut code, 28, 0xd420_0000); // brk #0
    code[32..40].copy_from_slice(&data.to_le_bytes());
    code[40..48].copy_from_slice(&func.to_le_bytes());
    // 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) {
    const LINE: usize = 4; // safe lower bound; real lines are larger
    let ctr: usize;
    // SAFETY: ctr_el0 is readable from EL0 on Linux.
    unsafe { core::arch::asm!("mrs {}, ctr_el0", out(reg) ctr, options(nomem, nostack)) };
    let dline = (LINE << ((ctr >> 16) & 0xf)).max(LINE);
    let iline = (LINE << (ctr & 0xf)).max(LINE);
    // SAFETY: cache maintenance on our own mappings.
    unsafe {
        let mut a = rw & !(dline - 1);
        while a < rw + len {
            core::arch::asm!("dc cvau, {}", in(reg) a, options(nostack));
            a += dline;
        }
        core::arch::asm!("dsb ish", options(nostack));
        let mut a = rx & !(iline - 1);
        while a < rx + len {
            core::arch::asm!("ic ivau, {}", in(reg) a, options(nostack));
            a += iline;
        }
        core::arch::asm!("dsb ish", "isb", options(nostack));
    }
}

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

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

/// 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)) }
}

// Save/restore the argument registers x0-x8, x17 (thunk data) and q0-q7 in
// a 224-byte area at sp; x30 goes at sp + 80.
macro_rules! save_args {
    () => {
        concat!(
            "stp x0, x1, [sp]\n",
            "stp x2, x3, [sp, #16]\n",
            "stp x4, x5, [sp, #32]\n",
            "stp x6, x7, [sp, #48]\n",
            "stp x8, x17, [sp, #64]\n",
            "str x30, [sp, #80]\n",
            "stp q0, q1, [sp, #96]\n",
            "stp q2, q3, [sp, #128]\n",
            "stp q4, q5, [sp, #160]\n",
            "stp q6, q7, [sp, #192]\n",
        )
    };
}
macro_rules! restore_args {
    () => {
        concat!(
            "ldp x0, x1, [sp]\n",
            "ldp x2, x3, [sp, #16]\n",
            "ldp x4, x5, [sp, #32]\n",
            "ldp x6, x7, [sp, #48]\n",
            "ldp x8, x17, [sp, #64]\n",
            "ldp q0, q1, [sp, #96]\n",
            "ldp q2, q3, [sp, #128]\n",
            "ldp q4, q5, [sp, #160]\n",
            "ldp q6, q7, [sp, #192]\n",
        )
    };
}
// Save/restore the return registers x0-x7 and q0-q3 at sp + 32 (sp..sp+32
// is the 3/4-word `out` area of leave_*).
macro_rules! save_ret {
    () => {
        concat!(
            "stp x0, x1, [sp, #32]\n",
            "stp x2, x3, [sp, #48]\n",
            "stp x4, x5, [sp, #64]\n",
            "stp x6, x7, [sp, #80]\n",
            "stp q0, q1, [sp, #96]\n",
            "stp q2, q3, [sp, #128]\n",
        )
    };
}
macro_rules! restore_ret {
    () => {
        concat!(
            "ldp x0, x1, [sp, #32]\n",
            "ldp x2, x3, [sp, #48]\n",
            "ldp x4, x5, [sp, #64]\n",
            "ldp x6, x7, [sp, #80]\n",
            "ldp q0, q1, [sp, #96]\n",
            "ldp q2, q3, [sp, #128]\n",
        )
    };
}

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

    // void __dldota_aarch64_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_aarch64_boot",
    ".hidden __dldota_aarch64_boot",
    "__dldota_aarch64_boot:",
    "stp x29, x30, [sp, #-160]!",
    "mov x29, sp",
    "stp x19, x20, [sp, #16]",
    "stp x21, x22, [sp, #32]",
    "stp x23, x24, [sp, #48]",
    "stp x25, x26, [sp, #64]",
    "stp x27, x28, [sp, #80]",
    "stp d8, d9, [sp, #96]",
    "stp d10, d11, [sp, #112]",
    "stp d12, d13, [sp, #128]",
    "stp d14, d15, [sp, #144]",
    "mov x9, sp",
    "str x9, [x0]",             // state.host_sp
    "mov sp, x2",
    "mov x0, #0",
    "mov x29, #0",
    "mov x30, #0",
    "br x1",

    // The program entry ld.so jumps to (AT_ENTRY), shaped like crt1's _start:
    // sp -> argc, x0 = ld.so's fini function (glibc). Calls the foreign
    // __libc_start_main, which initializes libc and calls our "main".
    ".p2align 4",
    ".globl __dldota_aarch64_entry",
    ".hidden __dldota_aarch64_entry",
    "__dldota_aarch64_entry:",
    "adrp x9, {state}",
    "ldr x9, [x9, :lo12:{state}]",
    "str x0, [x9, #32]",        // state.rtld_fini
    "mov x5, x0",               // rtld_fini
    "ldr x1, [sp]",             // argc
    "add x2, sp, #8",           // argv
    "mov x6, sp",               // stack_end
    "mov x3, #0",               // init
    "mov x4, #0",               // fini
    "adr x0, 4f",               // main
    "ldr x9, [x9, #16]",        // state.start_main_slot
    "ldr x9, [x9]",
    "mov x29, #0",
    "mov x30, #0",
    "blr x9",
    "udf #0",
    // "main": the foreign libc is up. Record its thread pointer, restore the
    // host's, and return from __dldota_aarch64_boot. This frame stays on the
    // boot stack, which the context keeps.
    "4:",
    "adrp x9, {state}",
    "ldr x9, [x9, :lo12:{state}]",
    "mrs x10, tpidr_el0",
    "str x10, [x9, #24]",       // state.foreign_tp
    "ldr x10, [x9, #8]",        // state.host_tp
    "msr tpidr_el0, x10",
    "ldr x10, [x9]",            // state.host_sp
    "mov sp, x10",
    "ldp x19, x20, [sp, #16]",
    "ldp x21, x22, [sp, #32]",
    "ldp x23, x24, [sp, #48]",
    "ldp x25, x26, [sp, #64]",
    "ldp x27, x28, [sp, #80]",
    "ldp d8, d9, [sp, #96]",
    "ldp d10, d11, [sp, #112]",
    "ldp d12, d13, [sp, #128]",
    "ldp d14, d15, [sp, #144]",
    "ldp x29, x30, [sp], #160",
    "ret",

    // Host -> foreign. Entered from a thunk: x17 -> {target, gate}, x30 =
    // the host caller's return address, TP = host. The return address and
    // the caller's x19/x20 are parked in a host-side frame stack; x19
    // carries the host TP across the call.
    ".p2align 4",
    ".globl __dldota_aarch64_tramp_out",
    ".hidden __dldota_aarch64_tramp_out",
    "__dldota_aarch64_tramp_out:",
    "sub sp, sp, #224",
    save_args!(),
    "ldr x0, [x17, #8]",        // gate
    "mov x1, x30",              // return address
    "mov x2, x19",
    "mov x3, x20",
    "bl {enter_foreign}",       // -> x0 = foreign TP
    "mrs x19, tpidr_el0",       // host TP
    "msr tpidr_el0, x0",
    restore_args!(),
    "ldr x16, [x17]",           // target
    "add sp, sp, #224",
    "blr x16",
    "sub sp, sp, #160",         // out[3], x0-x7, q0-q3
    save_ret!(),
    "msr tpidr_el0, x19",
    "mov x0, sp",
    "bl {leave_foreign}",       // out = [ret, x19, x20]
    "ldp x30, x19, [sp]",
    "ldr x20, [sp, #16]",
    restore_ret!(),
    "add sp, sp, #160",
    "ret",

    // Foreign -> host (callbacks). Entered from a thunk: x17 -> {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_aarch64_tramp_in",
    ".hidden __dldota_aarch64_tramp_in",
    "__dldota_aarch64_tramp_in:",
    "sub sp, sp, #240",         // save area + foreign TP + padding
    save_args!(),
    "mrs x0, tpidr_el0",
    "str x0, [sp, #224]",
    "ldr x1, [x17, #8]",        // gate
    "ldr x2, [x1, #16]",        // gate.getspecific
    "cbz x2, 8f",
    "ldr w0, [x1, #24]",        // gate.key
    "blr x2",                   // -> x0 = this thread's record
    "cbz x0, 5f",
    "b 9f",
    "8:",                       // no donors: only the bootstrap TCB has a host
    "ldr x3, [x1]",             // gate.boot_tp
    "cmp x0, x3",
    "b.ne 5f",
    "add x0, x1, #8",           // gate.cur_host_tp
    "9:",
    "ldr x0, [x0]",             // host TP
    "msr tpidr_el0, x0",
    "ldr x17, [sp, #72]",       // thunk data
    "ldr x0, [x17, #8]",        // gate
    "ldr x1, [sp, #80]",        // return address
    "mov x2, x19",
    "mov x3, x20",
    "ldr x4, [sp, #224]",       // foreign TP
    "bl {enter_host}",
    restore_args!(),
    "ldr x16, [x17]",           // host function
    "add sp, sp, #240",
    "blr x16",
    "sub sp, sp, #160",         // out[4], x0-x7, q0-q3
    save_ret!(),
    "mov x0, sp",
    "bl {leave_host}",          // out = [ret, x19, x20, foreign TP]
    "ldr x0, [sp, #24]",
    "msr tpidr_el0, x0",
    "ldp x30, x19, [sp]",
    "ldr x20, [sp, #16]",
    restore_ret!(),
    "add sp, sp, #160",
    "ret",
    "5:",
    "mov x0, #2",
    "adr x1, 6f",
    "adr x2, 7f",
    "sub x2, x2, x1",
    "mov x8, #64",              // SYS_write
    "svc #0",
    "udf #0",
    "6:",
    ".ascii \"dldota: callback called on a thread that has no host thread (created by foreign code, or exiting)\\n\"",
    "7:",
    ".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,
);