bob 0.99.0

A pkgsrc package builder
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
/*
 * Copyright (c) 2026 Jonathan Perkin <jonathan@perkin.org.uk>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

//! Sandbox creation and management.
//!
//! This module provides the [`Sandbox`] struct for creating isolated build
//! environments using chroot. The implementation varies by platform but
//! presents a uniform interface.
//!
//! # Platform Support
//!
//! | Platform | Implementation |
//! |----------|---------------|
//! | Linux | Mount namespaces + chroot |
//! | macOS | bindfs/devfs + chroot |
//! | NetBSD | Native mounts + chroot |
//! | illumos/Solaris | Platform mounts + chroot |
//!
//! # Sandbox Lifecycle
//!
//! 1. **Create**: Set up the sandbox directory and perform configured actions
//! 2. **Execute**: Run build scripts inside the sandbox via chroot
//! 3. **Destroy**: Reverse actions and clean up the sandbox directory
//!
//! # Configuration
//!
//! Sandboxes are configured in the `sandboxes` section of the Lua config file.
//! See the [`action`](crate::action) module for available actions.
//!
//! ```lua
//! sandboxes = {
//!     basedir = "/data/chroot",
//!     actions = {
//!         { action = "mount", fs = "proc", dir = "/proc" },
//!         { action = "mount", fs = "dev", dir = "/dev" },
//!         { action = "mount", fs = "bind", dir = "/usr/bin", opts = "ro" },
//!         { action = "copy", dir = "/etc" },
//!     },
//! }
//! ```
//!
//! # Multiple Sandboxes
//!
//! Multiple sandboxes can be created for parallel builds. Each sandbox is
//! identified by an integer ID (0, 1, 2, ...) and created as a subdirectory
//! of `basedir`.
//!
//! With `build_threads = 4`, sandboxes are created at:
//! - `/data/chroot/0`
//! - `/data/chroot/1`
//! - `/data/chroot/2`
//! - `/data/chroot/3`
#[cfg(target_os = "linux")]
mod sandbox_linux;
#[cfg(target_os = "macos")]
mod sandbox_macos;
#[cfg(target_os = "netbsd")]
mod sandbox_netbsd;
#[cfg(any(target_os = "illumos", target_os = "solaris"))]
mod sandbox_sunos;

use crate::action::{Action, ActionContext, ActionType, FSType};
use crate::config::{Config, PkgsrcEnv};
use crate::try_println;
use crate::{Interrupted, RunState};
use anyhow::{Context, Result, bail};
use rayon::prelude::*;
use std::fs;
use std::io::Write;
use std::os::unix::process::CommandExt;
use std::os::unix::process::ExitStatusExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Output, Stdio};
use std::sync::mpsc::RecvTimeoutError;
use std::time::{Duration, Instant};
use tracing::{debug, info, info_span, warn};

/**
 * Extension trait to place a child process in its own session.
 *
 * Calling `.setsid()` detaches the child from the controlling terminal,
 * preventing build tools (e.g. pax) from writing to `/dev/tty`.  This
 * registers a `pre_exec` hook, which forces Rust to use `fork+exec`
 * instead of `posix_spawn`.  On illumos `fork()` suspends all threads,
 * so only use this when terminal isolation is required (builds, not
 * scans).
 */
pub trait CommandSetsid {
    fn new_session(&mut self) -> &mut Self;
}

impl CommandSetsid for Command {
    fn new_session(&mut self) -> &mut Self {
        unsafe {
            self.pre_exec(|| {
                libc::setsid();
                Ok(())
            });
        }
        self
    }
}

/*
 * The libc crate does not expose wait4() on illumos, but it is available
 * in libc as a wrapper around waitid().  Declare it here.
 */
#[cfg(target_os = "illumos")]
unsafe extern "C" {
    fn wait4(
        pid: libc::pid_t,
        status: *mut libc::c_int,
        options: libc::c_int,
        rusage: *mut libc::rusage,
    ) -> libc::pid_t;
}

/// How often to check the shutdown flag while waiting for something else.
/// This determines the maximum latency between Ctrl+C and response.
/// 100ms provides responsive feel without excessive polling overhead.
pub(crate) const SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(100);

/// Maximum number of retries when killing processes in a sandbox.
/// Uses exponential backoff: 64ms, 128ms, 256ms, 512ms, 1024ms = ~2s total.
pub(crate) const KILL_PROCESSES_MAX_RETRIES: u32 = 5;
pub(crate) const KILL_PROCESSES_INITIAL_DELAY_MS: u64 = 64;

/**
 * Poll for child process exit while checking a run state flag.  If
 * shutdown is requested, kill the child and return an error.  During
 * stop the child is allowed to continue running.
 *
 * Uses wait4() instead of try_wait() to collect resource usage from the
 * child process.  Returns the exit status and CPU time (user + system).
 */
pub fn wait_with_shutdown(child: &mut Child, state: &RunState) -> Result<(ExitStatus, Duration)> {
    let pid = child.id() as libc::pid_t;
    loop {
        if state.is_shutdown() {
            let _ = child.kill();
            let _ = child.wait();
            bail!("Interrupted by shutdown");
        }
        let mut status: libc::c_int = 0;
        let mut rusage: libc::rusage = unsafe { std::mem::zeroed() };
        #[cfg(target_os = "illumos")]
        let ret = unsafe { wait4(pid, &mut status, libc::WNOHANG, &mut rusage) };
        #[cfg(not(target_os = "illumos"))]
        let ret = unsafe { libc::wait4(pid, &mut status, libc::WNOHANG, &mut rusage) };
        if ret < 0 {
            let err = std::io::Error::last_os_error();
            bail!("wait4 failed for pid {}: {}", pid, err);
        }
        if ret == 0 {
            std::thread::sleep(SHUTDOWN_POLL_INTERVAL);
            continue;
        }
        let utime = Duration::new(
            rusage.ru_utime.tv_sec as u64,
            rusage.ru_utime.tv_usec as u32 * 1000,
        );
        let stime = Duration::new(
            rusage.ru_stime.tv_sec as u64,
            rusage.ru_stime.tv_usec as u32 * 1000,
        );
        return Ok((ExitStatus::from_raw(status), utime + stime));
    }
}

/**
 * Wait for child process exit while checking a shutdown flag, returning
 * the full output (stdout/stderr).  If shutdown is requested, kill the
 * child and return an error.
 *
 * Uses a single helper thread that calls wait_with_output() (which handles
 * pipe draining correctly via internal threads).  The main thread polls a
 * channel for results while checking the shutdown flag.  This avoids the
 * polling latency of try_wait() while still allowing shutdown interruption.
 */
pub fn wait_output_with_shutdown(child: Child, state: &RunState) -> Result<Output> {
    let pid = child.id();
    let (tx, rx) = std::sync::mpsc::channel();

    std::thread::spawn(move || {
        let _ = tx.send(child.wait_with_output());
    });

    loop {
        if state.is_shutdown() {
            unsafe {
                libc::kill(-(pid as libc::pid_t), libc::SIGKILL);
            }
            let _ = rx.recv();
            bail!("Interrupted by shutdown");
        }
        match rx.recv_timeout(SHUTDOWN_POLL_INTERVAL) {
            Ok(result) => return result.map_err(Into::into),
            Err(RecvTimeoutError::Timeout) => continue,
            Err(RecvTimeoutError::Disconnected) => {
                bail!("wait thread disconnected unexpectedly");
            }
        }
    }
}

/**
 * Build sandbox manager.
 *
 * Provides a uniform interface for running commands regardless of
 * whether sandboxes are enabled. When enabled, commands execute inside
 * a chroot; when disabled, they run directly on the host.
 *
 * Use [`SandboxScope`] for RAII lifecycle management in build/scan
 * operations.
 */
#[derive(Clone, Debug, Default)]
pub struct Sandbox {
    config: Config,
    context: ActionContext,
}

impl Sandbox {
    /**
     * Create a new [`Sandbox`] instance for build operations.  This is
     * used even if sandboxes have not been enabled, as it provides a
     * consistent interface to run commands through using [`execute`].
     * If sandboxes are enabled then commands are executed via
     * `chroot(8)`, otherwise they are executed directly.
     *
     * [`execute`]: Sandbox::execute
     */
    pub fn new(config: &Config) -> Sandbox {
        Self::with_context(config, ActionContext::Build)
    }

    /**
     * Create a new [`Sandbox`] instance for `bob sandbox shell`
     * interactive sessions.  Actions whose `only.context` is set to
     * `"dev"` will run; actions restricted to `"build"` will be skipped.
     */
    pub fn new_dev(config: &Config) -> Sandbox {
        Self::with_context(config, ActionContext::Dev)
    }

    fn with_context(config: &Config, context: ActionContext) -> Sandbox {
        Sandbox {
            config: config.clone(),
            context,
        }
    }

    /// Return whether sandboxes have been enabled.
    ///
    /// This is based on whether a valid `sandboxes` section has been
    /// specified in the config file.
    pub fn enabled(&self) -> bool {
        self.config.sandboxes().is_some()
    }

    fn basedir(&self) -> Option<&PathBuf> {
        self.config.sandboxes().as_ref().map(|s| &s.basedir)
    }

    /**
     * Return full path to a sandbox by id.
     */
    pub fn path(&self, id: usize) -> PathBuf {
        let sandbox = &self.config.sandboxes().as_ref().unwrap();
        let mut p = PathBuf::from(&sandbox.basedir);
        p.push(id.to_string());
        p
    }

    /**
     * Create a Command that runs in the sandbox (via chroot) if enabled,
     * or directly if sandboxes are disabled.
     *
     * The returned command uses `posix_spawn` where available.  Call
     * [`.new_session()`](CommandSetsid::new_session) on the result to place the
     * child in a new session (prevents `/dev/tty` access by build tools,
     * but forces `fork+exec` which is expensive on illumos).
     */
    pub fn command(&self, id: Option<usize>, cmd: &Path) -> Command {
        let mut c = match id {
            Some(id) => {
                let mut c = Command::new("/usr/sbin/chroot");
                c.arg(self.path(id)).arg(cmd);
                c
            }
            None => Command::new(cmd),
        };
        self.apply_build_environment(&mut c);
        c
    }

    /**
     * Apply the build-time environment to a Command.
     *
     * Resolves to `environment.build` from the config.  If neither
     * `environment` nor `environment.build` is configured, the parent
     * environment is inherited unchanged.  Otherwise the context's
     * `clear`/`inherit` policy is applied and its `vars` are set.
     */
    pub fn apply_build_environment(&self, cmd: &mut Command) {
        let Some(ctx) = self.config.environment().and_then(|e| e.build.as_ref()) else {
            return;
        };
        Self::apply_env_context(cmd, ctx);
        for (name, value) in &ctx.vars {
            cmd.env(name, value);
        }
    }

    /**
     * Apply only the dev-context parent-environment policy
     * (`clear`/`inherit`) to a Command, without setting any variables.
     *
     * Used by interactive `bob sandbox shell` sessions, where the user's
     * `environment.dev.vars` are written to a wrapper init script and
     * exported by the shell itself rather than via `cmd.env()`.
     */
    pub fn apply_dev_environment(&self, cmd: &mut Command) {
        let Some(ctx) = self.config.environment().and_then(|e| e.dev.as_ref()) else {
            return;
        };
        Self::apply_env_context(cmd, ctx);
    }

    fn apply_env_context(cmd: &mut Command, ctx: &crate::config::EnvContext) {
        if ctx.clear {
            cmd.env_clear();
            for name in &ctx.inherit {
                if let Ok(value) = std::env::var(name) {
                    cmd.env(name, value);
                }
            }
        }
    }

    /**
     * Kill all processes in a sandbox by id.
     * This is used for graceful shutdown on Ctrl+C.
     */
    pub fn kill_processes_by_id(&self, id: Option<usize>) {
        let Some(id) = id else { return };
        let sandbox = self.path(id);
        if sandbox.exists() {
            let span = info_span!("kill_processes", sandbox_id = id);
            let _guard = span.enter();
            self.kill_processes_by_path(&sandbox);
        }
    }

    /**
     * Kill all processes with open references under a sandbox path.
     *
     * Uses platform-specific `find_pids()` to locate processes, then
     * sends SIGKILL via `kill -9`.  Retries with exponential backoff.
     */
    fn kill_processes_by_path(&self, sandbox: &Path) {
        for iteration in 0..KILL_PROCESSES_MAX_RETRIES {
            let pids = self.find_pids(sandbox);

            if pids.is_empty() {
                debug!(retries = iteration, "No processes found in sandbox");
                return;
            }

            info!(pids = %pids.join(" "), "Killed processes using sandbox");

            let _ = Command::new("kill")
                .arg("-9")
                .args(&pids)
                .stderr(Stdio::null())
                .process_group(0)
                .status();

            let delay_ms = KILL_PROCESSES_INITIAL_DELAY_MS << iteration;
            std::thread::sleep(Duration::from_millis(delay_ms));
        }
        if let Some(proc_info) = self.get_process_info(sandbox) {
            warn!(
                max_retries = KILL_PROCESSES_MAX_RETRIES,
                remaining = %proc_info,
                "Gave up killing processes after max retries"
            );
        } else {
            warn!(
                max_retries = KILL_PROCESSES_MAX_RETRIES,
                "Gave up killing processes after max retries"
            );
        }
    }

    /**
     * Find PIDs of processes using files under the sandbox path.
     *
     * Uses `fuser` which matches by path, not filesystem.
     * macOS and NetBSD override this in their platform files.
     */
    #[cfg(not(any(target_os = "macos", target_os = "netbsd")))]
    fn find_pids(&self, sandbox: &Path) -> Vec<String> {
        let output = Command::new("fuser")
            .arg(sandbox)
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .process_group(0)
            .output();
        let Ok(out) = output else { return vec![] };
        if !out.status.success() {
            return vec![];
        }
        String::from_utf8_lossy(&out.stdout)
            .split_whitespace()
            .map(|s| s.to_string())
            .collect()
    }

    /**
     * Get human-readable info about processes still using the sandbox.
     */
    fn get_process_info(&self, sandbox: &Path) -> Option<String> {
        let pids = self.find_pids(sandbox);
        self.format_process_info(&pids)
    }

    /**
     * Format process info for a list of PIDs using ps.
     *
     * illumos overrides this with pargs (ps truncates on illumos).
     */
    #[cfg(not(any(target_os = "illumos", target_os = "solaris")))]
    fn format_process_info(&self, pids: &[String]) -> Option<String> {
        if pids.is_empty() {
            return None;
        }
        let out = Command::new("ps")
            .arg("-ww")
            .arg("-o")
            .arg("pid,args")
            .arg("-p")
            .arg(pids.join(","))
            .process_group(0)
            .output()
            .ok()?;

        let info: Vec<String> = String::from_utf8_lossy(&out.stdout)
            .lines()
            .skip(1)
            .filter_map(|line| {
                let mut parts = line.split_whitespace();
                let pid = parts.next()?;
                let cmd: String = parts.collect::<Vec<_>>().join(" ");
                Some(format!("pid={} cmd='{}'", pid, cmd))
            })
            .collect();

        if info.is_empty() {
            None
        } else {
            Some(info.join(", "))
        }
    }

    /**
     * Return full path to a specified mount point in a sandbox.
     * The returned path is guaranteed to be within the sandbox directory.
     */
    fn mountpath(&self, id: usize, mnt: &PathBuf) -> PathBuf {
        /*
         * Note that .push() on a PathBuf will replace the path if
         * it is absolute, so we need to trim any leading "/".
         */
        let mut p = self.path(id);
        match mnt.strip_prefix("/") {
            Ok(s) => p.push(s),
            Err(_) => p.push(mnt),
        };
        p
    }

    /**
     * Verify that a path is safely contained within the sandbox.
     * This prevents path traversal attacks via ".." or symlinks.
     * Returns error if the path escapes the sandbox boundary.
     */
    fn verify_path_in_sandbox(&self, id: usize, path: &Path) -> Result<()> {
        let sandbox_root = self.path(id);
        // Canonicalize both paths to resolve any ".." or symlinks
        // Note: canonicalize requires the path to exist, so we check
        // the parent directory for paths that don't exist yet
        let canonical_sandbox = sandbox_root.canonicalize().unwrap_or(sandbox_root.clone());

        // For the target path, try to canonicalize what exists
        let canonical_path = if path.exists() {
            path.canonicalize()?
        } else {
            // Path doesn't exist yet, check its parent
            if let Some(parent) = path.parent() {
                if parent.exists() {
                    let canonical_parent = parent.canonicalize()?;
                    if !canonical_parent.starts_with(&canonical_sandbox) {
                        bail!(
                            "Path escapes sandbox: {} is not within {}",
                            path.display(),
                            sandbox_root.display()
                        );
                    }
                }
            }
            return Ok(());
        };

        if !canonical_path.starts_with(&canonical_sandbox) {
            bail!(
                "Path escapes sandbox: {} resolves to {} which is not within {}",
                path.display(),
                canonical_path.display(),
                canonical_sandbox.display()
            );
        }
        Ok(())
    }

    /*
     * Marker directory functions for sandbox lifecycle management.
     *
     * Each sandbox has a .bob directory that marks it as bob-managed.
     * Inside .bob, a "completed" directory indicates the sandbox was set up
     * successfully.  This two-stage marker allows detecting incomplete sandboxes.
     */
    fn bobmarker(&self, id: usize) -> PathBuf {
        self.path(id).join(".bob")
    }

    fn completedpath(&self, id: usize) -> PathBuf {
        self.bobmarker(id).join("completed")
    }

    fn mark_complete(&self, id: usize) -> Result<()> {
        let path = self.completedpath(id);
        fs::create_dir(&path).with_context(|| format!("Failed to create {}", path.display()))?;
        Ok(())
    }

    fn is_bob_sandbox(&self, id: usize) -> bool {
        self.bobmarker(id).exists()
    }

    fn is_sandbox_complete(&self, id: usize) -> bool {
        self.completedpath(id).exists()
    }

    /**
     * Discover all bob-managed sandboxes by scanning basedir.
     * Returns sorted list of sandbox IDs.
     */
    fn discover_sandboxes(&self) -> Result<Vec<usize>> {
        let Some(basedir) = self.basedir() else {
            return Ok(vec![]);
        };
        if !basedir.exists() {
            return Ok(vec![]);
        }
        let mut ids = Vec::new();
        let entries = fs::read_dir(basedir)
            .with_context(|| format!("Failed to read {}", basedir.display()))?;
        for entry in entries {
            let entry = entry?;
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
                continue;
            };
            let Ok(id) = name.parse::<usize>() else {
                continue;
            };
            if self.is_bob_sandbox(id) {
                ids.push(id);
            }
        }
        ids.sort();
        Ok(ids)
    }

    /**
     * Claim the next available sandbox ID.
     */
    pub fn claim_id(&self) -> Result<usize> {
        let mut candidate = 0;
        loop {
            if self.create(candidate)? {
                return Ok(candidate);
            }
            candidate += 1;
        }
    }

    /**
     * Claim and set up `n` sandboxes in parallel.
     *
     * Each parallel task independently claims the next available ID
     * (the atomic mkdir on `.bob` prevents races) and sets it up.
     * On any failure, all successfully created sandboxes are destroyed.
     */
    pub fn claim_ids(&self, n: usize) -> Result<Vec<usize>> {
        let results: Vec<Result<usize>> = (0..n).into_par_iter().map(|_| self.claim_id()).collect();

        let mut claimed = Vec::with_capacity(n);
        let mut first_error: Option<anyhow::Error> = None;
        for result in results {
            match result {
                Ok(id) => claimed.push(id),
                Err(e) => {
                    if first_error.is_none() {
                        first_error = Some(e);
                    }
                }
            }
        }

        if let Some(e) = first_error {
            for &id in &claimed {
                let _ = self.destroy(id);
            }
            return Err(e);
        }

        claimed.sort();
        Ok(claimed)
    }

    /**
     * Atomically claims the ID via the `.bob` marker directory, then
     * runs configured actions and marks complete.  Returns `Ok(false)`
     * if the ID is already taken by another process.
     */
    pub fn create(&self, id: usize) -> Result<bool> {
        let sandbox = self.path(id);
        fs::create_dir_all(&sandbox)
            .with_context(|| format!("Failed to create {}", sandbox.display()))?;
        let marker = self.bobmarker(id);
        match fs::create_dir(&marker) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false),
            Err(e) => {
                return Err(e).with_context(|| format!("Failed to create {}", marker.display()));
            }
        }
        let Some(sandbox) = &self.config.sandboxes() else {
            bail!("Internal error: trying to create sandbox when sandboxes disabled.");
        };
        let envs = self.config.script_env(None);
        self.perform_actions(id, &sandbox.setup, &envs)?;
        self.mark_complete(id)?;
        Ok(true)
    }

    /**
     * Execute inline script content via /bin/sh.
     */
    pub fn execute_script(
        &self,
        id: Option<usize>,
        content: &str,
        envs: Vec<(String, String)>,
    ) -> Result<Child> {
        let mut cmd = self.command(id, Path::new("/bin/sh"));
        cmd.new_session();
        cmd.current_dir("/").arg("-s");

        for (key, val) in envs {
            cmd.env(key, val);
        }

        let mut child = cmd
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;

        if let Some(mut stdin) = child.stdin.take() {
            stdin.write_all(content.as_bytes())?;
        }

        Ok(child)
    }

    /**
     * Execute a command directly without shell interpretation.
     */
    pub fn execute_command<I, S>(
        &self,
        id: Option<usize>,
        cmd: &Path,
        args: I,
        envs: Vec<(String, String)>,
    ) -> Result<Child>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<std::ffi::OsStr>,
    {
        let mut command = self.command(id, cmd);
        command.args(args);
        for (key, val) in envs {
            command.env(key, val);
        }
        command
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .process_group(0)
            .spawn()
            .map_err(Into::into)
    }

    /**
     * Run pre-build operations:
     *  1. Unpack bootstrap kit if configured
     *  2. Execute build action create commands in order
     *
     * Returns Ok(true) if all operations succeeded or none were configured,
     * Ok(false) if any operation failed.
     */
    pub fn run_pre_build(
        &self,
        sandbox_id: Option<usize>,
        config: &Config,
        envs: Vec<(String, String)>,
    ) -> Result<bool> {
        if let Some(bootstrap) = config.bootstrap() {
            let Some(sandbox_id) = sandbox_id else {
                bail!("bootstrap requires sandboxes to be enabled");
            };
            let dest = self.path(sandbox_id);
            info!(bootstrap = %bootstrap.display(), dest = %dest.display(), "Unpacking bootstrap kit");
            let file = fs::File::open(bootstrap)
                .with_context(|| format!("Failed to open bootstrap {}", bootstrap.display()))?;
            let gz = flate2::read::GzDecoder::new(file);
            let mut archive = tar::Archive::new(gz);
            archive.set_preserve_permissions(true);
            archive.set_preserve_ownerships(true);
            archive.unpack(&dest).with_context(|| {
                format!(
                    "Failed to unpack bootstrap {} to {}",
                    bootstrap.display(),
                    dest.display()
                )
            })?;
        }

        let hooks = config.hooks();
        if !hooks.is_empty() {
            let Some(sandbox_id) = sandbox_id else {
                bail!("hooks require sandboxes to be enabled");
            };
            if let Err(e) = self.perform_actions(sandbox_id, hooks, &envs) {
                warn!(error = %e, "Hook action failed");
                return Ok(false);
            }
        }

        Ok(true)
    }

    /**
     * Run post-build operations:
     *  1. Execute hook destroy commands in reverse order
     *  2. Remove prefix, pkg_dbdir, and pkg_refcount_dbdir
     *
     * Returns Ok(true) if all operations succeeded or none were configured,
     * Ok(false) if any operation failed.
     */
    pub fn run_post_build(
        &self,
        sandbox_id: Option<usize>,
        config: &Config,
        envs: Vec<(String, String)>,
    ) -> Result<bool> {
        let hooks = config.hooks();
        if !hooks.is_empty() {
            let Some(sandbox_id) = sandbox_id else {
                bail!("hooks require sandboxes to be enabled");
            };
            if let Err(e) = self.reverse_actions(sandbox_id, hooks, &envs) {
                warn!(error = %e, "Hook destroy action failed");
                return Ok(false);
            }
        }

        for var in ["bob_prefix", "bob_pkg_dbdir", "bob_pkg_refcount_dbdir"] {
            if let Some((_, path)) = envs.iter().find(|(k, _)| k == var) {
                let target = match sandbox_id {
                    Some(id) => self.resolve_path(id, Path::new(path)),
                    None => PathBuf::from(path),
                };
                if target.exists() {
                    debug!(path = %target.display(), "Removing");
                    if let Err(e) = fs::remove_dir_all(&target) {
                        warn!(
                            path = %target.display(),
                            error = %e,
                            "Failed to remove directory"
                        );
                    }
                }
            }
        }

        Ok(true)
    }

    /**
     * Resolve a path relative to the sandbox root.
     */
    fn resolve_path(&self, sandbox_id: usize, path: &Path) -> PathBuf {
        self.mountpath(sandbox_id, &path.to_path_buf())
    }

    /**
     * Run a command as part of an action.
     *
     * When `chroot` is true, the command runs inside the sandbox via
     * chroot.  Otherwise it runs on the host with the sandbox root as
     * the working directory.
     */
    fn run_action_cmd(
        &self,
        sandbox_id: usize,
        cmd: &str,
        chroot: bool,
        envs: &[(String, String)],
    ) -> Result<Option<Output>> {
        let sandbox_path = self.path(sandbox_id);
        let output = if chroot {
            let mut c = Command::new("/usr/sbin/chroot");
            self.apply_build_environment(&mut c);
            for (key, val) in envs {
                c.env(key, val);
            }
            c.arg(&sandbox_path)
                .arg("/bin/sh")
                .arg("-ceu")
                .arg(cmd)
                .stdin(Stdio::null())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .process_group(0);
            c.output()?
        } else {
            let mut c = Command::new("/bin/sh");
            self.apply_build_environment(&mut c);
            for (key, val) in envs {
                c.env(key, val);
            }
            c.arg("-ceu")
                .arg(cmd)
                .env("bob_sandbox_path", &sandbox_path)
                .current_dir(&sandbox_path)
                .stdin(Stdio::null())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .process_group(0);
            c.output()?
        };
        Ok(Some(output))
    }

    /**
     * Destroy a single sandbox by id.
     */
    pub fn destroy(&self, id: usize) -> anyhow::Result<()> {
        let sandbox = self.path(id);
        if !sandbox.exists() {
            return Ok(());
        }
        /*
         * First, remove the "completed" marker to indicate this sandbox is no
         * longer available for builds.  If cleanup fails after this point,
         * the sandbox remains discoverable (has .bob) but is marked incomplete.
         */
        let completeddir = self.completedpath(id);
        if completeddir.exists() {
            self.remove_empty_hierarchy(&completeddir)?;
        }
        let Some(sandbox_config) = &self.config.sandboxes() else {
            bail!("Internal error: trying to destroy sandbox when sandboxes disabled.");
        };
        let envs = self.config.script_env(None);
        self.kill_processes_by_path(&self.path(id));
        self.reverse_actions(id, &sandbox_config.setup, &envs)?;
        /*
         * Remove all sandbox contents EXCEPT .bob.  If removal fails due to
         * unexpected files, the .bob marker remains and the sandbox can still
         * be discovered for retry.
         */
        if sandbox.exists() {
            let bobmarker = self.bobmarker(id);
            let entries = fs::read_dir(&sandbox)
                .with_context(|| format!("Failed to read {}", sandbox.display()))?;
            for entry in entries {
                let entry = entry?;
                let path = entry.path();
                if path == bobmarker {
                    continue;
                }
                self.remove_empty_hierarchy(&path)?;
            }
            /*
             * All other contents removed successfully.  Remove .bob as the
             * absolute last step - this is what makes the sandbox no longer
             * discoverable.
             */
            if bobmarker.exists() {
                self.remove_empty_hierarchy(&bobmarker)?;
            }
            self.remove_empty_hierarchy(&sandbox)?;
        }
        Ok(())
    }

    /**
     * Create sandboxes, claiming available IDs.
     */
    pub fn create_all(&self, count: usize) -> Result<()> {
        let msg = if count == 1 {
            "Creating sandbox".to_string()
        } else {
            format!("Creating {} sandboxes", count)
        };
        crate::print_status(&msg);
        let start = Instant::now();
        self.claim_ids(count)?;
        crate::print_elapsed(&msg, start.elapsed());
        Ok(())
    }

    /**
     * Destroy all discovered sandboxes in parallel.  Runs post-build cleanup
     * on each sandbox first, then destroys them.  Continue on errors to ensure
     * all sandboxes are attempted, printing each error as it occurs.
     */
    pub fn destroy_all(&self, pkgsrc_env: Option<&PkgsrcEnv>) -> Result<()> {
        let sandboxes = self.discover_sandboxes()?;
        if sandboxes.is_empty() {
            return Ok(());
        }
        let envs = self.config.script_env(pkgsrc_env);
        for &id in &sandboxes {
            if self.path(id).exists() {
                match self.run_post_build(Some(id), &self.config, envs.clone()) {
                    Ok(true) => {}
                    Ok(false) => {
                        warn!("post-build failed for sandbox {}", id)
                    }
                    Err(e) => {
                        warn!(error = %e, sandbox = id, "post-build error")
                    }
                }
            }
        }
        let msg = if sandboxes.len() == 1 {
            "Destroying sandbox".to_string()
        } else {
            format!("Destroying {} sandboxes", sandboxes.len())
        };
        crate::print_status(&msg);
        let start = Instant::now();
        let results: Vec<(usize, Result<()>)> = sandboxes
            .into_par_iter()
            .map(|i| (i, self.destroy(i)))
            .collect();
        let mut failed = 0;
        for (i, result) in results {
            if let Err(e) = result {
                if failed == 0 {
                    println!();
                }
                eprintln!("sandbox {}: {:#}", i, e);
                failed += 1;
            }
        }
        if failed == 0 {
            crate::print_elapsed(&msg, start.elapsed());
            Ok(())
        } else {
            Err(anyhow::anyhow!(
                "Failed to destroy {} sandbox{}.\n\
                 Remove unexpected files, then run 'bob sandbox destroy'.",
                failed,
                if failed == 1 { "" } else { "es" }
            ))
        }
    }

    /**
     * List all discovered sandboxes.
     */
    pub fn list_all(&self) -> Result<()> {
        for id in self.discover_sandboxes()? {
            let sandbox = self.path(id);
            let line = if self.is_sandbox_complete(id) {
                format!("{}", sandbox.display())
            } else {
                format!("{} (incomplete)", sandbox.display())
            };
            if !try_println(&line) {
                break;
            }
        }
        Ok(())
    }

    /**
     * Count discovered sandboxes (complete or incomplete).
     */
    pub fn count_existing(&self) -> Result<usize> {
        Ok(self.discover_sandboxes()?.len())
    }

    /*
     * Remove any empty directories from a mount point up to the root of the
     * sandbox.
     */
    fn remove_empty_dirs(&self, id: usize, mountpoint: &Path) {
        for p in mountpoint.ancestors() {
            /*
             * Sanity check we are within the chroot.
             */
            if !p.starts_with(self.path(id)) {
                break;
            }
            /*
             * Go up to next parent if this path does not exist.
             */
            if !p.exists() {
                continue;
            }
            /*
             * Otherwise attempt to remove.  If this fails then skip any
             * parent directories.
             */
            if fs::remove_dir(p).is_err() {
                break;
            }
        }
    }

    /// Remove a directory hierarchy only if it contains nothing but empty
    /// directories and symlinks. Walks depth-first. Removes symlinks and
    /// empty directories. Fails if any regular files, device nodes, pipes,
    /// sockets, or other non-removable entries are encountered.
    #[allow(clippy::only_used_in_recursion)]
    fn remove_empty_hierarchy(&self, path: &Path) -> Result<()> {
        // Use symlink_metadata to not follow symlinks
        let meta = fs::symlink_metadata(path)?;

        if meta.is_symlink() {
            // Symlinks can be removed
            fs::remove_file(path).map_err(|e| {
                anyhow::anyhow!("Failed to remove symlink {}: {}", path.display(), e)
            })?;
            return Ok(());
        }

        if !meta.is_dir() {
            // Regular file, device node, pipe, socket, etc. - fail
            bail!(
                "Cannot remove sandbox: non-directory exists at {}",
                path.display()
            );
        }

        // It's a directory - process contents first (depth-first)
        let entries =
            fs::read_dir(path).with_context(|| format!("Failed to read {}", path.display()))?;
        for entry in entries {
            let entry = entry?;
            self.remove_empty_hierarchy(&entry.path())?;
        }

        // Directory should now be empty, remove it
        fs::remove_dir(path).map_err(|e| {
            anyhow::anyhow!(
                "Failed to remove directory {}: {}. Directory may not be empty.",
                path.display(),
                e
            )
        })
    }

    /**
     * Execute action create commands in order.
     */
    fn perform_actions(
        &self,
        sandbox_id: usize,
        actions: &[Action],
        envs: &[(String, String)],
    ) -> Result<()> {
        for action in actions {
            if !action.only().matches(self.context) {
                debug!(
                    sandbox = sandbox_id,
                    action = action
                        .action_type()
                        .map(|t| format!("{:?}", t))
                        .unwrap_or_default(),
                    "Skipped (only predicate not satisfied)"
                );
                continue;
            }
            action.validate()?;
            let action_type = action.action_type()?;

            let src = action.src().or(action.dest());
            let dest = action
                .dest()
                .or(action.src())
                .map(|d| self.resolve_path(sandbox_id, d));
            if let Some(dest_path) = &dest {
                self.verify_path_in_sandbox(sandbox_id, dest_path)?;
            }

            let mut opts = vec![];
            if let Some(o) = action.opts() {
                for opt in o.split(' ').collect::<Vec<&str>>() {
                    opts.push(opt);
                }
            }

            let status = match action_type {
                ActionType::Mount => {
                    let fs_type = action.fs_type()?;
                    let src =
                        src.ok_or_else(|| anyhow::anyhow!("mount action requires src or dest"))?;
                    let dest = dest.ok_or_else(|| anyhow::anyhow!("mount action requires dest"))?;
                    debug!(
                        sandbox = sandbox_id,
                        action = "mount",
                        fs = ?fs_type,
                        src = %src.display(),
                        dest = %dest.display(),
                        "Mounting"
                    );
                    match fs_type {
                        FSType::Bind => self.mount_bindfs(src, &dest, &opts)?,
                        FSType::Dev => self.mount_devfs(src, &dest, &opts)?,
                        FSType::Fd => self.mount_fdfs(src, &dest, &opts)?,
                        FSType::Nfs => self.mount_nfs(src, &dest, &opts)?,
                        FSType::Proc => self.mount_procfs(src, &dest, &opts)?,
                        FSType::Tmp => self.mount_tmpfs(src, &dest, &opts)?,
                    }
                }
                ActionType::Copy => {
                    let src =
                        src.ok_or_else(|| anyhow::anyhow!("copy action requires src or dest"))?;
                    let dest = dest.ok_or_else(|| anyhow::anyhow!("copy action requires dest"))?;
                    debug!(
                        sandbox = sandbox_id,
                        action = "copy",
                        src = %src.display(),
                        dest = %dest.display(),
                        "Copying"
                    );
                    if let Some(parent) = dest.parent() {
                        fs::create_dir_all(parent)
                            .with_context(|| format!("Failed to create {}", parent.display()))?;
                    }
                    copy_dir::copy_dir(src, &dest).with_context(|| {
                        format!("Failed to copy {} to {}", src.display(), dest.display())
                    })?;
                    fs::set_permissions(&dest, fs::metadata(src)?.permissions())?;
                    None
                }
                ActionType::Cmd => {
                    if let Some(create_cmd) = action.create_cmd() {
                        debug!(
                            sandbox = sandbox_id,
                            action = "cmd",
                            cmd = %create_cmd.run,
                            chroot = action.chroot(),
                            "Running create command"
                        );
                        let mut merged_envs: Vec<(String, String)> = envs.to_vec();
                        merged_envs.extend(create_cmd.env.iter().cloned());
                        if let Some(out) = self.run_action_cmd(
                            sandbox_id,
                            &create_cmd.run,
                            action.chroot(),
                            &merged_envs,
                        )? {
                            if !out.status.success() {
                                let stderr = String::from_utf8_lossy(&out.stderr);
                                let stderr = stderr.trim();
                                if stderr.is_empty() {
                                    bail!(
                                        "create command failed (exit code {}): {}",
                                        out.status
                                            .code()
                                            .map_or("signal".to_string(), |c| c.to_string()),
                                        create_cmd.run,
                                    );
                                } else {
                                    bail!(
                                        "create command failed (exit code {}): {}\n{}",
                                        out.status
                                            .code()
                                            .map_or("signal".to_string(), |c| c.to_string()),
                                        create_cmd.run,
                                        stderr,
                                    );
                                }
                            }
                        }
                    }
                    None
                }
                ActionType::Symlink => {
                    let src = action
                        .src()
                        .ok_or_else(|| anyhow::anyhow!("symlink action requires src"))?;
                    let dest_path = self.resolve_path(
                        sandbox_id,
                        action
                            .dest()
                            .ok_or_else(|| anyhow::anyhow!("symlink action requires dest"))?,
                    );
                    debug!(
                        sandbox = sandbox_id,
                        action = "symlink",
                        src = %src.display(),
                        dest = %dest_path.display(),
                        "Creating symlink"
                    );
                    if let Some(parent) = dest_path.parent() {
                        if !parent.exists() {
                            fs::create_dir_all(parent).with_context(|| {
                                format!("Failed to create {}", parent.display())
                            })?;
                        }
                    }
                    std::os::unix::fs::symlink(src, &dest_path).with_context(|| {
                        format!(
                            "Failed to create symlink {} -> {}",
                            dest_path.display(),
                            src.display()
                        )
                    })?;
                    None
                }
                ActionType::MacosMdnsListener => {
                    #[cfg(not(target_os = "macos"))]
                    bail!("'macos-mdns-listener' action is only supported on macOS");
                    #[cfg(target_os = "macos")]
                    {
                        debug!(
                            sandbox = sandbox_id,
                            action = "macos-mdns-listener",
                            "Creating mDNS listener"
                        );
                        self.create_mdns_listener(sandbox_id)?;
                        None
                    }
                }
            };
            if let Some(s) = status {
                if !s.success() {
                    bail!(
                        "Action failed (exit code {:?})",
                        s.code().map_or("signal".to_string(), |c| c.to_string()),
                    );
                }
            }
        }
        Ok(())
    }

    /**
     * Execute action destroy commands in reverse order.
     */
    fn reverse_actions(
        &self,
        sandbox_id: usize,
        actions: &[Action],
        envs: &[(String, String)],
    ) -> Result<()> {
        for action in actions.iter().rev() {
            if !action.only().matches(self.context) {
                continue;
            }
            let action_type = action.action_type()?;
            let dest = action
                .dest()
                .or(action.src())
                .map(|d| self.resolve_path(sandbox_id, d));

            match action_type {
                ActionType::Cmd => {
                    if let Some(destroy_cmd) = action.destroy_cmd() {
                        debug!(
                            action = "cmd",
                            cmd = %destroy_cmd.run,
                            chroot = action.chroot(),
                            "Running destroy command"
                        );
                        let mut merged_envs: Vec<(String, String)> = envs.to_vec();
                        merged_envs.extend(destroy_cmd.env.iter().cloned());
                        if let Some(out) = self.run_action_cmd(
                            sandbox_id,
                            &destroy_cmd.run,
                            action.chroot(),
                            &merged_envs,
                        )? {
                            if !out.status.success() {
                                let stderr = String::from_utf8_lossy(&out.stderr);
                                let stderr = stderr.trim();
                                if stderr.is_empty() {
                                    bail!(
                                        "destroy command failed (exit code {}): {}",
                                        out.status
                                            .code()
                                            .map_or("signal".to_string(), |c| c.to_string()),
                                        destroy_cmd.run,
                                    );
                                } else {
                                    bail!(
                                        "destroy command failed (exit code {}): {}\n{}",
                                        out.status
                                            .code()
                                            .map_or("signal".to_string(), |c| c.to_string()),
                                        destroy_cmd.run,
                                        stderr,
                                    );
                                }
                            }
                        }
                    }
                }
                ActionType::Copy => {
                    let Some(dest) = dest else { continue };
                    if !dest.exists() {
                        self.remove_empty_dirs(sandbox_id, &dest);
                        continue;
                    }
                    if fs::remove_dir(&dest).is_ok() {
                        continue;
                    }
                    /*
                     * Use remove_dir_recursive which fails if non-empty
                     * directories remain, rather than blindly deleting.
                     * First verify the path is within the sandbox.
                     */
                    debug!(
                        sandbox = sandbox_id,
                        action = "copy",
                        dest = %dest.display(),
                        "Removing copied path"
                    );
                    self.verify_path_in_sandbox(sandbox_id, &dest)?;
                    self.remove_dir_recursive(&dest)?;
                    self.remove_empty_dirs(sandbox_id, &dest);
                }
                ActionType::Symlink => {
                    let Some(dest) = dest else { continue };
                    if dest.is_symlink() {
                        debug!(
                            sandbox = sandbox_id,
                            action = "symlink",
                            dest = %dest.display(),
                            "Removing symlink"
                        );
                        fs::remove_file(&dest)?;
                    }
                    self.remove_empty_dirs(sandbox_id, &dest);
                }
                ActionType::Mount => {
                    let Some(dest) = dest else { continue };
                    let fs_type = action.fs_type()?;

                    /*
                     * If the mount point does not exist then do not try
                     * to unmount it, but do try to clean up any empty
                     * parent directories up to the sandbox root.
                     */
                    if !dest.exists() {
                        self.remove_empty_dirs(sandbox_id, &dest);
                        continue;
                    }

                    /*
                     * Try removing the directory first, in case it was
                     * never mounted.  Avoids errors trying to unmount a
                     * filesystem that is not mounted.
                     */
                    if fs::remove_dir(&dest).is_ok() {
                        continue;
                    }

                    /*
                     * Unmount the filesystem.  It is critical that all
                     * mounts are successfully unmounted before we attempt
                     * to remove the sandbox directory.
                     */
                    debug!(
                        sandbox = sandbox_id,
                        action = "mount",
                        fs = ?fs_type,
                        dest = %dest.display(),
                        "Unmounting"
                    );
                    let status = match fs_type {
                        FSType::Bind => self.unmount_bindfs(&dest)?,
                        FSType::Dev => self.unmount_devfs(&dest)?,
                        FSType::Fd => self.unmount_fdfs(&dest)?,
                        FSType::Nfs => self.unmount_nfs(&dest)?,
                        FSType::Proc => self.unmount_procfs(&dest)?,
                        FSType::Tmp => self.unmount_tmpfs(&dest)?,
                    };
                    if let Some(s) = status {
                        if !s.success() {
                            bail!("Failed to unmount {}", dest.display());
                        }
                    }
                    self.remove_empty_dirs(sandbox_id, &dest);
                }
                ActionType::MacosMdnsListener => {
                    #[cfg(not(target_os = "macos"))]
                    bail!("'macos-mdns-listener' action is only supported on macOS");
                    #[cfg(target_os = "macos")]
                    {
                        debug!(
                            sandbox = sandbox_id,
                            action = "macos-mdns-listener",
                            "Destroying mDNS listener"
                        );
                        self.destroy_mdns_listener(sandbox_id)?;
                    }
                }
            }
        }
        Ok(())
    }

    /**
     * Recursively remove a directory by walking it depth-first and removing
     * files and empty directories.  Unlike remove_dir_all, this will fail
     * if it encounters a non-empty directory that cannot be removed, which
     * would indicate an active mount point.
     *
     * IMPORTANT: This function explicitly does NOT follow symlinks to avoid
     * deleting files outside the sandbox via symlink attacks.
     */
    #[allow(clippy::only_used_in_recursion)]
    fn remove_dir_recursive(&self, path: &Path) -> Result<()> {
        // Use symlink_metadata to check type WITHOUT following symlinks
        let meta = fs::symlink_metadata(path)
            .with_context(|| format!("Failed to stat {}", path.display()))?;
        if meta.is_symlink() {
            // Remove the symlink itself, don't follow it
            fs::remove_file(path)
                .with_context(|| format!("Failed to remove {}", path.display()))?;
            return Ok(());
        }
        if !meta.is_dir() {
            fs::remove_file(path)
                .with_context(|| format!("Failed to remove {}", path.display()))?;
            return Ok(());
        }
        let entries =
            fs::read_dir(path).with_context(|| format!("Failed to read {}", path.display()))?;
        for entry in entries {
            let entry = entry?;
            let entry_path = entry.path();
            // Use file_type() from DirEntry which doesn't follow symlinks
            let file_type = entry.file_type()?;
            if file_type.is_symlink() {
                // Remove symlink itself, don't follow
                fs::remove_file(&entry_path)
                    .with_context(|| format!("Failed to remove {}", entry_path.display()))?;
            } else if file_type.is_dir() {
                self.remove_dir_recursive(&entry_path)?;
            } else {
                fs::remove_file(&entry_path)
                    .with_context(|| format!("Failed to remove {}", entry_path.display()))?;
            }
        }
        fs::remove_dir(path).with_context(|| format!("Failed to remove {}", path.display()))?;
        Ok(())
    }
}

/**
 * RAII scope for sandbox lifecycle management.
 *
 * Creates sandboxes on demand via `ensure()`, destroys them on drop.
 * This ensures sandboxes are always cleaned up, even on error paths.
 * If sandboxes are disabled, all operations are no-ops.
 */
#[derive(Debug)]
pub struct SandboxScope {
    sandbox: Sandbox,
    owned: Vec<usize>,
    state: RunState,
}

impl SandboxScope {
    /**
     * Create a new scope with no sandboxes.
     *
     * Use `ensure()` to create sandboxes when needed.
     */
    pub fn new(sandbox: Sandbox, state: RunState) -> Self {
        Self {
            sandbox,
            owned: Vec::new(),
            state,
        }
    }

    /**
     * Ensure at least `n` sandboxes are owned by this scope.
     *
     * Claims available IDs atomically, skipping any already held by other
     * processes.  Sets up new sandboxes in parallel.
     *
     * On error or interrupt, newly created sandboxes are rolled back but
     * previously owned sandboxes remain (they'll be cleaned up on drop).
     */
    pub fn ensure(&mut self, n: usize) -> Result<&[usize]> {
        if n <= self.owned.len() {
            return Ok(&self.owned);
        }
        let needed = n - self.owned.len();
        let new_ids = self.sandbox.claim_ids(needed)?;
        if self.state.interrupted() {
            for &id in &new_ids {
                let _ = self.sandbox.destroy(id);
            }
            return Err(Interrupted.into());
        }
        self.owned.extend(new_ids);
        Ok(&self.owned)
    }

    /**
     * Return the sandbox IDs owned by this scope.
     *
     * Index 0 is the first sandbox allocated, etc.  Use this to map
     * worker indices to sandbox IDs.
     */
    pub fn ids(&self) -> Option<&[usize]> {
        if self.owned.is_empty() {
            None
        } else {
            Some(&self.owned)
        }
    }

    /**
     * Access the underlying sandbox for operations.
     */
    pub fn sandbox(&self) -> &Sandbox {
        &self.sandbox
    }

    /**
     * Return whether sandboxes are enabled.
     */
    pub fn enabled(&self) -> bool {
        self.sandbox.enabled()
    }

    /**
     * Return the number of sandboxes currently managed.
     */
    pub fn count(&self) -> usize {
        self.owned.len()
    }

    /**
     * Access the run state flag.
     */
    pub fn state(&self) -> &RunState {
        &self.state
    }
}

impl Drop for SandboxScope {
    fn drop(&mut self) {
        if !self.sandbox.enabled() || self.owned.is_empty() {
            return;
        }
        let envs = self.sandbox.config.script_env(None);
        for &id in &self.owned {
            if self.sandbox.path(id).exists() {
                match self
                    .sandbox
                    .run_post_build(Some(id), &self.sandbox.config, envs.clone())
                {
                    Ok(true) => {}
                    Ok(false) => {
                        warn!("post-build failed for sandbox {}", id)
                    }
                    Err(e) => {
                        warn!(error = %e, sandbox = id, "post-build error")
                    }
                }
            }
        }
        let msg = if self.owned.len() == 1 {
            "Destroying sandbox".to_string()
        } else {
            format!("Destroying {} sandboxes", self.owned.len())
        };
        crate::print_status(&msg);
        let start = Instant::now();
        let ids = self.owned.clone();
        let results: Vec<(usize, Result<()>)> = ids
            .into_par_iter()
            .map(|id| (id, self.sandbox.destroy(id)))
            .collect();
        let mut failed = 0;
        for (id, result) in results {
            if let Err(e) = result {
                if failed == 0 {
                    println!();
                }
                eprintln!("sandbox {}: {:#}", id, e);
                failed += 1;
            }
        }
        if failed == 0 {
            crate::print_elapsed(&msg, start.elapsed());
        } else {
            eprintln!(
                "Warning: failed to destroy {} sandbox{}",
                failed,
                if failed == 1 { "" } else { "es" }
            );
        }
    }
}