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
//! Raw Linux system calls. The loader can't rely on the host's libc: under
//! fullrust there is none, and a static libc may not wrap what we need.

use std::ffi::CStr;
use std::io;

#[cfg(target_arch = "x86_64")]
mod nr {
    pub const WRITE: usize = 1;
    pub const CLOSE: usize = 3;
    pub const MMAP: usize = 9;
    pub const MPROTECT: usize = 10;
    pub const MUNMAP: usize = 11;
    pub const RT_SIGPROCMASK: usize = 14;
    pub const FTRUNCATE: usize = 77;
    pub const PRCTL: usize = 157;
    pub const SET_TID_ADDRESS: usize = 218;
    pub const SET_ROBUST_LIST: usize = 273;
    pub const GET_ROBUST_LIST: usize = 274;
    pub const GETRANDOM: usize = 318;
    pub const MEMFD_CREATE: usize = 319;
    pub const FUTEX: usize = 202;
    pub const GETPID: usize = 39;
    pub const GETTID: usize = 186;
    pub const TGKILL: usize = 234;
    pub const RT_SIGACTION: usize = 13;
    pub const BRK: usize = 12;
}

#[cfg(target_arch = "aarch64")]
mod nr {
    pub const WRITE: usize = 64;
    pub const CLOSE: usize = 57;
    pub const MMAP: usize = 222;
    pub const MPROTECT: usize = 226;
    pub const MUNMAP: usize = 215;
    pub const RT_SIGPROCMASK: usize = 135;
    pub const FTRUNCATE: usize = 46;
    pub const PRCTL: usize = 167;
    pub const SET_TID_ADDRESS: usize = 96;
    pub const SET_ROBUST_LIST: usize = 99;
    pub const GET_ROBUST_LIST: usize = 100;
    pub const GETRANDOM: usize = 278;
    pub const MEMFD_CREATE: usize = 279;
    pub const FUTEX: usize = 98;
    pub const GETPID: usize = 172;
    pub const GETTID: usize = 178;
    pub const TGKILL: usize = 131;
    pub const RT_SIGACTION: usize = 134;
    pub const BRK: usize = 214;
}

#[cfg(target_arch = "x86")]
mod nr {
    pub const WRITE: usize = 4;
    pub const CLOSE: usize = 6;
    pub const MMAP: usize = 192; // mmap2: offset in 4 KiB units
    pub const MPROTECT: usize = 125;
    pub const MUNMAP: usize = 91;
    pub const RT_SIGPROCMASK: usize = 175;
    pub const FTRUNCATE: usize = 93;
    pub const PRCTL: usize = 172;
    pub const SET_TID_ADDRESS: usize = 258;
    pub const SET_ROBUST_LIST: usize = 311;
    pub const GET_ROBUST_LIST: usize = 312;
    pub const GETRANDOM: usize = 355;
    pub const MEMFD_CREATE: usize = 356;
    pub const FUTEX: usize = 240;
    pub const GETPID: usize = 20;
    pub const GETTID: usize = 224;
    pub const TGKILL: usize = 270;
    pub const RT_SIGACTION: usize = 174;
    pub const BRK: usize = 45;
    pub const SET_THREAD_AREA: usize = 243;
}

#[cfg(target_arch = "arm")]
mod nr {
    pub const WRITE: usize = 4;
    pub const CLOSE: usize = 6;
    pub const MMAP: usize = 192; // mmap2: offset in 4 KiB units
    pub const MPROTECT: usize = 125;
    pub const MUNMAP: usize = 91;
    pub const RT_SIGPROCMASK: usize = 175;
    pub const FTRUNCATE: usize = 93;
    pub const PRCTL: usize = 172;
    pub const SET_TID_ADDRESS: usize = 256;
    pub const SET_ROBUST_LIST: usize = 338;
    pub const GET_ROBUST_LIST: usize = 339;
    pub const GETRANDOM: usize = 384;
    pub const MEMFD_CREATE: usize = 385;
    pub const FUTEX: usize = 240;
    pub const GETPID: usize = 20;
    pub const GETTID: usize = 224;
    pub const TGKILL: usize = 268;
    pub const RT_SIGACTION: usize = 174;
    pub const BRK: usize = 45;
    pub const CACHEFLUSH: usize = 0xf0002; // __ARM_NR_cacheflush
}

pub(crate) const PROT_NONE: usize = 0;
pub(crate) const PROT_READ: usize = 1;
pub(crate) const PROT_WRITE: usize = 2;
pub(crate) const PROT_EXEC: usize = 4;
pub(crate) const MAP_SHARED: usize = 0x01;
pub(crate) const MAP_PRIVATE: usize = 0x02;
pub(crate) const MAP_FIXED: usize = 0x10;
pub(crate) const MAP_ANONYMOUS: usize = 0x20;
pub(crate) const MAP_FIXED_NOREPLACE: usize = 0x10_0000;
pub(crate) const SIG_SETMASK: usize = 2;
const MFD_CLOEXEC: usize = 1;
const PR_GET_TID_ADDRESS: usize = 40;

#[cfg(target_arch = "x86_64")]
unsafe fn raw(n: usize, a: [usize; 6]) -> isize {
    let ret: isize;
    // SAFETY: the caller upholds the contract of syscall `n`.
    unsafe {
        core::arch::asm!(
            "syscall",
            inlateout("rax") n as isize => ret,
            in("rdi") a[0], in("rsi") a[1], in("rdx") a[2],
            in("r10") a[3], in("r8") a[4], in("r9") a[5],
            lateout("rcx") _, lateout("r11") _,
            options(nostack),
        )
    };
    ret
}

#[cfg(target_arch = "aarch64")]
unsafe fn raw(n: usize, a: [usize; 6]) -> isize {
    let ret: isize;
    // SAFETY: the caller upholds the contract of syscall `n`.
    unsafe {
        core::arch::asm!(
            "svc 0",
            in("x8") n,
            inlateout("x0") a[0] as isize => ret,
            in("x1") a[1], in("x2") a[2], in("x3") a[3], in("x4") a[4], in("x5") a[5],
            options(nostack),
        )
    };
    ret
}

/// i386: `int 0x80` with arguments in ebx, ecx, edx, esi, edi, ebp. LLVM
/// reserves esi and ebp, so those are loaded from memory around the call.
#[cfg(target_arch = "x86")]
unsafe fn raw(n: usize, a: [usize; 6]) -> isize {
    let ret: isize;
    let rest = [a[3], a[4], a[5]];
    // SAFETY: the caller upholds the contract of syscall `n`.
    unsafe {
        core::arch::asm!(
            "push ebp",
            "push esi",
            "mov esi, [edi]",
            "mov ebp, [edi + 8]",
            "mov edi, [edi + 4]",
            "int 0x80",
            "pop esi",
            "pop ebp",
            inlateout("eax") n as isize => ret,
            in("ebx") a[0], in("ecx") a[1], in("edx") a[2],
            inout("edi") rest.as_ptr() => _,
        )
    };
    ret
}

/// ARM EABI: `svc 0` with the number in r7.
#[cfg(target_arch = "arm")]
unsafe fn raw(n: usize, a: [usize; 6]) -> isize {
    let ret: isize;
    // SAFETY: the caller upholds the contract of syscall `n`.
    unsafe {
        core::arch::asm!(
            "svc 0",
            in("r7") n,
            inlateout("r0") a[0] as isize => ret,
            in("r1") a[1], in("r2") a[2], in("r3") a[3], in("r4") a[4], in("r5") a[5],
        )
    };
    ret
}

unsafe fn syscall(n: usize, args: [usize; 6]) -> io::Result<usize> {
    // SAFETY: forwarded to the caller.
    let ret = unsafe { raw(n, args) };
    if (-4095..0).contains(&ret) {
        Err(io::Error::from_raw_os_error(-ret as i32))
    } else {
        Ok(ret as usize)
    }
}

/// # Safety
/// With `MAP_FIXED`, `addr..addr+len` must not hold anything still in use.
pub(crate) unsafe fn mmap(
    addr: usize,
    len: usize,
    prot: usize,
    flags: usize,
    fd: i32,
    off: usize,
) -> io::Result<usize> {
    // 32-bit targets only have mmap2, which takes the offset in 4 KiB units.
    let off = if cfg!(target_pointer_width = "32") {
        off / 4096
    } else {
        off
    };
    // SAFETY: forwarded to the caller.
    unsafe {
        syscall(
            nr::MMAP,
            [addr, len, prot, flags, fd as isize as usize, off],
        )
    }
}

/// # Safety
/// Nothing may use the range afterwards.
pub(crate) unsafe fn munmap(addr: usize, len: usize) -> io::Result<()> {
    // SAFETY: forwarded to the caller.
    unsafe { syscall(nr::MUNMAP, [addr, len, 0, 0, 0, 0]) }.map(drop)
}

/// # Safety
/// Nothing may rely on the old protection of the range.
pub(crate) unsafe fn mprotect(addr: usize, len: usize, prot: usize) -> io::Result<()> {
    // SAFETY: forwarded to the caller.
    unsafe { syscall(nr::MPROTECT, [addr, len, prot, 0, 0, 0]) }.map(drop)
}

pub(crate) fn memfd_create(name: &CStr) -> io::Result<i32> {
    // SAFETY: `name` is a valid C string.
    unsafe {
        syscall(
            nr::MEMFD_CREATE,
            [name.as_ptr() as usize, MFD_CLOEXEC, 0, 0, 0, 0],
        )
    }
    .map(|fd| fd as i32)
}

pub(crate) fn ftruncate(fd: i32, len: usize) -> io::Result<()> {
    // SAFETY: plain fd operation.
    unsafe { syscall(nr::FTRUNCATE, [fd as usize, len, 0, 0, 0, 0]) }.map(drop)
}

pub(crate) fn write(fd: i32, buf: &[u8]) -> io::Result<usize> {
    // SAFETY: reads within `buf`.
    unsafe {
        syscall(
            nr::WRITE,
            [fd as usize, buf.as_ptr() as usize, buf.len(), 0, 0, 0],
        )
    }
}

pub(crate) fn close(fd: i32) -> io::Result<()> {
    // SAFETY: the caller owns `fd`.
    unsafe { syscall(nr::CLOSE, [fd as usize, 0, 0, 0, 0, 0]) }.map(drop)
}

/// Set the signal mask, returning the previous one.
pub(crate) fn sigprocmask_set(mask: u64) -> io::Result<u64> {
    let mut old = 0u64;
    // SAFETY: both pointers are valid 8-byte sigsets.
    unsafe {
        syscall(
            nr::RT_SIGPROCMASK,
            [
                SIG_SETMASK,
                &mask as *const u64 as usize,
                &mut old as *mut u64 as usize,
                8,
                0,
                0,
            ],
        )
    }?;
    Ok(old)
}

/// The calling thread's `clear_child_tid` address, if the kernel exposes it.
pub(crate) fn get_tid_address() -> Option<usize> {
    let mut addr = 0usize;
    // SAFETY: the kernel writes one pointer to `addr`.
    unsafe {
        syscall(
            nr::PRCTL,
            [
                PR_GET_TID_ADDRESS,
                &mut addr as *mut usize as usize,
                0,
                0,
                0,
                0,
            ],
        )
    }
    .ok()
    .map(|_| addr)
}

/// # Safety
/// `addr` must be what the thread's runtime expects the kernel to clear.
pub(crate) unsafe fn set_tid_address(addr: usize) {
    // SAFETY: forwarded to the caller; it cannot fail.
    let _ = unsafe { syscall(nr::SET_TID_ADDRESS, [addr, 0, 0, 0, 0, 0]) };
}

/// The calling thread's robust futex list: `(head, len)`.
pub(crate) fn get_robust_list() -> Option<(usize, usize)> {
    let (mut head, mut len) = (0usize, 0usize);
    // SAFETY: the kernel writes one pointer and one length.
    unsafe {
        syscall(
            nr::GET_ROBUST_LIST,
            [
                0,
                &mut head as *mut usize as usize,
                &mut len as *mut usize as usize,
                0,
                0,
                0,
            ],
        )
    }
    .ok()
    .map(|_| (head, len))
}

/// # Safety
/// `head` must be the list the thread's runtime registered.
pub(crate) unsafe fn set_robust_list(head: usize, len: usize) {
    // SAFETY: forwarded to the caller.
    let _ = unsafe { syscall(nr::SET_ROBUST_LIST, [head, len, 0, 0, 0, 0]) };
}

pub(crate) fn getrandom(buf: &mut [u8]) -> io::Result<()> {
    let mut filled = 0;
    while filled < buf.len() {
        // SAFETY: writes within `buf`.
        filled += unsafe {
            syscall(
                nr::GETRANDOM,
                [
                    buf[filled..].as_mut_ptr() as usize,
                    buf.len() - filled,
                    0,
                    0,
                    0,
                    0,
                ],
            )
        }?;
    }
    Ok(())
}

const FUTEX_WAIT_PRIVATE: usize = 128;
const FUTEX_WAKE_PRIVATE: usize = 129;

/// Sleep while `*word == expected` (spurious wakeups possible).
pub(crate) fn futex_wait(word: &core::sync::atomic::AtomicU32, expected: u32) {
    // SAFETY: `word` is a live, aligned u32.
    let _ = unsafe {
        syscall(
            nr::FUTEX,
            [
                word.as_ptr() as usize,
                FUTEX_WAIT_PRIVATE,
                expected as usize,
                0,
                0,
                0,
            ],
        )
    };
}

pub(crate) fn futex_wake(word: &core::sync::atomic::AtomicU32, n: u32) {
    // SAFETY: `word` is a live, aligned u32.
    let _ = unsafe {
        syscall(
            nr::FUTEX,
            [
                word.as_ptr() as usize,
                FUTEX_WAKE_PRIVATE,
                n as usize,
                0,
                0,
                0,
            ],
        )
    };
}

pub(crate) fn gettid() -> i32 {
    // SAFETY: no arguments, cannot fail.
    unsafe { syscall(nr::GETTID, [0; 6]) }.map_or(0, |t| t as i32)
}

/// Whether thread `tid` of this process still exists.
pub(crate) fn thread_alive(tid: i32) -> bool {
    const ESRCH: i32 = 3;
    // SAFETY: signal 0 only checks for existence.
    let pid = unsafe { syscall(nr::GETPID, [0; 6]) }.unwrap_or(0);
    // SAFETY: as above.
    let r = unsafe { syscall(nr::TGKILL, [pid, tid as usize, 0, 0, 0, 0]) };
    !matches!(r, Err(e) if e.raw_os_error() == Some(ESRCH))
}

/// The kernel's `struct sigaction` for `rt_sigaction` (every supported
/// architecture has `sa_restorer`; the mask is two words on 32-bit ones).
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(crate) struct KSigaction {
    pub handler: usize,
    pub flags: usize,
    pub restorer: usize,
    pub mask: [usize; 8 / size_of::<usize>()],
}

pub(crate) fn sigaction_get(sig: usize) -> Option<KSigaction> {
    let mut old = KSigaction::default();
    // SAFETY: the kernel writes one struct to `old`.
    unsafe {
        syscall(
            nr::RT_SIGACTION,
            [sig, 0, &mut old as *mut KSigaction as usize, 8, 0, 0],
        )
    }
    .ok()
    .map(|_| old)
}

/// # Safety
/// Installs `act` as the process-wide disposition of `sig`.
pub(crate) unsafe fn sigaction_set(sig: usize, act: &KSigaction) {
    // SAFETY: forwarded to the caller.
    let _ = unsafe {
        syscall(
            nr::RT_SIGACTION,
            [sig, act as *const KSigaction as usize, 0, 8, 0, 0],
        )
    };
}

/// The current program break.
pub(crate) fn current_brk() -> usize {
    // SAFETY: brk(0) only queries.
    unsafe { syscall(nr::BRK, [0; 6]) }.unwrap_or(0)
}

/// i386: install `base` as the TLS descriptor `entry` of the calling thread
/// (`set_thread_area`). An `entry` of `u32::MAX` lets the kernel pick a free
/// one; returns the entry used. `base == None` clears the entry.
#[cfg(target_arch = "x86")]
pub(crate) fn set_thread_area(entry: u32, base: Option<usize>) -> io::Result<u32> {
    // struct user_desc: entry_number, base_addr, limit, then flag bits
    // seg_32bit(0) contents(1-2) read_exec_only(3) limit_in_pages(4)
    // seg_not_present(5) useable(6).
    let mut desc: [u32; 4] = match base {
        Some(base) => [entry, base as u32, 0xfffff, 0x51],
        None => [entry, 0, 0, 0x28],
    };
    // SAFETY: the kernel reads and updates one user_desc.
    unsafe {
        syscall(
            nr::SET_THREAD_AREA,
            [desc.as_mut_ptr() as usize, 0, 0, 0, 0, 0],
        )
    }?;
    Ok(desc[0])
}

/// ARM: make freshly written code at `start..end` visible to instruction
/// fetch (`cacheflush`).
#[cfg(target_arch = "arm")]
pub(crate) fn cacheflush(start: usize, end: usize) {
    // SAFETY: only maintains caches over our own mapping.
    let _ = unsafe { syscall(nr::CACHEFLUSH, [start, end, 0, 0, 0, 0]) };
}