1use std::collections::HashMap;
11use std::os::fd::RawFd;
12use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
14use std::sync::{Arc, OnceLock, RwLock};
15
16use crate::host;
17
18static SYSCALL_COUNT: AtomicU64 = AtomicU64::new(0);
20static MAX_SYSCALLS: AtomicU64 = AtomicU64::new(256);
22
23const FD_SLOTS: usize = 1024;
25const FD_EMPTY: i32 = -1;
27
28static FD_HOST: [AtomicI32; FD_SLOTS] = [const { AtomicI32::new(FD_EMPTY) }; FD_SLOTS];
33static FD_NEXT: AtomicI32 = AtomicI32::new(3);
35
36#[derive(Clone, Copy, Debug)]
38pub(crate) struct SoftSigAct {
39 pub handler: u64,
40 pub mask: u32,
41 pub flags: i32,
42}
43
44#[derive(Clone, Copy, Debug, Default)]
48#[allow(dead_code)]
49pub(crate) struct BsdThreadReg {
50 pub threadstart: u64,
52 pub wqthread: u64,
54 pub flags: u32,
56 pub stack_addr_hint: u64,
58 pub tsd_offset: u32,
60 pub dispatchqueue_offset: u32,
62}
63
64impl SoftSigAct {
65 pub(crate) const fn zero() -> Self {
66 Self {
67 handler: 0,
68 mask: 0,
69 flags: 0,
70 }
71 }
72}
73
74#[derive(Debug, Default)]
76struct FdTable;
77
78impl FdTable {
79 const fn new() -> Self {
80 Self
81 }
82
83 fn reset(&mut self) {
84 let _ = self;
85 reset_fd_map();
86 }
87}
88
89#[must_use]
91#[inline]
92pub fn fd_get(gfd: i32) -> Option<RawFd> {
93 if gfd == 0 || gfd == 1 || gfd == 2 {
94 return Some(gfd);
95 }
96 if gfd < 0 {
97 return None;
98 }
99 let Ok(idx) = usize::try_from(gfd) else {
100 return None;
101 };
102 let slot = FD_HOST.get(idx)?;
103 let v = slot.load(Ordering::Acquire);
104 if v < 0 { None } else { Some(v) }
105}
106
107#[must_use]
109#[inline]
110pub fn fd_take(gfd: i32) -> Option<RawFd> {
111 if gfd <= 2 {
112 return None;
113 }
114 let Ok(idx) = usize::try_from(gfd) else {
115 return None;
116 };
117 let slot = FD_HOST.get(idx)?;
118 let v = slot.swap(FD_EMPTY, Ordering::AcqRel);
119 if v < 0 { None } else { Some(v) }
120}
121
122#[must_use]
124#[inline]
125pub fn fd_alloc(host_fd: RawFd) -> Option<i32> {
126 if host_fd < 0 {
127 return None;
128 }
129 let start = usize::try_from(FD_NEXT.load(Ordering::Relaxed).max(3)).unwrap_or(3);
130 for idx in start..FD_SLOTS {
131 if try_claim_slot(idx, host_fd) {
132 let gfd = i32::try_from(idx).ok()?;
133 FD_NEXT.store(gfd.saturating_add(1), Ordering::Relaxed);
134 return Some(gfd);
135 }
136 }
137 for idx in 3..start.min(FD_SLOTS) {
138 if try_claim_slot(idx, host_fd) {
139 let gfd = i32::try_from(idx).ok()?;
140 FD_NEXT.store(gfd.saturating_add(1), Ordering::Relaxed);
141 return Some(gfd);
142 }
143 }
144 None
145}
146
147static BOTTLE_ROOT: RwLock<Option<Arc<PathBuf>>> = RwLock::new(None);
149
150static BOTTLE_DIRFD: AtomicI32 = AtomicI32::new(-1);
155
156static BSDTHREAD_REG: RwLock<Option<BsdThreadReg>> = RwLock::new(None);
158
159fn try_claim_slot(idx: usize, host_fd: RawFd) -> bool {
160 let Some(slot) = FD_HOST.get(idx) else {
161 return false;
162 };
163 slot.compare_exchange(FD_EMPTY, host_fd, Ordering::AcqRel, Ordering::Relaxed)
164 .is_ok()
165}
166
167fn reset_fd_map() {
168 for (i, slot) in FD_HOST.iter().enumerate() {
169 let prev = slot.swap(FD_EMPTY, Ordering::AcqRel);
170 if i > 2 && prev >= 0 {
171 host::close_fd(prev);
172 }
173 }
174 FD_NEXT.store(3, Ordering::Relaxed);
175}
176
177#[derive(Debug)]
182pub struct ProcessState {
183 fds: FdTable,
184 dir_streams: HashMap<i32, host::HostDir>,
186 sig_mask: u32,
187 sigactions: [SoftSigAct; 32],
188}
189
190impl ProcessState {
191 #[must_use]
193 pub fn new() -> Self {
194 Self {
195 fds: FdTable::new(),
196 dir_streams: HashMap::new(),
197 sig_mask: 0,
198 sigactions: [SoftSigAct::zero(); 32],
199 }
200 }
201
202 pub fn reset_run(&mut self, max_syscalls: usize) {
204 self.dir_streams.clear();
205 self.fds.reset();
206 self.sig_mask = 0;
207 self.sigactions = [SoftSigAct::zero(); 32];
208 clear_bsdthread_reg();
209 let max = u64::try_from(max_syscalls).unwrap_or(256);
210 MAX_SYSCALLS.store(max, Ordering::Relaxed);
211 SYSCALL_COUNT.store(0, Ordering::Relaxed);
212 crate::thread::reset_thread_runtime();
213 }
214
215 pub(crate) fn close_dir_stream(&mut self, gfd: i32) {
217 drop(self.dir_streams.remove(&gfd));
218 }
219
220 pub(crate) fn readdir_next(&mut self, gfd: i32) -> Result<Option<(Vec<u8>, u8)>, i64> {
224 let Some(host_fd) = fd_get(gfd) else {
225 return Err(9); };
227
228 if let std::collections::hash_map::Entry::Vacant(e) = self.dir_streams.entry(gfd) {
229 match host::HostDir::open_dup(host_fd) {
230 Ok(dir) => {
231 e.insert(dir);
232 }
233 Err(err) => return Err(i64::from(err)),
234 }
235 }
236
237 let Some(stream) = self.dir_streams.get_mut(&gfd) else {
238 return Err(9);
239 };
240 Ok(stream.read_next())
241 }
242
243 #[must_use]
244 pub(crate) fn sig_mask(&self) -> u32 {
245 self.sig_mask
246 }
247
248 pub(crate) fn set_sig_mask(&mut self, mask: u32) {
249 self.sig_mask = mask;
250 }
251
252 #[must_use]
253 pub(crate) fn sigaction(&self, sig: usize) -> Option<SoftSigAct> {
254 self.sigactions.get(sig).copied()
255 }
256
257 pub(crate) fn set_sigaction(&mut self, sig: usize, act: SoftSigAct) -> bool {
258 if let Some(slot) = self.sigactions.get_mut(sig) {
259 *slot = act;
260 true
261 } else {
262 false
263 }
264 }
265}
266
267impl Default for ProcessState {
268 fn default() -> Self {
269 Self::new()
270 }
271}
272
273#[must_use]
277pub fn tick_syscall() -> bool {
278 let n = SYSCALL_COUNT.fetch_add(1, Ordering::Relaxed);
279 n >= MAX_SYSCALLS.load(Ordering::Relaxed)
280}
281
282fn active_lock() -> &'static RwLock<ProcessState> {
283 static ACTIVE: OnceLock<RwLock<ProcessState>> = OnceLock::new();
284 ACTIVE.get_or_init(|| RwLock::new(ProcessState::new()))
285}
286
287pub fn with_mut<R>(f: impl FnOnce(&mut ProcessState) -> R) -> R {
289 match active_lock().write() {
290 Ok(mut guard) => f(&mut guard),
291 Err(poisoned) => f(&mut poisoned.into_inner()),
292 }
293}
294
295pub fn with_ref<R>(f: impl FnOnce(&ProcessState) -> R) -> R {
297 match active_lock().read() {
298 Ok(guard) => f(&guard),
299 Err(poisoned) => f(&poisoned.into_inner()),
300 }
301}
302
303pub fn reset_run(max_syscalls: usize) {
305 with_mut(|p| p.reset_run(max_syscalls));
306}
307
308pub fn set_bottle_root(root: Option<PathBuf>) {
312 let new_fd = root.as_ref().map_or(-1, |p| open_bottle_dirfd(p).unwrap_or(-1));
313 let old_fd = BOTTLE_DIRFD.swap(new_fd, Ordering::AcqRel);
314 if old_fd >= 0 {
315 host::close_fd(old_fd);
316 }
317
318 let next = root.map(Arc::new);
319 match BOTTLE_ROOT.write() {
320 Ok(mut guard) => {
321 *guard = next;
322 }
323 Err(poisoned) => {
324 *poisoned.into_inner() = next;
325 }
326 }
327}
328
329#[must_use]
331pub fn bottle_root() -> Option<PathBuf> {
332 with_bottle_root(|p| p.map(Path::to_path_buf))
333}
334
335pub fn with_bottle_root<R>(f: impl FnOnce(Option<&Path>) -> R) -> R {
339 match BOTTLE_ROOT.read() {
340 Ok(guard) => f(guard.as_ref().map(|a| a.as_path())),
341 Err(poisoned) => f(poisoned.into_inner().as_ref().map(|a| a.as_path())),
342 }
343}
344
345#[must_use]
349pub fn bottle_dirfd() -> Option<RawFd> {
350 let fd = BOTTLE_DIRFD.load(Ordering::Acquire);
351 if fd >= 0 { Some(fd) } else { None }
352}
353
354fn open_bottle_dirfd(root: &Path) -> Option<RawFd> {
356 let c = std::ffi::CString::new(root.as_os_str().as_encoded_bytes()).ok()?;
357 host::open_directory(&c)
358}
359
360pub(crate) fn set_bsdthread_reg(reg: BsdThreadReg) {
362 match BSDTHREAD_REG.write() {
363 Ok(mut guard) => {
364 *guard = Some(reg);
365 }
366 Err(poisoned) => {
367 *poisoned.into_inner() = Some(reg);
368 }
369 }
370}
371
372#[must_use]
374pub(crate) fn bsdthread_reg() -> Option<BsdThreadReg> {
375 match BSDTHREAD_REG.read() {
376 Ok(guard) => *guard,
377 Err(poisoned) => *poisoned.into_inner(),
378 }
379}
380
381fn clear_bsdthread_reg() {
382 match BSDTHREAD_REG.write() {
383 Ok(mut guard) => {
384 *guard = None;
385 }
386 Err(poisoned) => {
387 *poisoned.into_inner() = None;
388 }
389 }
390}
391
392#[cfg(test)]
394pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> {
395 use std::sync::Mutex;
396 static LOCK: Mutex<()> = Mutex::new(());
397 LOCK.lock()
398 .unwrap_or_else(std::sync::PoisonError::into_inner)
399}