1use std::collections::HashMap;
8use std::os::fd::RawFd;
9use std::path::PathBuf;
10use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
11use std::sync::{OnceLock, RwLock};
12
13use crate::host;
14
15static SYSCALL_COUNT: AtomicU64 = AtomicU64::new(0);
17static MAX_SYSCALLS: AtomicU64 = AtomicU64::new(256);
19
20const FD_SLOTS: usize = 1024;
22const FD_EMPTY: i32 = -1;
24
25static FD_HOST: [AtomicI32; FD_SLOTS] = [const { AtomicI32::new(FD_EMPTY) }; FD_SLOTS];
30static FD_NEXT: AtomicI32 = AtomicI32::new(3);
32
33#[derive(Clone, Copy, Debug)]
35pub(crate) struct SoftSigAct {
36 pub handler: u64,
37 pub mask: u32,
38 pub flags: i32,
39}
40
41#[derive(Clone, Copy, Debug, Default)]
45#[allow(dead_code)]
46pub(crate) struct BsdThreadReg {
47 pub threadstart: u64,
49 pub wqthread: u64,
51 pub flags: u32,
53 pub stack_addr_hint: u64,
55 pub tsd_offset: u32,
57 pub dispatchqueue_offset: u32,
59}
60
61impl SoftSigAct {
62 pub(crate) const fn zero() -> Self {
63 Self {
64 handler: 0,
65 mask: 0,
66 flags: 0,
67 }
68 }
69}
70
71#[derive(Debug, Default)]
73pub(crate) struct FdTable;
74
75impl FdTable {
76 const fn new() -> Self {
77 Self
78 }
79
80 pub(crate) fn reset(&mut self) {
81 let _ = self;
82 reset_fd_map();
83 }
84
85 pub(crate) fn take(&mut self, gfd: i32) -> Option<RawFd> {
86 let _ = self;
87 fd_take(gfd)
88 }
89
90 pub(crate) fn alloc(&mut self, host_fd: RawFd) -> Option<i32> {
91 let _ = self;
92 fd_alloc(host_fd)
93 }
94}
95
96#[must_use]
98#[inline]
99pub fn fd_get(gfd: i32) -> Option<RawFd> {
100 if gfd == 0 || gfd == 1 || gfd == 2 {
101 return Some(gfd);
102 }
103 if gfd < 0 {
104 return None;
105 }
106 let Ok(idx) = usize::try_from(gfd) else {
107 return None;
108 };
109 let slot = FD_HOST.get(idx)?;
110 let v = slot.load(Ordering::Acquire);
111 if v < 0 { None } else { Some(v) }
112}
113
114fn fd_take(gfd: i32) -> Option<RawFd> {
115 if gfd <= 2 {
116 return None;
117 }
118 let Ok(idx) = usize::try_from(gfd) else {
119 return None;
120 };
121 let slot = FD_HOST.get(idx)?;
122 let v = slot.swap(FD_EMPTY, Ordering::AcqRel);
123 if v < 0 { None } else { Some(v) }
124}
125
126fn fd_alloc(host_fd: RawFd) -> Option<i32> {
127 if host_fd < 0 {
128 return None;
129 }
130 let start = usize::try_from(FD_NEXT.load(Ordering::Relaxed).max(3)).unwrap_or(3);
131 for idx in start..FD_SLOTS {
132 if try_claim_slot(idx, host_fd) {
133 let gfd = i32::try_from(idx).ok()?;
134 FD_NEXT.store(gfd.saturating_add(1), Ordering::Relaxed);
135 return Some(gfd);
136 }
137 }
138 for idx in 3..start.min(FD_SLOTS) {
139 if try_claim_slot(idx, host_fd) {
140 let gfd = i32::try_from(idx).ok()?;
141 FD_NEXT.store(gfd.saturating_add(1), Ordering::Relaxed);
142 return Some(gfd);
143 }
144 }
145 None
146}
147
148fn try_claim_slot(idx: usize, host_fd: RawFd) -> bool {
149 let Some(slot) = FD_HOST.get(idx) else {
150 return false;
151 };
152 slot.compare_exchange(FD_EMPTY, host_fd, Ordering::AcqRel, Ordering::Relaxed)
153 .is_ok()
154}
155
156fn reset_fd_map() {
157 for (i, slot) in FD_HOST.iter().enumerate() {
158 let prev = slot.swap(FD_EMPTY, Ordering::AcqRel);
159 if i > 2 && prev >= 0 {
160 host::close_fd(prev);
161 }
162 }
163 FD_NEXT.store(3, Ordering::Relaxed);
164}
165
166#[derive(Debug)]
168pub struct ProcessState {
169 fds: FdTable,
170 dir_streams: HashMap<i32, host::HostDir>,
172 bottle_root: Option<PathBuf>,
173 sig_mask: u32,
174 sigactions: [SoftSigAct; 32],
175 bsdthread: Option<BsdThreadReg>,
176}
177
178impl ProcessState {
179 #[must_use]
181 pub fn new() -> Self {
182 Self {
183 fds: FdTable::new(),
184 dir_streams: HashMap::new(),
185 bottle_root: None,
186 sig_mask: 0,
187 sigactions: [SoftSigAct::zero(); 32],
188 bsdthread: None,
189 }
190 }
191
192 pub fn reset_run(&mut self, max_syscalls: usize) {
194 self.dir_streams.clear();
195 self.fds.reset();
196 self.sig_mask = 0;
197 self.sigactions = [SoftSigAct::zero(); 32];
198 self.bsdthread = None;
199 let max = u64::try_from(max_syscalls).unwrap_or(256);
200 MAX_SYSCALLS.store(max, Ordering::Relaxed);
201 SYSCALL_COUNT.store(0, Ordering::Relaxed);
202 crate::thread::reset_thread_runtime();
203 }
204
205 pub(crate) fn close_dir_stream(&mut self, gfd: i32) {
207 drop(self.dir_streams.remove(&gfd));
208 }
209
210 pub(crate) fn readdir_next(&mut self, gfd: i32) -> Result<Option<(Vec<u8>, u8)>, i64> {
214 let Some(host_fd) = fd_get(gfd) else {
215 return Err(9); };
217
218 if let std::collections::hash_map::Entry::Vacant(e) = self.dir_streams.entry(gfd) {
219 match host::HostDir::open_dup(host_fd) {
220 Ok(dir) => {
221 e.insert(dir);
222 }
223 Err(err) => return Err(i64::from(err)),
224 }
225 }
226
227 let Some(stream) = self.dir_streams.get_mut(&gfd) else {
228 return Err(9);
229 };
230 Ok(stream.read_next())
231 }
232
233 #[must_use]
234 pub(crate) fn bsdthread(&self) -> Option<BsdThreadReg> {
235 self.bsdthread
236 }
237
238 pub(crate) fn set_bsdthread(&mut self, reg: BsdThreadReg) {
239 self.bsdthread = Some(reg);
240 }
241
242 pub(crate) fn fds_mut(&mut self) -> &mut FdTable {
243 &mut self.fds
244 }
245
246 #[must_use]
247 pub fn bottle_root(&self) -> Option<&std::path::Path> {
248 self.bottle_root.as_deref()
249 }
250
251 pub fn set_bottle_root(&mut self, root: Option<PathBuf>) {
252 self.bottle_root = root;
253 }
254
255 #[must_use]
256 pub(crate) fn sig_mask(&self) -> u32 {
257 self.sig_mask
258 }
259
260 pub(crate) fn set_sig_mask(&mut self, mask: u32) {
261 self.sig_mask = mask;
262 }
263
264 #[must_use]
265 pub(crate) fn sigaction(&self, sig: usize) -> Option<SoftSigAct> {
266 self.sigactions.get(sig).copied()
267 }
268
269 pub(crate) fn set_sigaction(&mut self, sig: usize, act: SoftSigAct) -> bool {
270 if let Some(slot) = self.sigactions.get_mut(sig) {
271 *slot = act;
272 true
273 } else {
274 false
275 }
276 }
277}
278
279impl Default for ProcessState {
280 fn default() -> Self {
281 Self::new()
282 }
283}
284
285#[must_use]
289pub fn tick_syscall() -> bool {
290 let n = SYSCALL_COUNT.fetch_add(1, Ordering::Relaxed);
291 n >= MAX_SYSCALLS.load(Ordering::Relaxed)
292}
293
294fn active_lock() -> &'static RwLock<ProcessState> {
295 static ACTIVE: OnceLock<RwLock<ProcessState>> = OnceLock::new();
296 ACTIVE.get_or_init(|| RwLock::new(ProcessState::new()))
297}
298
299pub fn with_mut<R>(f: impl FnOnce(&mut ProcessState) -> R) -> R {
301 match active_lock().write() {
302 Ok(mut guard) => f(&mut guard),
303 Err(poisoned) => f(&mut poisoned.into_inner()),
304 }
305}
306
307pub fn with_ref<R>(f: impl FnOnce(&ProcessState) -> R) -> R {
309 match active_lock().read() {
310 Ok(guard) => f(&guard),
311 Err(poisoned) => f(&poisoned.into_inner()),
312 }
313}
314
315pub fn reset_run(max_syscalls: usize) {
317 with_mut(|p| p.reset_run(max_syscalls));
318}
319
320pub fn set_bottle_root(root: Option<PathBuf>) {
322 with_mut(|p| p.set_bottle_root(root));
323}
324
325#[must_use]
327pub fn bottle_root() -> Option<PathBuf> {
328 with_ref(|p| p.bottle_root.clone())
329}
330
331pub fn with_bottle_root<R>(f: impl FnOnce(Option<&std::path::Path>) -> R) -> R {
333 with_ref(|p| f(p.bottle_root.as_deref()))
334}
335
336#[cfg(test)]
338pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> {
339 use std::sync::Mutex;
340 static LOCK: Mutex<()> = Mutex::new(());
341 LOCK.lock()
342 .unwrap_or_else(std::sync::PoisonError::into_inner)
343}