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
//! Unloading a context: run the foreign world's destructors, then unmap it.
use std::ffi::c_void;
use std::time::{Duration, Instant};
use crate::context::Inner;
use crate::error::{Error, Result};
use crate::loader::{self, Flavor, LoadedObject};
use crate::sys;
/// How long unload waits for threads that may be about to disappear.
const JOIN_GRACE: Duration = Duration::from_millis(100);
const DT_NULL: usize = 0;
const DT_FINI: usize = 13;
const DT_FINI_ARRAY: usize = 26;
const DT_FINI_ARRAYSZ: usize = 28;
impl Inner {
/// # Safety
/// No `Library`, `Symbol` or `Callback` of this context may be used
/// afterwards, on success.
pub(crate) unsafe fn unload(&self) -> Result<()> {
self.gate.acquire();
// SAFETY: forwarded.
let r = unsafe { self.teardown() };
if r.is_err() {
self.gate.reopen();
}
self.gate.release();
r
}
/// Call the foreign function `f(arg)` from the host.
fn call_foreign(&self, f: usize, arg: usize) -> Result<()> {
let thunk = self
.thunks
.lock()
.unwrap_or_else(|e| e.into_inner())
.outbound(self.gate, f)?;
// SAFETY: a foreign `void (*)(void *)` (or `void (*)(void)`, which
// ignores the argument), through a thunk that switches the TP.
unsafe { std::mem::transmute::<usize, unsafe extern "C" fn(usize)>(thunk)(arg) };
Ok(())
}
unsafe fn teardown(&self) -> Result<()> {
// A thread that foreign code just joined can still exist for a moment:
// `pthread_join` returns when the kernel clears its tid, slightly
// before the task is gone.
let mut live = self.rt.live_threads();
let deadline = Instant::now() + JOIN_GRACE;
while live > 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(1));
live = self.rt.live_threads();
}
if live > 0 {
return Err(Error::Busy(format!(
"{live} thread(s) created by foreign code still running"
)));
}
// The host threads' foreign threads exit first, running their
// thread-local destructors. From here on this thread's foreign calls
// run on the bootstrap TCB, like a main thread's exit handlers.
if let Err(stuck) = self.gate.close_threads() {
return Err(Error::Busy(format!(
"{stuck} foreign thread(s) of host threads did not exit"
)));
}
let booted = &self.booted;
debug!("unloading");
if let Some(fflush) = self.fflush {
// SAFETY: fflush(NULL) flushes every foreign stream.
unsafe { fflush(std::ptr::null_mut::<c_void>()) };
}
while let Some((func, arg)) = self.rt.pop_exit(None) {
self.call_foreign(func, arg)?;
}
// SAFETY: still loaded; finalizers below don't unmap anything.
let objects = unsafe { loader::loaded_objects(booted) };
match booted.flavor {
// ld.so's _dl_fini runs every object's finalizers in dependency order.
Flavor::Glibc if booted.rtld_fini != 0 => self.call_foreign(booted.rtld_fini, 0)?,
Flavor::Glibc => {}
// musl only runs finalizers from exit(): run them ourselves.
Flavor::Musl => {
for obj in objects.iter().rev() {
// SAFETY: the object is still mapped and was initialized.
unsafe { self.run_finalizers(obj)? };
}
}
}
let spans: Vec<(usize, usize)> = objects
.iter()
.filter_map(|o| o.span)
.chain(booted.regions.iter().copied())
.collect();
restore_signals(&booted.signals, &spans);
// SAFETY: nothing runs foreign code anymore: no live foreign threads,
// and the Context is being consumed.
unsafe {
for &(start, len) in &spans {
let _ = sys::munmap(start, len);
}
let thunks = self.thunks.lock().unwrap_or_else(|e| e.into_inner());
for (start, len) in thunks.regions() {
let _ = sys::munmap(start, len);
}
}
self.rt.heap.release_all();
debug!("unloaded {} objects", objects.len());
if crate::debug_enabled() {
let now = loader::anon_mappings();
for &(start, end) in &booted.boot_anon {
if now.iter().any(|&(s, e)| s < end && start < e) {
debug!(
"still mapped after unload: {start:#x}-{end:#x} ({} KiB)",
(end - start) / 1024
);
}
}
}
Ok(())
}
/// Run an object's `DT_FINI_ARRAY` (in reverse) and `DT_FINI`.
unsafe fn run_finalizers(&self, obj: &LoadedObject) -> Result<()> {
let (mut fini, mut array, mut array_size) = (0, 0, 0);
let mut dynamic = obj.dynamic as *const usize;
// SAFETY: the object's dynamic section, terminated by DT_NULL.
unsafe {
while *dynamic != DT_NULL {
match *dynamic {
DT_FINI => fini = *dynamic.add(1),
DT_FINI_ARRAY => array = *dynamic.add(1),
DT_FINI_ARRAYSZ => array_size = *dynamic.add(1),
_ => {}
}
dynamic = dynamic.add(2);
}
}
if array != 0 {
let entries = (obj.base + array) as *const usize;
for i in (0..array_size / size_of::<usize>()).rev() {
// SAFETY: within the relocated fini array.
let f = unsafe { *entries.add(i) };
if f != 0 && f != usize::MAX {
self.call_foreign(f, 0)?;
}
}
}
if fini != 0 {
self.call_foreign(obj.base + fini, 0)?;
}
Ok(())
}
}
/// Put back the pre-boot disposition of every signal whose handler lies in
/// memory about to be unmapped.
fn restore_signals(saved: &[Option<sys::KSigaction>], spans: &[(usize, usize)]) {
for (sig, old) in saved.iter().enumerate() {
let (Some(old), Some(cur)) = (old, sys::sigaction_get(sig)) else {
continue;
};
if spans
.iter()
.any(|&(start, len)| (start..start + len).contains(&cur.handler))
{
debug!("restoring handler of signal {sig}");
// SAFETY: reinstating what the process had before boot.
unsafe { sys::sigaction_set(sig, old) };
}
}
}