syd 3.54.1

rock-solid application kernel
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
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
785
786
787
788
789
790
791
792
793
//
// Syd: rock-solid application kernel
// src/workers/emu.rs: `syd_emu' emulator threads
//
// 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

use std::{
    option::Option,
    os::fd::{BorrowedFd, FromRawFd, RawFd},
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc, RwLock,
    },
    thread,
};

use concurrent_queue::{PopError, PushError};
use libc::{AF_ALG, AF_INET, AF_INET6, AF_NETLINK, AF_UNIX};
use libseccomp::{ScmpAction, ScmpArch, ScmpFilterContext, ScmpNotifResp, ScmpNotifRespFlags};
use libseccomp_sys::{const_scmp_filter_ctx, seccomp_load};
use nix::{
    errno::Errno,
    fcntl::OFlag,
    sched::{unshare, CloneFlags},
    unistd::{Gid, Pid, Uid},
};

use crate::{
    alert,
    compat::{clock_ms, seccomp_notif_resp},
    config::*,
    confine::{
        confine_scmp, confine_scmp_accept4, confine_scmp_bind, confine_scmp_clone,
        confine_scmp_clone3, confine_scmp_close, confine_scmp_close_range, confine_scmp_connect,
        confine_scmp_execveat, confine_scmp_faccessat2, confine_scmp_fallocate,
        confine_scmp_fchdir, confine_scmp_fchmod, confine_scmp_fchmodat, confine_scmp_fchmodat2,
        confine_scmp_fchown, confine_scmp_fchownat, confine_scmp_fcntl, confine_scmp_fgetxattr,
        confine_scmp_flistxattr, confine_scmp_fremovexattr, confine_scmp_fsetxattr,
        confine_scmp_ftruncate, confine_scmp_getdents64, confine_scmp_inotify_add_watch,
        confine_scmp_ioctl_syd, confine_scmp_kcmp, confine_scmp_kill, confine_scmp_linkat,
        confine_scmp_lremovexattr, confine_scmp_lsetxattr, confine_scmp_madvise,
        confine_scmp_memfd_create, confine_scmp_memfd_secret, confine_scmp_mkdirat,
        confine_scmp_mknodat, confine_scmp_open, confine_scmp_openat, confine_scmp_openat2,
        confine_scmp_pidfd_getfd, confine_scmp_pidfd_open, confine_scmp_pidfd_send_signal,
        confine_scmp_pipe2, confine_scmp_prctl, confine_scmp_read, confine_scmp_readlinkat,
        confine_scmp_recvmmsg, confine_scmp_recvmsg, confine_scmp_renameat2, confine_scmp_sendfile,
        confine_scmp_sendmmsg, confine_scmp_sendmsg, confine_scmp_setid, confine_scmp_sigaction,
        confine_scmp_socket, confine_scmp_socketpair, confine_scmp_splice, confine_scmp_statx,
        confine_scmp_symlinkat, confine_scmp_tgkill, confine_scmp_tkill, confine_scmp_truncate,
        confine_scmp_umask, confine_scmp_uname, confine_scmp_unlinkat, confine_scmp_unshare,
        confine_scmp_utimensat, confine_scmp_write, confine_scmp_wx_syd, ScmpNotifReq, SydArch,
        SydNotifReq, SydNotifResp, Sydcall, EIDRM, EOWNERDEAD, SIGCANCEL, SIGSETXID, SIGTIMER,
        X32_SYSCALL_BIT,
    },
    cookie::{safe_close, safe_kill, safe_read},
    err::{err2no, SydJoinHandle, SydResult},
    fd::SafeOwnedFd,
    fs::seccomp_notify_respond,
    hook::HandlerMap,
    id::SydId,
    info,
    kernel::ptrace::event::{exec::sysevent_exec, exit::sysevent_exit, scmp::sysevent_scmp},
    proc::proc_get_vma,
    req::UNotifyEventRequest,
    retry::retry_on_eintr,
    sandbox::{Options, Sandbox},
    workers::{WorkerCache, WorkerData},
};

#[derive(Clone)]
pub(crate) struct Worker {
    fd: RawFd,
    queue_wr_fd: RawFd,
    cache: Arc<WorkerCache>,
    sandbox: Arc<RwLock<Sandbox>>,
    handlers: Arc<HandlerMap>,
    is_idle: bool,
    should_exit: Arc<AtomicBool>,
    worker_data: Arc<WorkerData>,
}

impl Worker {
    #[expect(clippy::too_many_arguments)]
    pub(crate) fn new(
        fd: RawFd,
        queue_wr_fd: RawFd,
        cache: Arc<WorkerCache>,
        sandbox: Arc<RwLock<Sandbox>>,
        handlers: Arc<HandlerMap>,
        is_idle: bool,
        should_exit: Arc<AtomicBool>,
        worker_data: Arc<WorkerData>,
    ) -> Self {
        Self {
            fd,
            queue_wr_fd,
            cache,
            sandbox,
            handlers,
            is_idle,
            should_exit,
            worker_data,
        }
    }

    #[expect(clippy::cognitive_complexity)]
    pub(crate) fn try_spawn(
        self,
        ctx: Option<&ScmpFilterContext>,
    ) -> Result<SydJoinHandle<()>, Errno> {
        // ScmpFilterContext is not Send, so we cannot pass it between
        // threads. Therefore we pass a pointer which is owned by the
        // monitor thread. This pointer is guaranteed to be valid
        // throughout Syd's lifetime.
        let mut ctx = ctx.map(|ctx| ctx.as_ptr() as usize);

        thread::Builder::new()
            .name(SydId::get_name("syd_emu").to_string())
            .stack_size(EMU_STACK_SIZE)
            .spawn(move || {
                // Unshare:
                // 1. CLONE_FS so cwd and umask are per-thread.
                // 2. CLONE_FILES so file descriptor table is per-thread.
                // 3. CLONE_SYSVSEM so System V semaphores are per-thread.
                //
                // CLONE_FILES is not set if:
                // 1. Crypt sandboxing is on because emulator threads have
                //    to share memory fds with AES threads.
                // 2. KCOV is on because emulator threads have to share
                //    memory fds with the main thread.
                let mut unshare_flags = CloneFlags::CLONE_FS | CloneFlags::CLONE_SYSVSEM;
                let is_crypt = self.cache.crypt_map.is_some();
                if !cfg!(feature = "kcov") && !is_crypt {
                    unshare_flags.insert(CloneFlags::CLONE_FILES);
                }

                // We use exit_group(2) here to bail, because this
                // unsharing is a critical safety feature.
                if let Err(errno) = unshare(unshare_flags) {
                    alert!("ctx": "boot", "op": "unshare_emu_thread",
                        "msg": format!("failed to unshare({unshare_flags:?}): {errno}"),
                        "err": errno as i32);
                    std::process::exit(101);
                }

                if unshare_flags.contains(CloneFlags::CLONE_FILES) {
                    // Close our private copy of write end of the pipe.
                    // This end of the pipe is owned by the notifier.
                    let _ = safe_close(self.queue_wr_fd);
                }

                // Timestamp of last completed work item in milliseconds.
                // Used for keepalive retirement of idle threads.
                let mut last_work_ms = if self.is_idle {
                    match clock_ms() {
                        Ok(ms) => Some(ms),
                        Err(errno) => {
                            alert!("ctx": "boot", "op": "gettime_emu_thread",
                                "msg": format!("failed to get time: {errno}"),
                                "err": errno as i32);
                            std::process::exit(101);
                        }
                    }
                } else {
                    None
                };

                // Create sentinel, that will handle graceful teardown.
                let mut sentinel = Sentinel::new(&self);

                loop {
                    // Confine thread if sandbox is locked.
                    if let Some(filter) = ctx {
                        if Sandbox::is_locked_once() {
                            // Deny critical system calls on sandbox lock.
                            //
                            // We use exit_group(2) here to bail,
                            // because this confinement is a critical
                            // safety feature.
                            if let Err(error) =
                                confine_scmp(ScmpAction::KillProcess, EMU_LOCK_SYSCALLS)
                            {
                                let errno = error.errno().unwrap_or(Errno::ENOSYS);
                                alert!("ctx": "boot", "op": "confine_emu_thread",
                                    "msg": format!("failed to confine: {error}"),
                                    "err": errno as i32);
                                std::process::exit(101);
                            }
                            info!("ctx": "confine", "op": "confine_emu_thread",
                                "msg": "emulator thread confined");

                            // SAFETY: Filter pointer is owned by the monitor thread, and
                            // it's valid for the lifetime of the Syd process.
                            let error = unsafe { seccomp_load(filter as const_scmp_filter_ctx) };
                            ctx = None; // Leak ctx intentionally.

                            // We use exit_group(2) here to bail,
                            // because this confinement is a critical
                            // safety feature.
                            if error != 0 {
                                let errno = Errno::from_raw(error.abs());
                                alert!("ctx": "boot", "op": "confine_emu_thread",
                                    "msg": format!("failed to confine: {error}"),
                                    "err": errno as i32);
                                std::process::exit(101);
                            }

                            // Wake monitor to confine itself.
                            self.cache.notify_mon();
                        }
                    }

                    // Dequeue next request from the queue.
                    let request = match self.receive() {
                        Ok(request) => request,
                        Err(Errno::EAGAIN) => {
                            // Queue empty: Retry if core or check idle.
                            if let Some(last_work_ms) = last_work_ms {
                                let idle_ms = clock_ms()
                                    .unwrap_or(last_work_ms)
                                    .saturating_sub(last_work_ms);
                                #[expect(clippy::cast_possible_truncation)]
                                if idle_ms >= EMU_KEEP_ALIVE.as_millis() as u64 {
                                    self.worker_data.decrement_worker_total();
                                    break;
                                }
                            }
                            continue;
                        }
                        Err(_) => {
                            // Critical error, decrement worker total and exit.
                            self.worker_data.decrement_worker_total();
                            break;
                        }
                    };

                    // Read clock after successful dequeue.
                    let now_ms =
                        last_work_ms.map(|last_work_ms| clock_ms().unwrap_or(last_work_ms));

                    // Handle dispatched request.
                    self.dispatch_request(&mut sentinel, request);

                    // Handle all available items in the queue.
                    while let Ok(request) = self.cache.sysreq_queue.pop() {
                        if self.should_exit.load(Ordering::Acquire) {
                            break;
                        }
                        self.dispatch_request(&mut sentinel, request);
                    }

                    // Retire idle thread if blocked long enough.
                    if let (Some(now_ms), Some(last_work_ms)) = (now_ms, last_work_ms) {
                        let idle_ms = now_ms.saturating_sub(last_work_ms);
                        #[expect(clippy::cast_possible_truncation)]
                        if idle_ms >= EMU_KEEP_ALIVE.as_millis() as u64 {
                            self.worker_data.decrement_worker_total();
                            break;
                        }
                    }

                    // Check for exit notification.
                    if self.should_exit.load(Ordering::Acquire) {
                        break;
                    }

                    // Update last work time.
                    last_work_ms = now_ms;
                }

                Ok(())
            })
            .map_err(|err| err2no(&err))
    }

    // Receive a notification from syscall notification queue.
    fn receive(&self) -> Result<SydNotifReq, Errno> {
        // SAFETY: sysreq_pipe is a valid fd.
        let rd = unsafe { BorrowedFd::borrow_raw(self.cache.sysreq_pipe) };

        let mut buf = [42u8; 1];
        if retry_on_eintr(|| safe_read(rd, &mut buf))? == 0 {
            return Err(Errno::ENOTCONN);
        }

        match self.cache.sysreq_queue.pop() {
            Ok(request) => Ok(request),
            Err(PopError::Empty) => Err(Errno::EAGAIN),
            Err(PopError::Closed) => Err(Errno::ENOTCONN),
        }
    }

    #[expect(clippy::cognitive_complexity)]
    fn handle(&self, mut req: ScmpNotifReq) {
        // Correct architecture for x32 syscalls.
        if req.data.arch == ScmpArch::X8664
            && req.data.syscall.as_raw_syscall() & X32_SYSCALL_BIT != 0
        {
            req.data.arch = ScmpArch::X32;
        }

        // Lookup the system call handler, panic if not found.
        let syscall = Sydcall::new(req.data.syscall, req.data.arch);
        let handler = if let Some(handler) = self.handlers.get(&syscall) {
            handler
        } else {
            unreachable!("BUG: Missing hook for request {req:?}!");
        };

        let request = UNotifyEventRequest::new(
            req,
            syscall,
            self.fd,
            Arc::clone(&self.cache),
            Arc::clone(&self.sandbox),
        );
        let mut ghost = Sandbox::ghost_once();
        let mut response = if ghost {
            ScmpNotifResp::new_error(req.id, -libc::ENOSYS, ScmpNotifRespFlags::empty())
        } else {
            handler(request)
        };

        // Check for the following pseudo errnos:
        // 1. EIDRM:
        //    a. A previous SECCOMP_IOCTL_NOTIF_ADDFD has replied to the request with
        //       SECCOMP_ADDFD_FLAG_SEND already, no need to return a reply again here.
        //    b. A read-write encryption request was made and the encrypted fd has
        //       already been returned as a reply with SECCOMP_IOCTL_NOTIF_ADDFD with
        //       the flag SECCOMP_ADDFD_FLAG_SEND.
        // 2. EOWNERDEAD: Enter ghost mode.
        ghost = ghost
            || match response.error {
                EIDRM if response.id == 0 && response.val == 0 && response.flags == 0 => return,
                EOWNERDEAD if response.id == 0 && response.val == 0 && response.flags == 0 => {
                    #[expect(clippy::cast_possible_wrap)]
                    let pid = Pid::from_raw(req.pid as libc::pid_t);
                    let vma = proc_get_vma(pid, req.data.instr_pointer).ok();
                    crate::warn!("ctx": "confine", "op": "enter_ghost_mode", "pid": req.pid,
                    "sys": syscall, "arch": SydArch::from(req.data.arch), "args": req.data.args,
                    "ip": req.data.instr_pointer, "src": vma);

                    // 1. Correct seccomp user notification ID.
                    // 2. Correct the pseudo errno(3) EOWNERDEAD back to success.
                    response.id = req.id;
                    response.error = 0;
                    response.val = 0;

                    true
                }
                _ => false,
            };

        let response = seccomp_notif_resp {
            id: response.id,
            val: response.val,
            error: response.error,
            flags: response.flags,
        };

        // EINTR is not retried because it may mean child is signaled.
        // ENOENT means child died mid-way.
        // Nothing else we can do on errors here.
        let _ = seccomp_notify_respond(self.fd, std::ptr::addr_of!(response));

        // Finalize ghost mode as necessary.
        if ghost {
            // SAFETY: self.fd is a valid file descriptor.
            drop(unsafe { SafeOwnedFd::from_raw_fd(self.fd) });

            // Inform other threads to exit and wake monitor.
            self.should_exit.store(true, Ordering::Release);
            self.cache.notify_mon();
            self.cache.interrupt_run();
        }
    }

    fn dispatch_request(&self, sentinel: &mut Sentinel<'_>, request: SydNotifReq) {
        match request {
            SydNotifReq::Seccomp(req) => {
                sentinel.seccomp_id = Some(req.id);
                self.worker_data.increment_worker_busy();
                self.handle(req);
                self.worker_data.decrement_worker_busy();
                sentinel.seccomp_id = None;
            }
            ptrace_req => {
                let is_sigreturn = ptrace_req.is_sigreturn();
                let (arch, child) = match &ptrace_req {
                    SydNotifReq::PtraceScmp { info, .. } => (info.arch, None),
                    SydNotifReq::PtraceExec { .. } => (0, None),
                    SydNotifReq::PtraceExit { .. } => (0, None),
                    SydNotifReq::Seccomp(_) => unreachable!(),
                };

                let pid = ptrace_req.pid();
                sentinel.ptrace_info = Some(PtraceInfo {
                    pid,
                    arch,
                    cpid: child,
                    is_sigreturn,
                });

                self.worker_data.increment_worker_busy();
                if self.handle_ptrace_request(ptrace_req).is_err() {
                    let _ = safe_kill(pid, libc::SIGKILL);
                    if let Some(cpid) = child {
                        let _ = safe_kill(cpid, libc::SIGKILL);
                    }
                }
                self.worker_data.decrement_worker_busy();

                sentinel.ptrace_info = None;
            }
        }
    }

    fn handle_ptrace_request(&self, request: SydNotifReq) -> Result<(), Errno> {
        let response = match request {
            SydNotifReq::PtraceScmp { pid, info } => {
                sysevent_scmp(pid, info, &self.cache, &self.sandbox)
            }

            SydNotifReq::PtraceExec { pid } => sysevent_exec(pid, &self.cache, &self.sandbox),

            SydNotifReq::PtraceExit {
                pid,
                wait_all,
                status,
            } => sysevent_exit(pid, status, wait_all, &self.cache, &self.sandbox),

            SydNotifReq::Seccomp(_) => unreachable!(),
        };

        // Push response to queue and wake main thread.
        if let Some(response) = response {
            match self.cache.ptrace_resp.push(response) {
                Ok(()) => self.cache.interrupt_run(),
                Err(PushError::Full(_)) => return Err(Errno::ENOSPC),
                Err(PushError::Closed(_)) => return Err(Errno::ENOTCONN),
            }
        }
        Ok(())
    }

    /// Confine Worker thread.
    #[expect(clippy::cognitive_complexity)]
    pub(crate) fn prepare_confine(
        seccomp_fd: RawFd,
        options: Options,
        is_crypt: bool,
        safe_kcapi: bool,
        transit_uids: &[(Uid, Uid)],
        transit_gids: &[(Gid, Gid)],
    ) -> SydResult<ScmpFilterContext> {
        // Create seccomp filter with default action.
        let mut ctx = ScmpFilterContext::new(ScmpAction::KillProcess)?;

        // Enforce the NO_NEW_PRIVS functionality before
        // loading the seccomp filter into the kernel.
        ctx.set_ctl_nnp(true)?;

        // Disable Speculative Store Bypass mitigations
        // with trace/allow_unsafe_exec_speculative:1
        ctx.set_ctl_ssb(options.allow_unsafe_exec_speculative())?;

        // DO NOT synchronize filter to all threads.
        // Main thread will confine itself.
        ctx.set_ctl_tsync(false)?;

        // We kill for bad system call and bad arch.
        ctx.set_act_badarch(ScmpAction::KillProcess)?;

        // Use a binary tree sorted by syscall number if possible.
        let _ = ctx.set_ctl_optimize(2);

        // Do NOT add supported architectures to the filter.
        // This ensures Syd can never run a non-native system call,
        // which we do not need at all.
        // seccomp_add_architectures(&mut ctx)?;

        // Allow clones without namespace flags.
        confine_scmp_clone(&mut ctx)?;
        // Deny clone3 with ENOSYS for compatibility.
        confine_scmp_clone3(&mut ctx)?;

        // Allow safe madvise(2) advice.
        confine_scmp_madvise(&mut ctx)?;

        // SafeSetId is used when changing UID/GID.
        let safe_setid =
            options.intersects(Options::OPT_ALLOW_SAFE_SETUID | Options::OPT_ALLOW_SAFE_SETGID);

        // Syscall argument cookies may be disabled
        // at startup with trace/allow_unsafe_nocookie:1.
        let restrict_cookie = !options.allow_unsafe_nocookie();

        // Confine block/char device creation.
        let restrict_mkbdev = !options.allow_unsafe_mkbdev();
        let restrict_mkcdev = !options.allow_unsafe_mkcdev();

        // Allow safe system calls.
        //
        // KCOV_SYSCALLS is empty in case `kcov` feature is disabled.
        // PROF_SYSCALLS is empty in case `prof` feature is disabled.
        for sysname in EMU_SYSCALLS
            .iter()
            .chain(ALLOC_SYSCALLS)
            .chain(FUTEX_SYSCALLS)
            .chain(GETID_SYSCALLS)
            .chain(KCOV_SYSCALLS)
            .chain(PROF_SYSCALLS)
            .chain(VDSO_SYSCALLS)
        {
            match Sydcall::from_name(sysname) {
                Ok(syscall) => {
                    ctx.add_rule(ScmpAction::Allow, syscall)?;
                }
                Err(_) => {
                    info!("ctx": "confine", "op": "allow_emu_syscall",
                        "msg": format!("invalid or unsupported syscall {sysname}"));
                }
            }
        }

        let prctl_ops = EMU_PRCTL_OPS.iter().chain(if safe_setid {
            EMU_PRCTL_OPS_SAFESETID.iter()
        } else {
            [].iter()
        });
        confine_scmp_read(&mut ctx, 0x10000, restrict_cookie)?;
        confine_scmp_write(
            &mut ctx,
            Some(0x10000),
            false, /*log_only*/
            restrict_cookie,
        )?;
        confine_scmp_close(&mut ctx, restrict_cookie)?;
        confine_scmp_close_range(&mut ctx, restrict_cookie)?;
        confine_scmp_execveat(&mut ctx, restrict_cookie)?;
        confine_scmp_faccessat2(&mut ctx, restrict_cookie)?;
        confine_scmp_fallocate(&mut ctx, restrict_cookie)?;
        confine_scmp_fchdir(&mut ctx, restrict_cookie)?;
        confine_scmp_fchmod(&mut ctx, restrict_cookie)?;
        confine_scmp_fchmodat(&mut ctx, restrict_cookie)?;
        confine_scmp_fchmodat2(&mut ctx, restrict_cookie)?;
        confine_scmp_fchown(&mut ctx, restrict_cookie)?;
        confine_scmp_fchownat(&mut ctx, restrict_cookie)?;
        confine_scmp_fgetxattr(&mut ctx, restrict_cookie)?;
        confine_scmp_flistxattr(&mut ctx, restrict_cookie)?;
        confine_scmp_fremovexattr(&mut ctx, restrict_cookie)?;
        confine_scmp_fsetxattr(&mut ctx, restrict_cookie)?;
        confine_scmp_ftruncate(&mut ctx, restrict_cookie)?;
        confine_scmp_getdents64(&mut ctx, restrict_cookie)?;
        confine_scmp_ioctl_syd(&mut ctx, restrict_cookie, Some(seccomp_fd))?;
        confine_scmp_inotify_add_watch(&mut ctx, restrict_cookie)?;
        confine_scmp_kcmp(&mut ctx, restrict_cookie)?;
        confine_scmp_linkat(&mut ctx, restrict_cookie)?;
        confine_scmp_lremovexattr(&mut ctx, restrict_cookie)?;
        confine_scmp_lsetxattr(&mut ctx, restrict_cookie)?;
        confine_scmp_memfd_create(&mut ctx, restrict_cookie)?;
        confine_scmp_memfd_secret(&mut ctx, restrict_cookie)?;
        confine_scmp_mkdirat(&mut ctx, restrict_cookie)?;
        confine_scmp_mknodat(&mut ctx, restrict_cookie, restrict_mkbdev, restrict_mkcdev)?;
        confine_scmp_open(&mut ctx)?;
        confine_scmp_openat(&mut ctx)?;
        confine_scmp_openat2(&mut ctx, restrict_cookie)?;
        confine_scmp_pidfd_getfd(&mut ctx, restrict_cookie)?;
        confine_scmp_pidfd_open(&mut ctx, restrict_cookie)?;
        confine_scmp_pidfd_send_signal(&mut ctx, restrict_cookie)?;
        confine_scmp_prctl(&mut ctx, prctl_ops)?;
        confine_scmp_readlinkat(&mut ctx, restrict_cookie)?;
        confine_scmp_renameat2(&mut ctx, restrict_cookie, restrict_mkcdev)?;
        confine_scmp_sigaction(&mut ctx)?;
        confine_scmp_statx(&mut ctx, restrict_cookie)?;
        confine_scmp_symlinkat(&mut ctx, restrict_cookie)?;
        confine_scmp_truncate(&mut ctx, restrict_cookie)?;
        confine_scmp_umask(&mut ctx, restrict_cookie)?;
        confine_scmp_uname(&mut ctx, restrict_cookie)?;
        confine_scmp_unlinkat(&mut ctx, restrict_cookie)?;
        confine_scmp_utimensat(&mut ctx, restrict_cookie)?;
        confine_scmp_wx_syd(&mut ctx)?;

        // KCOV needs unrestricted fcntl(2) calls.
        // TODO: Find out what fcntls it actually needs.
        if cfg!(feature = "kcov") {
            for sysname in ["fcntl", "fcntl64"] {
                if let Ok(syscall) = Sydcall::from_name(sysname) {
                    ctx.add_rule(ScmpAction::Allow, syscall)?;
                }
            }
        } else {
            confine_scmp_fcntl(&mut ctx, EMU_FCNTL_OPS)?;
        }

        // Restrict pipe2(2) flags, and use syscall argument cookies.
        // Allow pipes(2), splice(2), and sendfile(2) for zero-copy.
        // Needed for Force & Crypt sandboxing and KCOV.
        if safe_kcapi || cfg!(feature = "kcov") {
            confine_scmp_pipe2(&mut ctx, restrict_cookie, OFlag::O_CLOEXEC)?;
            confine_scmp_splice(&mut ctx)?;
            confine_scmp_sendfile(&mut ctx, restrict_cookie)?;
        }

        // Allow unshare(2) with CLONE_FS|CLONE_FILES|CLONE_SYSVSEM only.
        // Crypt sandboxing and KCOV require FD-share between EMU<->AES threads.
        let mut clone_flags = CloneFlags::CLONE_FS | CloneFlags::CLONE_SYSVSEM;
        if !cfg!(feature = "kcov") && !is_crypt {
            clone_flags.insert(CloneFlags::CLONE_FILES);
        };
        confine_scmp_unshare(&mut ctx, clone_flags)?;

        // Confine network system calls.
        //
        // Allow only specified socket domains.
        let domains = if !options.allow_unsupp_socket() {
            let mut domains = vec![AF_UNIX, AF_INET, AF_INET6, AF_NETLINK];
            if safe_kcapi {
                domains.push(AF_ALG);
            }
            Some(domains)
        } else {
            None
        };
        let restrict_socket = !options.allow_unsafe_socket();
        confine_scmp_socket(
            &mut ctx,
            domains.as_deref(),
            restrict_socket,
            restrict_cookie,
        )?;
        confine_scmp_socketpair(
            &mut ctx,
            domains.as_deref(),
            restrict_socket,
            restrict_cookie,
        )?;
        confine_scmp_accept4(&mut ctx, restrict_cookie)?;
        confine_scmp_bind(&mut ctx, restrict_cookie)?;
        confine_scmp_connect(&mut ctx, restrict_cookie)?;
        confine_scmp_recvmmsg(&mut ctx, restrict_cookie)?;
        confine_scmp_recvmsg(&mut ctx, restrict_cookie)?;
        confine_scmp_sendmmsg(&mut ctx, restrict_cookie)?;
        confine_scmp_sendmsg(&mut ctx, restrict_cookie)?;

        // Allow kill(2) with syscall argument cookies.
        confine_scmp_kill(
            &mut ctx,
            &[libc::SIGABRT, libc::SIGKILL, libc::SIGSTOP],
            restrict_cookie,
        )?;

        // Signal allowlist for tkill(2) and tgkill(2):
        // 1. Allow 0 for existence checks.
        // 2. Allow libc internal signals for thread cancellation and timers.
        // 3. SIGRTMIN is used to wake main thread.
        // 4. SIGSETXID is only needed when SafeSetID is enabled.
        if safe_setid {
            confine_scmp_tkill(&mut ctx, &[SIGCANCEL, SIGTIMER, SIGSETXID])?;
            confine_scmp_tgkill(
                &mut ctx,
                &[libc::SIGRTMIN(), SIGCANCEL, SIGTIMER, SIGSETXID],
            )?;
        } else {
            confine_scmp_tkill(&mut ctx, &[SIGCANCEL, SIGTIMER])?;
            confine_scmp_tgkill(&mut ctx, &[libc::SIGRTMIN(), SIGCANCEL, SIGTIMER])?;
        }

        // Allow UID/GID changing system calls as necessary.
        let safe_setuid = options.allow_safe_setuid();
        let safe_setgid = options.allow_safe_setgid();
        if safe_setuid || safe_setgid {
            confine_scmp_setid(
                "emu",
                &mut ctx,
                safe_setuid,
                safe_setgid,
                transit_uids,
                transit_gids,
            )?;

            // cap{g,s}et is necessary to drop CAP_SET{U,G}ID after changing {U,G}ID.
            // {rt_,}sig{action,return} are already allowed for emulators to handle SIGALRM.
            for sysname in ["capget", "capset"] {
                match Sydcall::from_name(sysname) {
                    Ok(syscall) => {
                        ctx.add_rule(ScmpAction::Allow, syscall)?;
                    }
                    Err(_) => {
                        info!("ctx": "confine", "op": "allow_emu_syscall",
                            "msg": format!("invalid or unsupported syscall {sysname}"));
                    }
                }
            }
        }

        Ok(ctx)
    }
}

// Ptrace request in progress used for panic cleanup.
struct PtraceInfo {
    pid: Pid,
    arch: u32,
    cpid: Option<Pid>,
    is_sigreturn: bool,
}

// Type that exists to manage worker exit on panic.
//
// This type is constructed once per `Worker` and implements `Drop` to
// handle proper worker exit in case the worker panics when executing
// the current task or anywhere else in its work loop.
struct Sentinel<'a> {
    seccomp_id: Option<u64>,
    ptrace_info: Option<PtraceInfo>,
    worker_ref: &'a Worker,
}

impl<'a> Sentinel<'a> {
    fn new(worker_ref: &'a Worker) -> Sentinel<'a> {
        Self {
            seccomp_id: None,
            ptrace_info: None,
            worker_ref,
        }
    }

    #[expect(clippy::arithmetic_side_effects)]
    fn deny_syscall(&self, seccomp_id: u64, errno: Errno) {
        let response = seccomp_notif_resp {
            id: seccomp_id,
            val: 0,
            error: -(errno as i32),
            flags: 0,
        };

        // EAGAIN|EINTR is retried.
        // ENOENT means child died mid-way.
        // Nothing else we can do on errors here.
        let _ = seccomp_notify_respond(self.worker_ref.fd, std::ptr::addr_of!(response));
    }
}

impl Drop for Sentinel<'_> {
    fn drop(&mut self) {
        if thread::panicking() {
            if let Some(seccomp_id) = self.seccomp_id {
                // Seccomp notification: Deny syscall in progress.
                self.deny_syscall(seccomp_id, Errno::EACCES);
                self.worker_ref.worker_data.decrement_both();
            } else if let Some(PtraceInfo {
                pid,
                arch,
                cpid,
                is_sigreturn,
            }) = self.ptrace_info
            {
                if is_sigreturn {
                    // sigreturn(2) must be terminated.
                    let _ = safe_kill(pid, libc::SIGKILL);
                } else if arch != 0 {
                    // Syscall entry: deny with EACCES, fallback to terminate.
                    let response = SydNotifResp::Deny {
                        pid,
                        arch,
                        errno: Errno::EACCES,
                    };
                    if self.worker_ref.cache.ptrace_resp.push(response).is_ok() {
                        self.worker_ref.cache.interrupt_run();
                    } else {
                        let _ = safe_kill(pid, libc::SIGKILL);
                    }
                } else {
                    // Non-syscall event: Terminate parent and child.
                    let _ = safe_kill(pid, libc::SIGKILL);
                    if let Some(cpid) = cpid {
                        let _ = safe_kill(cpid, libc::SIGKILL);
                    }
                }
                self.worker_ref.worker_data.decrement_both();
            } else {
                // Idle thread panicked.
                self.worker_ref.worker_data.decrement_worker_total();
            }
        }
    }
}