dldota 0.1.2

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
use std::ffi::{CStr, CString, c_char, c_int, c_void};
use std::marker::PhantomData;
use std::ops::Deref;
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use std::ptr::NonNull;
use std::sync::Mutex;

use crate::error::{Error, Result};
use crate::gate::{Gate, PthreadFns};
use crate::heap::{self, HeapUsage};
use crate::loader;
use crate::runtime::{self, Runtime};
use crate::thunk::Thunks;

type DlOpen = unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void;
type DlSym = unsafe extern "C" fn(*mut c_void, *const c_char) -> *mut c_void;
type DlClose = unsafe extern "C" fn(*mut c_void) -> c_int;
type DlError = unsafe extern "C" fn() -> *const c_char;

/// `dlopen` mode flags. The values are identical in glibc and musl.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OpenFlags(pub i32);

impl OpenFlags {
    pub const LAZY: Self = Self(0x1);
    pub const NOW: Self = Self(0x2);
    pub const NOLOAD: Self = Self(0x4);
    pub const LOCAL: Self = Self(0x0);
    pub const GLOBAL: Self = Self(0x100);
    pub const NODELETE: Self = Self(0x1000);
}

impl std::ops::BitOr for OpenFlags {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

#[derive(Default)]
pub struct ContextBuilder {
    interpreter: Option<PathBuf>,
    env: Option<Vec<CString>>,
}

impl ContextBuilder {
    /// Use this dynamic loader instead of auto-detecting the system one.
    pub fn interpreter(mut self, path: impl Into<PathBuf>) -> Self {
        self.interpreter = Some(path.into());
        self
    }

    /// Environment seen by the foreign loader and libc (`KEY=VALUE` entries).
    /// Defaults to the current process environment. `LD_LIBRARY_PATH`,
    /// `LD_PRELOAD` and `GLIBC_TUNABLES` set here only affect this context.
    pub fn env(mut self, env: impl IntoIterator<Item = CString>) -> Self {
        self.env = Some(env.into_iter().collect());
        self
    }

    /// Map and boot the system dynamic loader.
    pub fn build(self) -> Result<Context> {
        let interpreter = match self.interpreter {
            Some(path) => path,
            None => loader::find_interpreter()?,
        };
        let env = self.env.unwrap_or_else(|| {
            std::env::vars_os()
                .filter_map(|(k, v)| {
                    let mut kv = k.as_bytes().to_vec();
                    kv.push(b'=');
                    kv.extend_from_slice(v.as_bytes());
                    CString::new(kv).ok()
                })
                .collect()
        });
        // Leaked: thunks and foreign code hold pointers to the gate and the
        // heap, and the foreign world outlives a dropped Context (see `unload`).
        let gate: &'static Gate = Box::leak(Box::new(Gate::new()));
        let rt: &'static Runtime = Box::leak(Box::new(Runtime::new(loader::page_size())));
        let mut thunks = Thunks::default();
        let heap_data = &rt.heap as *const _ as usize;
        let rt_data = rt as *const Runtime as usize;
        let defs = heap::exports()
            .into_iter()
            .map(|(name, func)| (name, func, heap_data))
            .chain(
                runtime::exports()
                    .into_iter()
                    .map(|(name, func)| (name, func, rt_data)),
            )
            .map(|(name, func, data)| Ok((name, thunks.bound(func, data)?)))
            .collect::<Result<Vec<_>>>()?;

        let booted = loader::boot(&interpreter, env, &defs)?;
        gate.boot_tp
            .store(booted.foreign_tp, std::sync::atomic::Ordering::Release);
        rt.heap.set_errno_location(booted.errno_location);

        let mut wrap = |target: usize| thunks.outbound(gate, target);
        // SAFETY: each thunk forwards to the function of that signature.
        let inner = unsafe {
            Inner {
                dlopen: std::mem::transmute::<usize, DlOpen>(wrap(booted.dlopen)?),
                dlsym: std::mem::transmute::<usize, DlSym>(wrap(booted.dlsym)?),
                dlclose: std::mem::transmute::<usize, DlClose>(wrap(booted.dlclose)?),
                dlerror: std::mem::transmute::<usize, DlError>(wrap(booted.dlerror)?),
                gate,
                rt,
                thunks: Mutex::new(thunks),
                fflush: None,
                booted,
            }
        };
        let mut inner = inner;
        inner.resolve_libc();
        Ok(Context {
            inner: Box::leak(Box::new(inner)),
        })
    }
}

/// A booted foreign dynamic loader, with its own libc and heap.
///
/// Call [`Context::unload`] to tear it down. Dropping a `Context` without
/// unloading leaks the foreign world rather than risk unmapping code that a
/// foreign thread is still running.
pub struct Context {
    inner: &'static Inner,
}

pub(crate) struct Inner {
    pub(crate) gate: &'static Gate,
    pub(crate) rt: &'static Runtime,
    pub(crate) thunks: Mutex<Thunks>,
    dlopen: DlOpen,
    dlsym: DlSym,
    dlclose: DlClose,
    dlerror: DlError,
    /// The foreign `fflush`, through an outbound thunk.
    pub(crate) fflush: Option<unsafe extern "C" fn(*mut c_void) -> c_int>,
    pub(crate) booted: loader::Booted,
}

impl Inner {
    /// Look up libc functions the runtime needs: the real `pthread_create`
    /// (called raw, from foreign code), `fflush` (for unload), and what the
    /// gate needs to give each host thread a foreign thread.
    fn resolve_libc(&mut self) {
        let mut pthread = PthreadFns::default();
        // glibc < 2.34 keeps pthread_create in libpthread; musl answers both.
        for lib in [c"libc.so.6", c"libpthread.so.0"] {
            // SAFETY: valid C strings; NOLOAD only finds loaded objects.
            let handle =
                unsafe { (self.dlopen)(lib.as_ptr(), OpenFlags::LAZY.0 | OpenFlags::NOLOAD.0) };
            if handle.is_null() {
                continue;
            }
            // SAFETY: a live handle and valid C strings.
            unsafe {
                let create = (self.dlsym)(handle, c"pthread_create".as_ptr());
                if !create.is_null() {
                    self.rt.set_pthread_create(create as usize);
                }
                for (slot, name) in [
                    (&mut pthread.create, c"pthread_create"),
                    (&mut pthread.join, c"pthread_join"),
                    (&mut pthread.key_create, c"pthread_key_create"),
                    (&mut pthread.setspecific, c"pthread_setspecific"),
                    (&mut pthread.getspecific, c"pthread_getspecific"),
                ] {
                    if *slot == 0 {
                        *slot = (self.dlsym)(handle, name.as_ptr()) as usize;
                    }
                }
                let fflush = (self.dlsym)(handle, c"fflush".as_ptr());
                if self.fflush.is_none() && !fflush.is_null() {
                    let mut thunks = self.thunks.lock().unwrap_or_else(|e| e.into_inner());
                    if let Ok(t) = thunks.outbound(self.gate, fflush as usize) {
                        self.fflush = Some(std::mem::transmute::<
                            usize,
                            unsafe extern "C" fn(*mut c_void) -> c_int,
                        >(t));
                    }
                }
                (self.dlclose)(handle);
            }
        }
        let mut thunks = self.thunks.lock().unwrap_or_else(|e| e.into_inner());
        self.gate
            .enable_threads(&pthread, |f| thunks.outbound(self.gate, f));
    }

    /// The foreign `dlerror()` text. Call inside `Gate::with`, right after
    /// the failing call, so no other thread's error replaces it.
    fn last_error(&self, fallback: &str) -> Error {
        // SAFETY: dlerror returns NULL or a NUL-terminated string.
        let msg = unsafe { (self.dlerror)() };
        if msg.is_null() {
            Error::Dl(fallback.to_owned())
        } else {
            // SAFETY: checked non-NULL above.
            Error::Dl(
                unsafe { CStr::from_ptr(msg) }
                    .to_string_lossy()
                    .into_owned(),
            )
        }
    }
}

impl Context {
    /// Boot the auto-detected system loader with the current environment.
    pub fn new() -> Result<Self> {
        Self::builder().build()
    }

    pub fn builder() -> ContextBuilder {
        ContextBuilder::default()
    }

    /// `dlopen` through the foreign loader.
    pub fn open(&self, name: &CStr, flags: OpenFlags) -> Result<Library<'_>> {
        let handle = self.open_raw(Some(name), flags)?;
        Ok(Library { ctx: self, handle })
    }

    /// Tear down the foreign world: run library destructors and exit handlers,
    /// then unmap every object, the loader, and the foreign heap.
    ///
    /// Fails with [`Error::Busy`] while threads created by foreign code are
    /// still alive; the context is handed back intact.
    pub fn unload(self) -> std::result::Result<(), (Self, Error)> {
        // SAFETY: consuming `self` ends every Library/Symbol/Callback borrow.
        if let Err(e) = unsafe { self.inner.unload() } {
            return Err((self, e));
        }
        // SAFETY: these were leaked in `build` and nothing refers to them now.
        unsafe {
            let inner = Box::from_raw(self.inner as *const Inner as *mut Inner);
            drop(Box::from_raw(inner.gate as *const Gate as *mut Gate));
            drop(Box::from_raw(inner.rt as *const Runtime as *mut Runtime));
        }
        Ok(())
    }

    /// Current usage of the foreign heap. Every allocation made by foreign
    /// code, including libc-internal ones, goes through the context's allocator.
    pub fn heap_usage(&self) -> HeapUsage {
        self.inner.rt.heap.usage()
    }

    /// The foreign global scope (`dlopen(NULL)`): the system libc and anything
    /// opened with [`OpenFlags::GLOBAL`]. Use it to reach libc functions
    /// without knowing the libc's file name, which differs between glibc and musl.
    pub fn global(&self) -> Result<Library<'_>> {
        let handle = self.open_raw(None, OpenFlags::LAZY)?;
        Ok(Library { ctx: self, handle })
    }

    /// Wrap a host function so foreign code can call it, e.g. as a `qsort`
    /// comparator. The returned pointer switches the thread pointer back to the
    /// host for the duration of the call; it is valid while the
    /// [`Callback`] lives.
    ///
    /// # Safety
    /// `F` must be an `extern "C" fn` pointer type.
    pub unsafe fn callback<F: Copy>(&self, f: F) -> Result<Callback<'_, F>> {
        const { assert!(size_of::<F>() == size_of::<*mut c_void>()) };
        // SAFETY: size checked above; F is a function pointer per the contract.
        let raw = unsafe { std::mem::transmute_copy::<F, NonNull<c_void>>(&f) };
        let thunk = self.callback_raw(raw)?;
        // SAFETY: the thunk has the same ABI and signature as `f`.
        let thunk_fn = unsafe { std::mem::transmute_copy::<NonNull<c_void>, F>(&thunk) };
        Ok(Callback {
            ctx: self,
            thunk,
            thunk_fn,
        })
    }

    /// Create a callback thunk for the raw host function `f`.
    pub fn callback_raw(&self, f: NonNull<c_void>) -> Result<NonNull<c_void>> {
        let mut thunks = self.inner.thunks.lock().unwrap_or_else(|e| e.into_inner());
        let thunk = thunks.inbound(self.inner.gate, f.as_ptr() as usize)?;
        Ok(NonNull::new(thunk as *mut c_void).expect("thunk address"))
    }

    /// Wrap a foreign function that was not looked up by name, so the host can
    /// call it: one that foreign code returned at run time
    /// (`vkGetInstanceProcAddr`, `eglGetProcAddress`) or stored in a struct or
    /// vtable. The returned pointer switches the thread pointer around the
    /// call, like a [`Library::symbol`] result. It stays valid until the
    /// context is unloaded; using it once the library that owns `f` is closed
    /// is undefined behaviour.
    ///
    /// A pointer that already switches the thread pointer (from
    /// [`Library::symbol`] or this method) is returned unchanged.
    ///
    /// # Safety
    /// `F` must be a function pointer type, and `f` a function in foreign
    /// code with that signature.
    pub unsafe fn foreign<F: Copy>(&self, f: F) -> Result<F> {
        const { assert!(size_of::<F>() == size_of::<*mut c_void>()) };
        // SAFETY: size checked above; F is a function pointer per the contract.
        let raw = unsafe { std::mem::transmute_copy::<F, NonNull<c_void>>(&f) };
        let thunk = self.foreign_raw(raw)?;
        // SAFETY: the thunk has the same ABI and signature as `f`.
        Ok(unsafe { std::mem::transmute_copy::<NonNull<c_void>, F>(&thunk) })
    }

    /// Create (or reuse) the outbound thunk for the foreign code address
    /// `f`: the counterpart of [`Context::callback_raw`]. See
    /// [`Context::foreign`].
    pub fn foreign_raw(&self, f: NonNull<c_void>) -> Result<NonNull<c_void>> {
        let mut thunks = self.inner.thunks.lock().unwrap_or_else(|e| e.into_inner());
        if thunks.contains(f.as_ptr() as usize) {
            return Ok(f);
        }
        let thunk = thunks.outbound(self.inner.gate, f.as_ptr() as usize)?;
        Ok(NonNull::new(thunk as *mut c_void).expect("thunk address"))
    }

    /// Release a thunk created by [`Context::callback_raw`].
    pub fn free_callback_raw(&self, thunk: NonNull<c_void>) {
        let _ = thunk;
    }

    /// `dlopen` returning the raw foreign handle; `None` opens the global scope.
    pub fn open_raw(&self, name: Option<&CStr>, flags: OpenFlags) -> Result<NonNull<c_void>> {
        let name_ptr = name.map_or(std::ptr::null(), CStr::as_ptr);
        self.inner.gate.with(|| {
            // SAFETY: NULL or a valid C string.
            let handle = unsafe { (self.inner.dlopen)(name_ptr, flags.0) };
            NonNull::new(handle).ok_or_else(|| self.inner.last_error("dlopen failed"))
        })
    }

    /// `dlsym` on a raw foreign handle. The returned pointer is a trampoline
    /// that switches the thread pointer around the call.
    pub fn symbol_raw(&self, handle: NonNull<c_void>, name: &CStr) -> Result<NonNull<c_void>> {
        let target = self.inner.gate.with(|| {
            // SAFETY: a handle from dlopen and a valid C string.
            let sym = unsafe { (self.inner.dlsym)(handle.as_ptr(), name.as_ptr()) };
            NonNull::new(sym).ok_or_else(|| self.inner.last_error("dlsym failed"))
        })?;
        let mut thunks = self.inner.thunks.lock().unwrap_or_else(|e| e.into_inner());
        let thunk = thunks.outbound(self.inner.gate, target.as_ptr() as usize)?;
        Ok(NonNull::new(thunk as *mut c_void).expect("thunk address"))
    }

    /// `dlclose` on a raw foreign handle.
    pub fn close_raw(&self, handle: NonNull<c_void>) -> Result<()> {
        self.inner.gate.with(|| {
            // SAFETY: a handle from dlopen, closed once.
            match unsafe { (self.inner.dlclose)(handle.as_ptr()) } {
                0 => Ok(()),
                _ => Err(self.inner.last_error("dlclose failed")),
            }
        })
    }
}

/// A library opened through a [`Context`]; `dlclose`d on drop.
pub struct Library<'ctx> {
    ctx: &'ctx Context,
    handle: NonNull<c_void>,
}

// SAFETY: a dlopen handle is an opaque identifier; the foreign dlsym/dlclose
// it is passed to are thread-safe.
unsafe impl Send for Library<'_> {}
unsafe impl Sync for Library<'_> {}

impl<'ctx> Library<'ctx> {
    /// Look up `name` and reinterpret it as `T`, typically an
    /// `unsafe extern "C" fn` type.
    ///
    /// # Safety
    /// `T` must be pointer-sized and match the symbol's real type.
    pub unsafe fn symbol<T: Copy>(&self, name: &CStr) -> Result<Symbol<'_, T>> {
        const { assert!(size_of::<T>() == size_of::<*mut c_void>()) };
        let ptr = self.ctx.symbol_raw(self.handle, name)?;
        // SAFETY: size checked above; type correctness is the caller's contract.
        let value = unsafe { std::mem::transmute_copy::<NonNull<c_void>, T>(&ptr) };
        Ok(Symbol {
            value,
            _lib: PhantomData,
        })
    }

    pub fn as_raw(&self) -> NonNull<c_void> {
        self.handle
    }
}

impl Drop for Library<'_> {
    fn drop(&mut self) {
        let _ = self.ctx.close_raw(self.handle);
    }
}

/// A symbol borrowed from a [`Library`]; cannot outlive it.
pub struct Symbol<'lib, T> {
    value: T,
    _lib: PhantomData<&'lib ()>,
}

impl<T> Deref for Symbol<'_, T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.value
    }
}

/// A host function made callable from foreign code by [`Context::callback`].
/// Derefs to the thunk, to be passed to foreign code.
pub struct Callback<'ctx, F> {
    ctx: &'ctx Context,
    thunk: NonNull<c_void>,
    thunk_fn: F,
}

impl<F> Deref for Callback<'_, F> {
    type Target = F;
    fn deref(&self) -> &F {
        &self.thunk_fn
    }
}

impl<F> Drop for Callback<'_, F> {
    fn drop(&mut self) {
        self.ctx.free_callback_raw(self.thunk);
    }
}

// SAFETY: the thunk is immutable code owned by the context.
unsafe impl<F: Send> Send for Callback<'_, F> {}
unsafe impl<F: Sync> Sync for Callback<'_, F> {}