dldota 0.1.3

Load shared libraries from statically linked programs by bootstrapping the system's own dynamic loader
Documentation
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! i386: thread pointer access, the boot jump into `ld.so`, and the call
//! trampolines that switch the thread pointer at the boundary.
//!
//! The thread pointer is the base of the segment `%gs` selects: one of the
//! thread's three GDT TLS descriptors, each set with `set_thread_area`. The
//! host libc uses one; the foreign `ld.so` takes the next free one for the
//! bootstrap TCB, and foreign threads keep using that entry (new threads get
//! the entry number of the creating thread's `%gs`). So:
//! - switching to the host only reloads `%gs` with the host's selector,
//!   whose descriptor nothing else changes on a host thread;
//! - switching to a foreign TCB points the thread's own copy of the foreign
//!   descriptor at that TCB (`set_thread_area`), then reloads `%gs`.
//!
//! Every context uses the same foreign descriptor: before each boot, the
//! booting thread's other TLS descriptors are cleared, so `ld.so` always
//! picks the same free one.
//!
//! Arguments travel on the stack (cdecl), and the thunks pass their data in
//! eax/ecx/edx, which carry no arguments. Values come back in eax:edx or
//! st(0) (or xmm0), and a callee returning a struct pops its hidden pointer:
//! the trampolines keep all of that, and return relative to the stack
//! pointer the callee left.

use std::sync::atomic::{AtomicU32, Ordering};

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 = 6; // R_386_GLOB_DAT
pub(crate) const THUNK_SIZE: usize = 40;

/// `%gs` selector of the host's TLS descriptor (the same on every host thread).
static HOST_GS: AtomicU32 = AtomicU32::new(0);
/// `%gs` selector of the foreign TLS descriptor, once a context has booted.
static FOREIGN_GS: AtomicU32 = AtomicU32::new(0);
/// The selector the foreign `ld.so` picked during the last boot.
static BOOT_GS: AtomicU32 = AtomicU32::new(0);

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

/// Current thread pointer: glibc and musl both keep a self-pointer at
/// `%gs:0`.
#[inline(always)]
pub(crate) fn thread_pointer() -> usize {
    let tp: usize;
    // SAFETY: reads the TCB self-pointer, which every Linux i386 libc sets up.
    unsafe {
        core::arch::asm!("mov {}, dword ptr gs:[0]", out(reg) tp, options(nostack, readonly, preserves_flags))
    };
    tp
}

fn gs() -> u32 {
    let sel: u32;
    // SAFETY: reads a segment register.
    unsafe {
        core::arch::asm!("mov {:e}, gs", out(reg) sel, options(nomem, nostack, preserves_flags))
    };
    sel & 0xffff
}

/// Before booting `ld.so` on this thread: remember the host's selector and
/// free every other TLS descriptor, so `ld.so` gets the same one each time.
pub(crate) fn before_boot() {
    let host = gs();
    HOST_GS.store(host, Ordering::Relaxed);
    // Native kernels have TLS entries 6-8, 64-bit ones 12-14 for 32-bit tasks.
    let entries = match host >> 3 {
        6..=8 => 6..=8,
        _ => 12..=14,
    };
    for entry in entries.filter(|&e| e != host >> 3) {
        let _ = sys::set_thread_area(entry, None);
    }
}

/// After booting: check that `ld.so` used the foreign descriptor the
/// trampolines switch.
pub(crate) fn after_boot() -> Result<(), &'static str> {
    let booted = BOOT_GS.load(Ordering::Relaxed);
    match FOREIGN_GS.compare_exchange(0, booted, Ordering::Relaxed, Ordering::Relaxed) {
        Ok(_) => Ok(()),
        Err(known) if known == booted => Ok(()),
        Err(_) => Err("the foreign loader picked another TLS descriptor than the first context's"),
    }
}

unsafe extern "C" {
    fn __dldota_x86_boot(state: *mut crate::loader::BootState, entry: usize, sp: usize);
    fn __dldota_x86_entry();
    fn __dldota_x86_tramp_out();
    fn __dldota_x86_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_x86_boot(state, entry, sp) }
}

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

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

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

/// Write a thunk that loads `target` into ecx and `data` into edx, then
/// jumps to `tramp` through eax.
///
/// # 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 = [0xccu8; THUNK_SIZE]; // int3 padding
    code[0] = 0xb9; // mov ecx, target
    code[1..5].copy_from_slice(&target.to_le_bytes());
    code[5] = 0xba; // mov edx, data
    code[6..10].copy_from_slice(&data.to_le_bytes());
    code[10] = 0xb8; // mov eax, tramp
    code[11..15].copy_from_slice(&tramp.to_le_bytes());
    code[15..17].copy_from_slice(&[0xff, 0xe0]); // jmp eax
    // 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)`: copies four stack arguments below a new first one.
///
/// # 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 = [0xccu8; THUNK_SIZE];
    code[0..3].copy_from_slice(&[0x83, 0xec, 0x08]); // sub esp, 8 (keeps 16-byte alignment)
    for i in 0..4 {
        // push dword ptr [esp + 24]: a3, a2, a1, a0 in turn
        code[3 + 4 * i..7 + 4 * i].copy_from_slice(&[0xff, 0x74, 0x24, 0x18]);
    }
    code[19] = 0x68; // push data
    code[20..24].copy_from_slice(&data.to_le_bytes());
    code[24] = 0xb8; // mov eax, func
    code[25..29].copy_from_slice(&func.to_le_bytes());
    code[29..31].copy_from_slice(&[0xff, 0xd0]); // call eax
    code[31..34].copy_from_slice(&[0x83, 0xc4, 0x1c]); // add esp, 28
    code[34] = 0xc3; // ret
    // SAFETY: forwarded to the caller.
    unsafe { std::ptr::copy_nonoverlapping(code.as_ptr(), dst, THUNK_SIZE) };
}

/// x86 keeps instruction fetch coherent with stores: nothing to do.
pub(crate) fn flush_code(_rw: usize, _rx: usize, _len: usize) {}

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

// Load the run-time address of `$what` (a symbol or a label) into `$reg`,
// position-independently: the word after the call holds its distance. (LLVM's
// Intel syntax parser takes no symbol difference in an instruction operand.)
macro_rules! addr {
    ($reg:literal, $what:literal) => {
        concat!(
            "call 21f\n",
            ".long ",
            $what,
            " - .\n",
            "21:\n",
            "pop ",
            $reg,
            "\n",
            "add ",
            $reg,
            ", [",
            $reg,
            "]\n",
        )
    };
}

// Switch to the foreign TCB in eax: point the foreign TLS descriptor at it
// (a user_desc built at esp + $off), then reload gs. Clobbers eax, ebx, ecx.
macro_rules! set_foreign_tp {
    ($off:literal) => {
        concat!(
            "mov [esp + ",
            $off,
            " + 4], eax\n", // base_addr
            addr!("ecx", "{fgs}"),
            "mov ecx, [ecx]\n",
            "mov eax, ecx\n",
            "shr eax, 3\n",
            "mov [esp + ",
            $off,
            "], eax\n", // entry_number
            "mov dword ptr [esp + ",
            $off,
            " + 8], 0xfffff\n", // limit
            "mov dword ptr [esp + ",
            $off,
            " + 12], 0x51\n", // seg_32bit, limit_in_pages, useable
            "lea ebx, [esp + ",
            $off,
            "]\n",
            "mov eax, 243\n", // SYS_set_thread_area
            "int 0x80\n",
            "mov gs, cx\n",
        )
    };
}

// Switch to the host TCB. Clobbers ecx.
macro_rules! set_host_tp {
    () => {
        concat!(addr!("ecx", "{hgs}"), "mov ecx, [ecx]\n", "mov gs, cx\n",)
    };
}

// Save st(0) at esp + $off if the callee returned one, with a flag at
// esp + $flag. Clobbers ax.
macro_rules! save_st0 {
    ($off:literal, $flag:literal) => {
        concat!(
            "fxam\n",
            "fnstsw ax\n",
            "and ax, 0x4500\n",
            "cmp ax, 0x4100\n", // C3 C0: empty
            "je 24f\n",
            "fstp tbyte ptr [esp + ",
            $off,
            "]\n",
            "mov dword ptr [esp + ",
            $flag,
            "], 1\n",
            "jmp 25f\n",
            "24:\n",
            "mov dword ptr [esp + ",
            $flag,
            "], 0\n",
            "25:\n",
        )
    };
}
macro_rules! restore_st0 {
    ($off:literal, $flag:literal) => {
        concat!(
            "cmp dword ptr [esp + ",
            $flag,
            "], 0\n",
            "je 26f\n",
            "fld tbyte ptr [esp + ",
            $off,
            "]\n",
            "26:\n",
        )
    };
}

core::arch::global_asm!(
    ".pushsection .text.dldota_x86,\"ax\",@progbits",

    // void __dldota_x86_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_x86_boot",
    ".hidden __dldota_x86_boot",
    "__dldota_x86_boot:",
    "push ebp",
    "push ebx",
    "push esi",
    "push edi",
    "mov eax, [esp + 20]",      // state
    "mov ecx, [esp + 24]",      // entry
    "mov edx, [esp + 28]",      // sp
    "mov [eax], esp",           // state.host_sp
    "mov esp, edx",
    "xor edx, edx",             // no atexit function from the "kernel"
    "xor ebp, ebp",
    "jmp ecx",

    // The program entry ld.so jumps to (AT_ENTRY), shaped like crt1's _start:
    // esp -> argc, edx = ld.so's fini function. Calls the foreign
    // __libc_start_main, which initializes libc and calls our "main".
    ".p2align 4",
    ".globl __dldota_x86_entry",
    ".hidden __dldota_x86_entry",
    "__dldota_x86_entry:",
    addr!("eax", "{state}"),
    "mov eax, [eax]",
    "mov [eax + 16], edx",      // state.rtld_fini
    "xor ebp, ebp",
    "pop esi",                  // argc
    "mov ecx, esp",             // argv
    "and esp, -16",
    "push eax",                 // padding
    "push esp",                 // stack_end
    "push edx",                 // rtld_fini
    "push 0",                   // fini
    "push 0",                   // init
    "push ecx",                 // argv
    "push esi",                 // argc
    addr!("ecx", "34f"),
    "push ecx",                 // main
    "mov eax, [eax + 8]",       // state.start_main_slot
    "call [eax]",
    "ud2",
    // "main": the foreign libc is up. Record its thread pointer and
    // selector, restore the host's, and return from __dldota_x86_boot. This
    // frame stays on the boot stack, which the context keeps.
    "34:",
    addr!("eax", "{state}"),
    "mov eax, [eax]",
    "mov ecx, dword ptr gs:[0]",
    "mov [eax + 12], ecx",      // state.foreign_tp
    addr!("ebx", "{bgs}"),
    "mov cx, gs",
    "movzx ecx, cx",
    "mov [ebx], ecx",
    set_host_tp!(),
    "mov esp, [eax]",           // state.host_sp
    "pop edi",
    "pop esi",
    "pop ebx",
    "pop ebp",
    "ret",

    // Host -> foreign. Entered from a thunk: ecx = target, edx = gate,
    // [esp] = the host caller's return address, TP = host.
    // The return address is parked in a host-side frame stack and the call
    // re-issued from the same stack slot, so stack arguments stay in place.
    // The caller's ebx/esi are parked too: they hold the target and the
    // stack pointer across the call.
    ".p2align 4",
    ".globl __dldota_x86_tramp_out",
    ".hidden __dldota_x86_tramp_out",
    "__dldota_x86_tramp_out:",
    "mov eax, esp",
    "sub esp, 48",
    "and esp, -16",
    "mov [esp + 16], ecx",      // target
    "mov [esp + 20], eax",      // entry esp
    "mov [esp], edx",           // gate
    "mov ecx, [eax]",
    "mov [esp + 4], ecx",       // return address
    "mov [esp + 8], ebx",
    "mov [esp + 12], esi",
    "call {enter_foreign}",     // -> eax = foreign TP
    set_foreign_tp!("0"),
    "mov esi, [esp + 16]",
    "mov ebx, [esp + 20]",
    "lea esp, [ebx + 4]",       // drop the caller's return address
    "call esi",
    // esp is past the return slot, and past a struct pointer the callee
    // popped: return to the caller from there.
    "mov ebx, esp",
    "sub esp, 96",              // arg, out[3], eax, edx, flag, st(0), xmm0
    "and esp, -16",
    "mov [esp + 16], eax",
    "mov [esp + 20], edx",
    "movdqu [esp + 48], xmm0",
    save_st0!("32", "24"),
    set_host_tp!(),
    "lea eax, [esp + 4]",
    "mov [esp], eax",
    "call {leave_foreign}",     // out = [ret, ebx, esi]
    "mov ecx, [esp + 4]",
    "mov [ebx - 4], ecx",
    "mov ecx, [esp + 8]",
    "mov [ebx - 8], ecx",
    "mov ecx, [esp + 12]",
    "mov [ebx - 12], ecx",
    "mov ecx, [esp + 16]",
    "mov [ebx - 16], ecx",
    "mov ecx, [esp + 20]",
    "mov [ebx - 20], ecx",
    "movdqu xmm0, [esp + 48]",
    restore_st0!("32", "24"),
    "lea esp, [ebx - 20]",
    "pop edx",
    "pop eax",
    "pop esi",
    "pop ebx",
    "ret",

    // Foreign -> host (callbacks). Entered from a thunk: ecx = host function,
    // edx = gate, TP = foreign. The host thread to switch to is found as on
    // other architectures (the gate's thread-specific key, or the bootstrap
    // TCB's `cur_host_tp`); on i386 the switch itself only reloads gs.
    ".p2align 4",
    ".globl __dldota_x86_tramp_in",
    ".hidden __dldota_x86_tramp_in",
    "__dldota_x86_tramp_in:",
    "mov eax, esp",
    "sub esp, 64",
    "and esp, -16",
    "mov [esp + 32], ecx",      // host function
    "mov [esp + 36], eax",      // entry esp
    "mov [esp + 40], edx",      // gate
    "mov eax, dword ptr gs:[0]",
    "mov [esp + 44], eax",      // foreign TP
    "mov ecx, [edx + 8]",       // gate.getspecific
    "test ecx, ecx",
    "jz 38f",
    "mov eax, [edx + 12]",      // gate.key
    "mov [esp], eax",
    "call ecx",                 // -> eax = this thread's record
    "test eax, eax",
    "jz 39f",
    "jmp 37f",
    "38:",                      // no donors: only the bootstrap TCB has a host
    "cmp eax, [edx]",           // gate.boot_tp
    "jne 39f",
    "37:",
    set_host_tp!(),
    "mov eax, [esp + 40]",
    "mov [esp], eax",           // gate
    "mov eax, [esp + 36]",
    "mov eax, [eax]",
    "mov [esp + 4], eax",       // return address
    "mov [esp + 8], ebx",
    "mov [esp + 12], esi",
    "mov eax, [esp + 44]",
    "mov [esp + 16], eax",      // foreign TP
    "call {enter_host}",
    "mov esi, [esp + 32]",
    "mov ebx, [esp + 36]",
    "lea esp, [ebx + 4]",
    "call esi",
    "mov ebx, esp",
    "sub esp, 128",             // arg, out[4], eax, edx, flag, st(0), xmm0, esp, user_desc
    "and esp, -16",
    "mov [esp + 20], eax",
    "mov [esp + 24], edx",
    "movdqu [esp + 48], xmm0",
    save_st0!("32", "28"),
    "mov [esp + 64], ebx",
    "lea eax, [esp + 4]",
    "mov [esp], eax",
    "call {leave_host}",        // out = [ret, ebx, esi, foreign TP]
    "mov eax, [esp + 16]",
    set_foreign_tp!("80"),
    "mov ebx, [esp + 64]",
    "mov ecx, [esp + 4]",
    "mov [ebx - 4], ecx",
    "mov ecx, [esp + 8]",
    "mov [ebx - 8], ecx",
    "mov ecx, [esp + 12]",
    "mov [ebx - 12], ecx",
    "mov ecx, [esp + 20]",
    "mov [ebx - 16], ecx",
    "mov ecx, [esp + 24]",
    "mov [ebx - 20], ecx",
    "movdqu xmm0, [esp + 48]",
    restore_st0!("32", "28"),
    "lea esp, [ebx - 20]",
    "pop edx",
    "pop eax",
    "pop esi",
    "pop ebx",
    "ret",
    "39:",
    addr!("ecx", "46f"),
    addr!("edx", "47f"),
    "sub edx, ecx",
    "mov ebx, 2",
    "mov eax, 4",               // SYS_write
    "int 0x80",
    "ud2",
    "46:",
    ".ascii \"dldota: callback called on a thread that has no host thread (created by foreign code, or exiting)\\n\"",
    "47:",
    ".popsection",

    state = sym BOOT_STATE,
    hgs = sym HOST_GS,
    fgs = sym FOREIGN_GS,
    bgs = sym BOOT_GS,
    enter_foreign = sym gate::enter_foreign,
    leave_foreign = sym gate::leave_foreign,
    enter_host = sym gate::enter_host,
    leave_host = sym gate::leave_host,
);