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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//
// Syd: rock-solid application kernel
// src/pool.rs: Self growing / shrinking `ThreadPool` implementation
//
// Copyright (c) 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
// Based in part upon rusty_pool which is:
// Copyright (c) Robin Friedli <robinfriedli@icloud.com>
// SPDX-License-Identifier: Apache-2.0
//
// SPDX-License-Identifier: GPL-3.0
// Last sync with rusty_pool:
// Version 0.7.0
// Commit:d56805869ba3cbe47021d5660bbaf19ac5ec4bfb
use std::{
fs::OpenOptions,
io::Write,
option::Option,
os::{
fd::{FromRawFd, RawFd},
unix::fs::OpenOptionsExt,
},
sync::{
atomic::{AtomicBool, Ordering},
Arc, RwLock,
},
thread,
};
use dur::Duration;
use libseccomp::ScmpFilterContext;
use nix::{
errno::Errno,
sched::{unshare, CloneFlags},
sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal},
unistd::{Gid, Uid},
};
use crate::{
alert,
cache::{SysNotif, SysQueue},
compat::handle_sig_ptrace,
config::*,
confine::{secure_getenv, ExportMode},
err::{err2no, scmp2no, SydJoinHandle, SydResult},
error,
fd::{SafeOwnedFd, NULL_FD, PROC_FD, ROOT_FD},
fs::{block_signal, seccomp_export_pfc},
hook::HandlerMap,
id::SydId,
info,
path::XPathBuf,
retry::retry_on_intr,
rwrite, rwriteln,
sandbox::{Capability, Options, Sandbox},
workers::{
aes::{AesLock, AesWorker},
emu::Worker,
int::Interrupter,
ipc::IpcWorker,
not::Notifier,
out::Timeouter,
WorkerCache, WorkerData,
},
};
// Signal handler function for SIGALRM.
extern "C" fn handle_sigalrm(_: libc::c_int) {}
/// Self growing / shrinking `ThreadPool` implementation.
#[derive(Clone)]
pub(crate) struct ThreadPool {
core_size: usize,
scmp_fd: RawFd,
options: Options,
queue_wr_fd: RawFd,
cache: Arc<WorkerCache>,
sandbox: Arc<RwLock<Sandbox>>,
handlers: Arc<HandlerMap>,
should_exit: Arc<AtomicBool>,
worker_data: Arc<WorkerData>,
}
impl ThreadPool {
// Construct a new "ThreadPool" with the specified core pool size.
//
// "core_size" specifies amount of threads to keep alive for as long
// as the "ThreadPool" exists and seccomp fd remains open.
// Additional workers are spawned on demand and exit after
// EMU_KEEP_ALIVE idle time.
#[expect(clippy::too_many_arguments)]
pub(crate) fn new(
scmp_fd: RawFd,
queue_rd_fd: RawFd,
queue_wr_fd: RawFd,
options: Options,
core_size: usize,
sandbox: Arc<RwLock<Sandbox>>,
handlers: Arc<HandlerMap>,
should_exit: Arc<AtomicBool>,
crypt_map: Option<AesLock>,
sysreq_queue: SysQueue,
) -> Self {
Self {
sandbox,
handlers,
core_size,
scmp_fd,
queue_wr_fd,
options,
should_exit,
cache: Arc::new(WorkerCache::new(crypt_map, sysreq_queue, queue_rd_fd)),
worker_data: Arc::new(WorkerData::new()),
}
}
/// Clone the worker cache for the main thread.
pub(crate) fn cache(&self) -> Arc<WorkerCache> {
Arc::clone(&self.cache)
}
/// Boot the thread pool. This is the main entry point.
pub(crate) fn boot(self, sysreq_notif: SysNotif) -> SydResult<SydJoinHandle<()>> {
// Export seccomp rules if requested.
// We have to prepare the filter twice if exporting,
// as we cannot move it safely between threads...
#[expect(clippy::disallowed_methods)]
match ExportMode::from_env() {
Some(ExportMode::BerkeleyPacketFilter) => {
// Worker rules
let is_crypt = self.cache.crypt_map.is_some();
let safe_kcapi = is_crypt || {
let sandbox = self.sandbox.read().unwrap_or_else(|err| err.into_inner());
sandbox.enabled(Capability::CAP_FORCE) || sandbox.options.allow_unsafe_kcapi()
};
let ctx = Worker::prepare_confine(
self.scmp_fd,
self.options,
is_crypt,
safe_kcapi,
&[],
&[],
)?;
let file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o400)
.open(XPathBuf::in_tmpdir(b"syd_emu.bpf"))?;
ctx.export_bpf(file)?;
// Interrupter rules
// We pass dry_run=true to avoid Landlock confinement.
let ctx = Interrupter::prepare_confine(self.scmp_fd, self.options, &[], &[], true)?;
let file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o400)
.open(XPathBuf::in_tmpdir(b"syd_int.bpf"))?;
ctx.export_bpf(file)?;
// Notifier rules
// We pass dry_run=true to avoid Landlock confinement.
let ctx = Notifier::prepare_confine(
self.scmp_fd,
self.queue_wr_fd,
self.options,
&[],
&[],
true,
)?;
let file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o400)
.open(XPathBuf::in_tmpdir(b"syd_not.bpf"))?;
ctx.export_bpf(file)?;
// IPC thread rules
// We pass dummy RawFd=2525 for epoll FD.
// We pass dry_run=true to avoid Landlock confinement.
let ctx = IpcWorker::prepare_confine(2525, self.options, &[], &[], true)?;
let file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o400)
.open(XPathBuf::in_tmpdir(b"syd_ipc.bpf"))?;
ctx.export_bpf(file)?;
// Aes worker rules
let ctx = AesWorker::prepare_confine(self.options, &[], &[], true)?;
let file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o400)
.open(XPathBuf::in_tmpdir(b"syd_aes.bpf"))?;
ctx.export_bpf(file)?;
}
Some(ExportMode::PseudoFiltercode) => {
// Lock stdout to prevent concurrent access.
let mut stdout = std::io::stdout().lock();
rwriteln!(
stdout,
"# Syd monitor rules with seccomp fd {}",
self.scmp_fd
)?;
// Worker rules
let is_crypt = self.cache.crypt_map.is_some();
let safe_kcapi = is_crypt || {
let sandbox = self.sandbox.read().unwrap_or_else(|err| err.into_inner());
sandbox.enabled(Capability::CAP_FORCE) || sandbox.options.allow_unsafe_kcapi()
};
let ctx = Worker::prepare_confine(
self.scmp_fd,
self.options,
is_crypt,
safe_kcapi,
&[],
&[],
)?;
rwrite!(stdout, "{}", seccomp_export_pfc(&ctx)?)?;
// Interrupter rules
// We pass dry_run=true to avoid Landlock confinement.
rwriteln!(
stdout,
"# Syd interrupter rules with seccomp fd {}",
self.scmp_fd
)?;
let ctx = Interrupter::prepare_confine(self.scmp_fd, self.options, &[], &[], true)?;
rwrite!(stdout, "{}", seccomp_export_pfc(&ctx)?)?;
// Notifier rules
// We pass dry_run=true to avoid Landlock confinement.
rwriteln!(
stdout,
"# Syd notifier rules with seccomp fd {}",
self.scmp_fd
)?;
let ctx = Notifier::prepare_confine(
self.scmp_fd,
self.queue_wr_fd,
self.options,
&[],
&[],
true,
)?;
rwrite!(stdout, "{}", seccomp_export_pfc(&ctx)?)?;
// IPC thread rules
// We pass dummy RawFd=2525 for epoll FD.
// We pass dry_run=true to avoid Landlock confinement.
rwriteln!(stdout, "# Syd ipc rules")?;
let ctx = IpcWorker::prepare_confine(2525, self.options, &[], &[], true)?;
rwrite!(stdout, "{}", seccomp_export_pfc(&ctx)?)?;
// Aes worker rules
rwriteln!(stdout, "# Syd encryptor rules")?;
let ctx = AesWorker::prepare_confine(self.options, &[], &[], true)?;
rwrite!(stdout, "{}", seccomp_export_pfc(&ctx)?)?;
}
_ => {}
}
// Ensure the lazy num_cpus::get is called before
// the CPU pinning otherwise it may report incorrect
// value.
let nproc = *NPROC;
info!("ctx": "boot", "op": "check_num_cpus",
"msg": format!("detected {nproc} CPUs on the system"),
"num_cpus": nproc);
// Block SIGALRM to be inherited.
block_signal(libc::SIGALRM)?;
let action = SigAction::new(
SigHandler::Handler(handle_sigalrm),
SaFlags::empty(),
SigSet::empty(),
);
// SAFETY: Register no-op handler for SIGALRM.
unsafe { sigaction(Signal::SIGALRM, &action) }?;
// Block SIGRTMIN to be inherited.
let sig_rtmin = libc::SIGRTMIN();
block_signal(sig_rtmin)?;
// SAFETY:
// 1. Register ptrace signal handler.
// 2. nix' sigaction doesn't support realtime signals.
unsafe {
let mut sa: libc::sigaction = std::mem::zeroed();
sa.sa_sigaction = handle_sig_ptrace as *const () as usize;
sa.sa_flags = 0;
libc::sigemptyset(&raw mut sa.sa_mask);
libc::sigaction(sig_rtmin, &raw const sa, std::ptr::null_mut());
}
// Lock sandbox for read.
let sandbox = self.sandbox.read().unwrap_or_else(|err| err.into_inner());
let scmp_fd = self.scmp_fd;
let queue_wr_fd = self.queue_wr_fd;
let options = self.options;
let should_exit = Arc::clone(&self.should_exit);
let cache = Arc::clone(&self.cache);
let tmout = sandbox.tmout;
let transit_uids = sandbox.transit_uids.clone();
let transit_gids = sandbox.transit_gids.clone();
drop(sandbox); // release read lock.
// Spawn the monitor thread which may confine itself, and spawn
// emulator threads. Note, this will panic if it cannot spawn
// the initial emulator thread which is going to tear everything
// down. Return a join handle to the main thread so it can wait
// for the monitor thread to gracefully exit which in turn is
// going to wait for the AES threads to gracefully exit.
let mon_handle = self.monitor()?;
// Spawn notifier thread which will confine itself.
Self::try_spawn_notify(
scmp_fd,
queue_wr_fd,
options,
sysreq_notif,
&transit_uids,
&transit_gids,
&should_exit,
&cache,
)
.map(drop)?;
// Spawn interrupt thread which will confine itself.
Self::try_spawn_interrupt(
scmp_fd,
options,
&transit_uids,
&transit_gids,
&should_exit,
&cache,
)
.map(drop)?;
// Spawn timeouter thread which will confine itself.
if let Some(tmout) = tmout {
Self::try_spawn_timeout(tmout, options, &transit_uids, &transit_gids)?;
}
Ok(mon_handle)
}
/// Spawn a monitor thread that watches the worker pool busy count,
/// and spawns new helper threads as necessary. This is done to
/// ensure a sandbox process cannot DOS Syd by merely exhausting
/// workers by e.g. opening the read end of a FIFO over and over
/// again.
#[expect(clippy::cognitive_complexity)]
pub(crate) fn monitor(self) -> SydResult<SydJoinHandle<()>> {
thread::Builder::new()
.name(SydId::get_name("syd_mon").to_string())
.stack_size(MON_STACK_SIZE)
.spawn(move || {
// 1. Use exit_group(2) here to bail, because this
// unsharing is a critical safety feature.
// 2. Skip CLONE_FILES for KCOV because ptrace handler
// must close FDs.
let unshare_flags = if !cfg!(feature = "kcov") {
CloneFlags::CLONE_FS | CloneFlags::CLONE_FILES | CloneFlags::CLONE_SYSVSEM
} else {
CloneFlags::CLONE_FS | CloneFlags::CLONE_SYSVSEM
};
if let Err(errno) = unshare(unshare_flags) {
alert!("ctx": "boot", "op": "unshare_monitor_thread",
"msg": format!("failed to unshare(CLONE_FS|CLONE_FILES): {errno}"),
"err": errno as i32);
std::process::exit(101);
}
// Lock sandbox for read.
let sandbox = self.sandbox.read().unwrap_or_else(|err| err.into_inner());
// SAFETY: The monitor thread needs to inherit FDs.
// We have to sort the set as the FDs are randomized.
#[expect(clippy::cast_sign_loss)]
let mut set = vec![
ROOT_FD() as libc::c_uint,
PROC_FD() as libc::c_uint,
NULL_FD() as libc::c_uint,
sandbox.fpid as libc::c_uint,
self.scmp_fd as libc::c_uint,
self.queue_wr_fd as libc::c_uint,
self.cache.sysreq_pipe as libc::c_uint,
crate::log::LOG_FD.load(Ordering::Relaxed) as libc::c_uint,
];
let crypt = if sandbox.enabled(Capability::CAP_CRYPT) {
Some((sandbox.crypt_setup()?, sandbox.crypt_tmp))
} else {
None
};
let close_scmp_fd = !cfg!(feature = "kcov") && crypt.is_none();
#[expect(clippy::cast_sign_loss)]
if let Some((crypt_fds, crypt_tmp)) = crypt {
set.push(crypt_fds.0 as libc::c_uint);
set.push(crypt_fds.1 as libc::c_uint);
if let Some(crypt_tmp) = crypt_tmp {
set.push(crypt_tmp as libc::c_uint);
}
}
set.sort_unstable();
#[cfg(not(feature = "kcov"))]
crate::fd::closeexcept(&set)?;
drop(set);
// Spawn the AES thread if encryption is on.
let crypt_handle = if let Some((fds, tmp)) = crypt {
let map = self.cache.crypt_map.as_ref().map(Arc::clone).ok_or(Errno::ENOKEY)?;
let should_exit = Arc::clone(&self.should_exit);
Some(self.try_spawn_aes(
fds,
map,
tmp.is_none(),
should_exit,
&sandbox.transit_uids,
&sandbox.transit_gids)?)
} else {
None
};
info!("ctx": "boot", "op": "start_monitor_thread",
"msg": format!("started monitor thread with pool size set to {} threads",
self.core_size),
"core_size": self.core_size);
// SAFETY:
// 1. If sandbox is locked, confine right away.
// Pass confined parameter to try_spawn so subsequent
// spawned threads don't need to reapply the same filter
// as it is inherited.
// 2. If sandbox is not locked yet, build the seccomp context anyway,
// precompute it and pass it to emulator threads for fast confinement.
// 3. If sandbox is locked, and trace/force_umask is set, use it to confine
// fchmodat(2) and fchmodat2(2) mode argument.
let dry_run = secure_getenv(ENV_SKIP_SCMP).is_some() || ExportMode::from_env().is_some();
let is_locked = sandbox.is_locked();
let is_crypt = self.cache.crypt_map.is_some();
let safe_kcapi = is_crypt || sandbox.enabled(Capability::CAP_FORCE) || sandbox.options.allow_unsafe_kcapi();
let safe_setid = self.options.intersects(Options::OPT_ALLOW_SAFE_SETUID | Options::OPT_ALLOW_SAFE_SETGID);
let mut ctx = if !dry_run {
let ctx = Worker::prepare_confine(
self.scmp_fd,
self.options,
is_crypt,
safe_kcapi,
&sandbox.transit_uids,
&sandbox.transit_gids)?;
if is_locked {
// Sandbox locked, confine right away.
//
// SAFETY: We use exit_group(2) here to bail,
// because this confinement is a critical safety feature.
if let Err(error) = ctx.load() {
let errno = scmp2no(&error).unwrap_or(Errno::ENOSYS);
alert!("ctx": "boot", "op": "confine_monitor_thread",
"msg": format!("failed to confine: {error}"),
"err": errno as i32);
std::process::exit(101);
}
info!("ctx": "confine", "op": "confine_monitor_thread",
"msg": format!("monitor thread confined with{} SROP mitigation",
if safe_setid { "out" } else { "" }));
None
} else {
// Sandbox not locked yet, precompute and save filter.
//
// SAFETY: We use exit_group(2) here to bail,
// because this confinement is a critical safety feature.
#[cfg(libseccomp_v2_6)]
if let Err(error) = ctx.precompute() {
let errno = scmp2no(&error).unwrap_or(Errno::ENOSYS);
alert!("ctx": "boot", "op": "confine_monitor_thread",
"msg": format!("failed to precompute: {error}"),
"err": errno as i32);
std::process::exit(101);
}
info!("ctx": "confine", "op": "confine_monitor_thread",
"msg": "monitor thread is running unconfined because sandbox isn't locked yet");
Some(ctx)
}
} else {
error!("ctx": "confine", "op": "confine_monitor_thread",
"msg": "monitor thread is running unconfined in debug mode");
None
};
drop(sandbox); // release read lock.
info!("ctx": "boot", "op": "start_core_emulator_threads",
"msg": format!("starting {} core emulator thread{}, sandboxing started!",
self.core_size,
if self.core_size > 1 { "s" } else { "" }),
"core_size": self.core_size);
// Register monitor thread for unpark().
self.cache.set_mon_thread(thread::current());
// Spawn initial emulator thread or bail.
if let Err(errno) = self.try_spawn(ctx.as_ref()) {
alert!("ctx": "boot", "op": "spawn_emulator_thread",
"msg": format!("failed to spawn emulator thread: {errno}"),
"err": errno as i32);
std::process::exit(101);
}
// Spawn rest of the core emulator threads.
for _ in 1..self.core_size {
if self.try_spawn(ctx.as_ref()).is_err() {
self.signal_int();
}
}
loop {
// Confine and drop filter if sandbox is locked.
if let Some(ref filter) = ctx {
if Sandbox::is_locked_once() {
// SAFETY: We use exit_group(2) here to bail,
// because this confinement is a critical safety feature.
if let Err(error) = filter.load() {
let errno = scmp2no(&error).unwrap_or(Errno::ENOSYS);
alert!("ctx": "boot", "op": "confine_monitor_thread",
"msg": format!("failed to confine: {error}"),
"err": errno as i32);
std::process::exit(101);
}
info!("ctx": "confine", "op": "confine_monitor_thread",
"msg": format!("monitor thread confined with{} SROP mitigation",
if safe_setid { "out" } else { "" }));
// SAFETY: We cannot free the seccomp context here,
// because it may have references in emulator
// threads.
std::mem::forget(ctx);
ctx = None;
}
}
// Check for exit notification.
if self.should_exit.load(Ordering::Acquire) {
// SAFETY: We cannot free the seccomp context here,
// because it may have references in emulator
// threads.
std::mem::forget(ctx);
break;
}
// Block until a worker signals via unpark().
thread::park();
// Check for exit notification again.
if self.should_exit.load(Ordering::Acquire) {
// SAFETY: We cannot free the seccomp context here,
// because it may have references in emulator
// threads.
std::mem::forget(ctx);
break;
}
// Spawn a new thread if all others are busy.
// Thread is going to confine itself as necessary.
// On errors, be defensive and signal stuck emulator
// threads to make better use of available
// resources.
//
// TODO: Logging here runs high risk of OOM and panic.
// Reconsider when logger does fallible allocations.
if self.try_spawn(ctx.as_ref()).is_err() {
self.signal_int();
}
}
// Close seccomp fd instance with interrupter and notifier threads.
if close_scmp_fd {
// SAFETY: self.scmp_fd is a valid file descriptor.
drop(unsafe { SafeOwnedFd::from_raw_fd(self.scmp_fd) });
}
// Wake AES threads and join.
if let Some(ref crypt_map) = self.cache.crypt_map {
let (_, ref cvar) = **crypt_map;
cvar.notify_one();
}
if let Some(crypt_handle) = crypt_handle {
crypt_handle.join().or(Err(Errno::EAGAIN))??;
}
// Wake interrupt thread.
if let Some(thread) = self.cache.sysint_map.int_thread.get() {
thread.unpark();
}
Ok(())
})
.map_err(|err| err2no(&err).into())
}
// Spawn an interrupt handler thread to unblock Syd syscall
// handler threads when the respective sandbox process
// receives a non-restarting signal.
fn try_spawn_interrupt(
scmp_fd: RawFd,
options: Options,
transit_uids: &[(Uid, Uid)],
transit_gids: &[(Gid, Gid)],
should_exit: &Arc<AtomicBool>,
cache: &Arc<WorkerCache>,
) -> SydResult<SydJoinHandle<()>> {
Ok(retry_on_intr(|| {
Interrupter::new(
scmp_fd,
options,
transit_uids,
transit_gids,
Arc::clone(should_exit),
Arc::clone(cache),
)
.try_spawn()
})?)
}
// Spawn a notifier thread to fetch seccomp notifications.
#[expect(clippy::too_many_arguments)]
fn try_spawn_notify(
scmp_fd: RawFd,
queue_wr_fd: RawFd,
options: Options,
sysreq_notif: SysNotif,
transit_uids: &[(Uid, Uid)],
transit_gids: &[(Gid, Gid)],
should_exit: &Arc<AtomicBool>,
cache: &Arc<WorkerCache>,
) -> SydResult<SydJoinHandle<()>> {
let handle = retry_on_intr(|| {
Notifier::new(
scmp_fd,
queue_wr_fd,
options,
transit_uids,
transit_gids,
Arc::clone(should_exit),
Arc::clone(cache),
)
.try_spawn(Arc::clone(&sysreq_notif))
})?;
// Notifier thread is sole owner of sender end of syscall
// notification queue. Drop our copy early to ensure this.
drop(sysreq_notif);
Ok(handle)
}
// Spawn an timeout handler thread to unblock Syd syscall
// handler threads when the respective sandbox process
// receives a non-restarting signal.
fn try_spawn_timeout(
timeout: Duration,
options: Options,
transit_uids: &[(Uid, Uid)],
transit_gids: &[(Gid, Gid)],
) -> SydResult<SydJoinHandle<()>> {
Ok(retry_on_intr(|| {
Timeouter::new(timeout, options, transit_uids, transit_gids).try_spawn()
})?)
}
// Try to create a new encryption thread.
fn try_spawn_aes(
&self,
fdalg: (RawFd, RawFd),
files: AesLock,
memfd: bool,
should_exit: Arc<AtomicBool>,
transit_uids: &[(Uid, Uid)],
transit_gids: &[(Gid, Gid)],
) -> Result<SydJoinHandle<()>, Errno> {
let worker = AesWorker::new(
fdalg,
files,
self.options,
memfd,
should_exit,
transit_uids,
transit_gids,
);
// AesWorker has only RawFds as Fds which
// we do _not_ want to duplicate on clone,
// so we can get away with a clone here...
retry_on_intr(|| worker.clone().try_spawn())
}
// Try to create a new worker thread as needed.
//
// Returns Ok(Some((SydJoinHandle, bool))) if spawn succeeded, Ok(None) if no spawn was needed.
// Boolean in success case is true if thread we spawned was a core thread.
#[expect(clippy::type_complexity)]
pub(crate) fn try_spawn(
&self,
ctx: Option<&ScmpFilterContext>,
) -> Result<Option<(SydJoinHandle<()>, bool)>, Errno> {
// Create a new worker if there are no idle threads and the
// current worker count is lower than the max pool size.
let worker_count_val = self.worker_data.counter.load(Ordering::Relaxed);
let (curr_worker_count, busy_worker_count) = WorkerData::split(worker_count_val);
let is_idle = if curr_worker_count < self.core_size {
// Create a new core worker if current pool size is below
// core size during the invocation of this function.
false
} else if busy_worker_count < curr_worker_count {
// We have idle threads, no need to spawn a new worker.
return Ok(None);
} else if curr_worker_count < *EMU_MAX_SIZE {
// Create a new helper worker if the current worker count is
// below the EMU_MAX_SIZE and the pool has been observed to
// be busy (no idle workers) during the invocation of this
// function.
true
} else {
// We cannot spawn anymore workers!
// Ideally, this should never happen.
return Err(Errno::ERANGE);
};
// Pre-increment total worker count so the counter is
// immediately visible to subsequent try_spawn calls.
self.worker_data.increment_worker_total();
// Try to spawn a new worker.
match retry_on_intr(|| {
Worker::new(
self.scmp_fd,
self.queue_wr_fd,
Arc::clone(&self.cache),
Arc::clone(&self.sandbox),
Arc::clone(&self.handlers),
is_idle,
Arc::clone(&self.should_exit),
Arc::clone(&self.worker_data),
)
.try_spawn(ctx)
}) {
Ok(handle) => Ok(Some((handle, !is_idle))),
Err(errno) => {
// Spawn failed, rollback total worker count.
self.worker_data.decrement_worker_total();
Err(errno)
}
}
}
// Unblock stuck emulator threads with manual signaling.
fn signal_int(&self) {
// Set signal-all flag to mark all entries for signaling.
self.cache
.sysint_map
.sys_signal
.store(true, Ordering::Release);
// Wake interrupter thread to deliver signals.
if let Some(thread) = self.cache.sysint_map.int_thread.get() {
thread.unpark();
}
}
}