kache 1.2.1

Compiler cache for Rust, C/C++ and CUDA, with S3, GCS, shared-filesystem and OCI remotes.
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
//! Cross-platform helpers for process management and signal handling.
//!
//! The daemon needs to:
//!   - probe whether a recorded PID is still alive (recovery from crashes)
//!   - politely ask another process to exit, then force-kill if it didn't
//!   - wait for an OS-level shutdown signal to flush state and exit cleanly
//!
//! On Unix these all map to libc primitives (kill(2), signal(2)).
//! On Windows they map to OpenProcess/TerminateProcess and the Windows
//! console-control events surfaced by tokio::signal::windows.

/// Is `pid` safe to hand to `kill(2)` as a single-process target?
///
/// `kill(2)` overloads the pid argument with broadcast modes, and a bogus or
/// sentinel PID that lands in one of them takes down far more than the
/// intended process:
///
///   - `pid == 0`: every process in the *caller's* process group
///   - `pid == -1`: every process the caller has permission to signal, i.e.
///     the user's entire login session
///   - `pid < -1`: the process group `-pid`
///   - `pid == 1`: init/launchd, and negating it yields the `-1` broadcast
///
/// Note that `u32::MAX` casts to `-1`, so a "definitely dead, made-up PID"
/// fixture is exactly the value that wipes the session. Reject anything that
/// is not an ordinary positive PID.
#[cfg(unix)]
fn is_single_process_pid(pid: u32) -> bool {
    pid > 1 && i32::try_from(pid).is_ok()
}

/// Refuse a PID that `kill(2)` would treat as a broadcast selector.
///
/// Production logs and carries on — a corrupt pidfile must not take the daemon
/// down. Tests panic instead: a fixture that reaches here is the exact bug this
/// module exists to prevent, and silently no-oping would let it pass green.
#[cfg(unix)]
fn refuse_unsafe_pid(pid: u32, what: &str) {
    tracing::error!(pid, action = what, "refusing to signal a non-process PID");

    #[cfg(test)]
    panic!(
        "test passed PID {pid} to {what}; kill(2) reads that as a broadcast \
         selector (0 = our process group, -1 = every process the user owns). \
         Use a real spawned child, not a sentinel PID."
    );
}

/// Parent of `pid`, or None when that cannot be established — no usable `ps`,
/// or the process is already gone.
#[cfg(all(unix, test))]
fn parent_pid(pid: u32) -> Option<u32> {
    let out = std::process::Command::new("ps")
        .args(["-o", "ppid=", "-p", &pid.to_string()])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    String::from_utf8_lossy(&out.stdout)
        .trim()
        .parse::<u32>()
        .ok()
}

/// Test-only blast radius limit: a unit test may only signal processes it
/// actually spawned.
///
/// The pid guard above rejects the broadcast selectors, but it cannot tell a
/// legitimate target from someone else's PID — and a test that signals a PID
/// it does not own has no correct outcome, only luck. This walks the target's
/// parent chain and refuses anything the test process does not sit above, so
/// a bad fixture fails the test instead of reaching across the machine.
///
/// Compiled only under `cfg(test)`, so production keeps the bare `kill(2)`.
///
/// Fails only on *positive* evidence of non-descent — a chain walked all the
/// way to init without meeting us. Where the chain cannot be resolved at all
/// there is nothing to conclude: the Nix build sandbox ships no `ps`, and
/// treating that silence as "not yours" failed legitimate tests signalling
/// their own children. The value guard above still rejects the broadcast
/// selectors there, which is the catastrophic class; this one is the finer
/// limit and correctly declines to judge without evidence.
#[cfg(all(unix, test))]
fn assert_test_owns_process(pid: u32, what: &str) -> bool {
    let me = std::process::id();
    let mut cursor = pid;

    // Depth-limited: a cycle in the reported parent chain must not hang.
    for _ in 0..64 {
        if cursor == me {
            return true;
        }
        if cursor <= 1 {
            // Reached init having never met ourselves: the target really is
            // somebody else's.
            break;
        }
        let Some(parent) = parent_pid(cursor) else {
            // No usable `ps`, or the process exited mid-walk. Either way we
            // cannot show the target is foreign, so do not claim it is.
            return true;
        };
        cursor = parent;
    }

    panic!(
        "test tried to {what} PID {pid}, which is not a descendant of the test \
         process ({me}). Tests may only signal processes they spawned; a PID \
         from a fixture, a config file, or a `pgrep` sweep belongs to the \
         developer's machine. (A child orphaned before this check — its \
         intermediate parent exited, so init reparented it — also lands here; \
         keep the process you intend to signal a live descendant.)"
    );
}

/// Forcefully kill a process and all its descendants (process group on Unix, process tree on Windows).
pub fn kill_process_group(pid: u32) {
    #[cfg(unix)]
    {
        // `-pid` is the group selector, so pid 1 would negate into the `-1`
        // "signal everything" broadcast and pid 0 into the caller's own group.
        if !is_single_process_pid(pid) {
            refuse_unsafe_pid(pid, "kill_process_group");
            return;
        }
        #[cfg(test)]
        assert_test_owns_process(pid, "SIGKILL the process group of");
        unsafe {
            libc::kill(-(pid as i32), libc::SIGKILL);
        }
    }
    #[cfg(windows)]
    {
        let _ = std::process::Command::new("taskkill")
            .args(["/F", "/T", "/PID", &pid.to_string()])
            .output();
    }
}

/// Current effective UID. Returns `libc::getuid()` on Unix. On Windows
/// there is no equivalent — UIDs are part of macOS launchctl target
/// strings (`gui/{uid}/...`) and that whole code path is macOS-only, so a
/// stub returning 0 keeps the rest of `service.rs` compilable.
#[cfg(unix)]
pub fn current_uid() -> u32 {
    unsafe { libc::getuid() }
}

#[cfg(not(unix))]
pub fn current_uid() -> u32 {
    0
}

/// Raise the soft open-file limit as far as the hard limit allows. launchd
/// starts agents with a soft limit of 256, as does a stock macOS shell, and a
/// daemon serving a parallel build holds a socket and store files per request
/// (#1361). Returns the old and new soft limit when it changed.
#[cfg(unix)]
pub fn raise_open_file_limit() -> std::io::Result<Option<(libc::rlim_t, libc::rlim_t)>> {
    let mut limit = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    // SAFETY: `limit` is a valid output slot for getrlimit.
    if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 {
        return Err(std::io::Error::last_os_error());
    }
    // macOS rejects a soft limit above `kern.maxfilesperproc`, and launchd's
    // hard limit is unlimited.
    #[cfg(target_os = "macos")]
    let cap = Some(macos_max_files_per_proc());
    #[cfg(not(target_os = "macos"))]
    let cap = None;
    let Some(target) = open_file_target(limit.rlim_cur, limit.rlim_max, cap) else {
        return Ok(None);
    };
    let before = limit.rlim_cur;
    limit.rlim_cur = target;
    // SAFETY: `limit` is a valid, initialized rlimit.
    if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) } != 0 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(Some((before, target)))
}

/// The soft limit to ask for: the hard limit, capped by what the kernel lets
/// one process open. `None` when that is no higher than `soft`.
#[cfg(unix)]
fn open_file_target(
    soft: libc::rlim_t,
    hard: libc::rlim_t,
    cap: Option<libc::rlim_t>,
) -> Option<libc::rlim_t> {
    let target = cap.map_or(hard, |cap| hard.min(cap));
    (target > soft).then_some(target)
}

/// `kern.maxfilesperproc`, or OPEN_MAX (the documented safe ceiling) when
/// the sysctl is unreadable.
#[cfg(target_os = "macos")]
fn macos_max_files_per_proc() -> libc::rlim_t {
    let mut value: libc::c_int = 0;
    let mut size = std::mem::size_of::<libc::c_int>();
    // SAFETY: the name is NUL-terminated and `value`/`size` describe a c_int.
    let status = unsafe {
        libc::sysctlbyname(
            c"kern.maxfilesperproc".as_ptr(),
            (&raw mut value).cast(),
            &mut size,
            std::ptr::null_mut(),
            0,
        )
    };
    if status == 0 && value > 0 {
        value as libc::rlim_t
    } else {
        10_240
    }
}

/// Resolve when the OS asks the daemon to stop. SIGTERM/SIGINT on Unix,
/// Ctrl+C / console-close on Windows.
pub async fn wait_for_shutdown() {
    #[cfg(unix)]
    {
        use tokio::signal::unix::{SignalKind, signal};
        let mut sigterm = signal(SignalKind::terminate()).expect("SIGTERM handler");
        let mut sigint = signal(SignalKind::interrupt()).expect("SIGINT handler");
        tokio::select! {
            _ = sigterm.recv() => {}
            _ = sigint.recv() => {}
        }
    }
    #[cfg(windows)]
    {
        use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
        let mut cc = ctrl_c().expect("ctrl_c handler");
        let mut cb = ctrl_break().expect("ctrl_break handler");
        let mut cl = ctrl_close().expect("ctrl_close handler");
        let mut cs = ctrl_shutdown().expect("ctrl_shutdown handler");
        tokio::select! {
            _ = cc.recv() => {}
            _ = cb.recv() => {}
            _ = cl.recv() => {}
            _ = cs.recv() => {}
        }
    }
}

/// Configure a process to be fully detached (in its own process group on Unix,
/// or with detached creation flags on Windows) so that pressing Ctrl-C on the parent
/// does not terminate the child.
pub fn configure_detached_process(cmd: &mut std::process::Command) {
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        // CREATE_NEW_PROCESS_GROUP = 0x00000200
        // DETACHED_PROCESS = 0x00000008
        cmd.creation_flags(0x00000200 | 0x00000008);
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = cmd;
    }
}

/// Put a child in its own process group so a timeout kill reaches its whole
/// tree, WITHOUT detaching it from the console. A .cmd/.bat wrapper runs via
/// cmd.exe, which needs a console; DETACHED_PROCESS makes it exit 0 with no
/// output, so the probe must not use it.
pub fn configure_process_group(cmd: &mut std::process::Command) {
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        // CREATE_NEW_PROCESS_GROUP = 0x00000200
        cmd.creation_flags(0x00000200);
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = cmd;
    }
}

/// Set on a kache process that kache started for one of its own
/// subcommands. The value is that subcommand.
pub const SELF_SPAWN_ENV: &str = "KACHE_SELF_SPAWN";

/// A command that runs the kache binary at `exe` as `kache <subcommand>`.
///
/// Under a compiler-name shim `exe` can be the shim itself: macOS reports
/// the symlink it was started through (`.../shims/cc`), and a Windows shim
/// is a copy named `gcc.exe`. main routes on argv[0] before it parses a
/// subcommand, so the child would run as the compiler. On Unix argv[0] is
/// set to `kache`. Windows cannot set it, so [`SELF_SPAWN_ENV`] tells main
/// which subcommand to expect there, and on Unix as a second guard.
pub fn self_command(exe: &std::path::Path, subcommand: &str) -> std::process::Command {
    let mut cmd = std::process::Command::new(exe);
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.arg0("kache");
    }
    cmd.arg(subcommand).env(SELF_SPAWN_ENV, subcommand);
    cmd
}

/// Whether this process is a [`self_command`] child: [`SELF_SPAWN_ENV`] is
/// set and names the subcommand in argv[1]. Both are required, so a leaked
/// variable cannot turn a compile into a CLI call.
pub fn is_self_spawn(argv: &[String], self_spawn: Option<&std::ffi::OsStr>) -> bool {
    match (argv.get(1), self_spawn) {
        (Some(subcommand), Some(expected)) => std::ffi::OsStr::new(subcommand) == expected,
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    /// Is a usable `ps` on PATH? Tests that assert on the parent-chain walk
    /// need to know before asserting — the Nix build sandbox has none, and
    /// there the guard deliberately allows instead of judging.
    ///
    /// Deliberately does not call `parent_pid`: this is the skip condition for
    /// tests that pin `parent_pid` itself, so routing through it would let a
    /// mutant that stubs it out downgrade those tests to silent skips.
    #[cfg(unix)]
    fn ps_available() -> bool {
        std::env::var_os("PATH")
            .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join("ps").is_file()))
    }

    /// launchd's 256/unlimited must land on the per-process cap, never on
    /// RLIM_INFINITY (which macOS rejects), and a limit that is already as
    /// high as allowed is left alone.
    #[cfg(unix)]
    #[test]
    fn open_file_target_takes_the_hard_limit_up_to_the_cap() {
        use super::open_file_target;
        assert_eq!(
            open_file_target(256, libc::RLIM_INFINITY, Some(61_440)),
            Some(61_440)
        );
        assert_eq!(open_file_target(1024, 524_288, None), Some(524_288));
        assert_eq!(open_file_target(256, 4096, Some(61_440)), Some(4096));
        assert_eq!(open_file_target(4096, 4096, None), None);
        assert_eq!(
            open_file_target(61_440, libc::RLIM_INFINITY, Some(61_440)),
            None
        );
        assert_eq!(open_file_target(8192, 524_288, Some(4096)), None);
    }

    /// Lowering the soft limit is always allowed, so setting it one below
    /// the target gives the raise something to do on any host. A soft limit
    /// already above the target (a shell's `ulimit -n`) is never lowered.
    #[cfg(unix)]
    #[test]
    fn raise_open_file_limit_restores_a_lowered_limit_once() {
        let current = || {
            let mut limit = libc::rlimit {
                rlim_cur: 0,
                rlim_max: 0,
            };
            assert_eq!(
                unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) },
                0
            );
            limit
        };
        #[cfg(target_os = "macos")]
        let cap = Some(super::macos_max_files_per_proc());
        #[cfg(not(target_os = "macos"))]
        let cap = None;
        let mut limit = current();
        let target = super::open_file_target(0, limit.rlim_max, cap).unwrap();
        limit.rlim_cur = target - 1;
        assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }, 0);
        assert_eq!(
            super::raise_open_file_limit().unwrap(),
            Some((target - 1, target))
        );
        assert_eq!(current().rlim_cur, target);
        assert_eq!(super::raise_open_file_limit().unwrap(), None);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_cap_reads_kern_maxfilesperproc() {
        // The Nix build sandbox has no sysctl binary; `Test (macOS)` runs this.
        let Ok(out) = std::process::Command::new("/usr/sbin/sysctl")
            .args(["-n", "kern.maxfilesperproc"])
            .output()
        else {
            return;
        };
        let expected: libc::rlim_t = String::from_utf8(out.stdout)
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        assert_eq!(super::macos_max_files_per_proc(), expected);
    }

    /// The program stays the path kache was started through; only argv
    /// changes, so the child is the same binary under the name `kache`.
    #[test]
    fn self_command_names_the_subcommand_in_argv_and_the_environment() {
        let exe = std::path::Path::new("/x/shims/cc");
        let cmd = super::self_command(exe, "gc");
        assert_eq!(cmd.get_program(), exe.as_os_str());
        let args: Vec<_> = cmd.get_args().collect();
        assert_eq!(args, ["gc"]);
        let marker = cmd
            .get_envs()
            .find(|(name, _)| *name == super::SELF_SPAWN_ENV)
            .and_then(|(_, value)| value);
        assert_eq!(marker, Some(std::ffi::OsStr::new("gc")));
    }

    /// Prints this process's argv[0] when run as a child of
    /// [`self_command_runs_as_kache_on_unix`]. On stderr: with one test
    /// thread, libtest puts its own progress text on the same stdout line.
    #[cfg(unix)]
    #[test]
    #[ignore = "child fixture for self_command_runs_as_kache_on_unix"]
    fn print_argv0_fixture() {
        if std::env::var_os("KACHE_TEST_PRINT_ARGV0").is_some() {
            eprintln!("argv0={}", std::env::args().next().unwrap_or_default());
        }
    }

    /// std has no getter for argv[0], so a real child reports it. The child
    /// is this test binary: a shell can be a multi-call binary (busybox in
    /// the Nix build) that picks its applet from argv[0].
    #[cfg(unix)]
    #[test]
    fn self_command_runs_as_kache_on_unix() {
        let exe = std::env::current_exe().unwrap();
        let output = super::self_command(&exe, "--exact")
            .args([
                "platform::tests::print_argv0_fixture",
                "--ignored",
                "--nocapture",
            ])
            .env("KACHE_TEST_PRINT_ARGV0", "1")
            .output()
            .unwrap();
        assert!(output.status.success(), "{output:?}");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.lines().any(|line| line == "argv0=kache"),
            "argv[0] must be kache, not the path the program was started from: {stderr}"
        );
    }

    fn argv(args: &[&str]) -> Vec<String> {
        args.iter().map(|arg| arg.to_string()).collect()
    }

    #[test]
    fn self_spawn_needs_the_marker_to_name_argv1() {
        use std::ffi::OsStr;
        let gc = Some(OsStr::new("gc"));
        assert!(super::is_self_spawn(&argv(&["/x/shims/cc", "gc"]), gc));
        assert!(super::is_self_spawn(
            &argv(&["gcc.exe", "daemon", "run"]),
            Some(OsStr::new("daemon"))
        ));
        // A user compile under a leaked marker stays a compile.
        assert!(!super::is_self_spawn(&argv(&["cc", "foo.c"]), gc));
        // The subcommand without the marker is a compile of a file named gc.
        assert!(!super::is_self_spawn(&argv(&["cc", "gc"]), None));
        assert!(!super::is_self_spawn(&argv(&["cc"]), gc));
        assert!(!super::is_self_spawn(&[], gc));
    }

    #[cfg(unix)]
    #[test]
    fn broadcast_pids_are_not_single_process_targets() {
        // The kill(2) broadcast selectors. `u32::MAX` is the dangerous one:
        // it casts to -1, which signals the user's entire session.
        for pid in [0, 1, u32::MAX] {
            assert!(
                !super::is_single_process_pid(pid),
                "pid {pid} must never be signalled as a single process"
            );
        }
        assert!(super::is_single_process_pid(std::process::id()));
    }

    #[cfg(unix)]
    #[test]
    fn signalling_a_process_the_test_does_not_own_panics() {
        // Needs a working `ps`: without one the guard deliberately allows
        // rather than judging, so there is nothing to assert. The Nix build
        // sandbox has no `ps`; the mutation and Test lanes do.
        //
        // Probe for the tool directly rather than asking `parent_pid`, which
        // is part of what this test pins: gating on it would let a mutant that
        // stubs it out silently turn this test into a skip.
        if !ps_available() {
            return;
        }

        // The test runner that spawned us: a live PID, definitely not ours.
        // `assert_test_owns_process` only inspects the parent chain — it
        // never signals — so this stays harmless even if the check regresses.
        let parent = unsafe { libc::getppid() } as u32;
        let outcome =
            std::panic::catch_unwind(|| super::assert_test_owns_process(parent, "SIGTERM"));

        let panic_msg = *outcome
            .expect_err("signalling a non-descendant must fail the test")
            .downcast::<String>()
            .expect("guard panics with a message");
        assert!(
            panic_msg.contains("not a descendant of the test process"),
            "unexpected panic message: {panic_msg}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn owning_a_process_is_not_claimed_without_evidence() {
        // The complement of the test above: where the parent chain cannot be
        // resolved the guard must allow, not panic. Pin it against a PID that
        // no `ps` can answer for, which is the same shape as the missing-`ps`
        // sandbox and the reaped-child race.
        let mut child = std::process::Command::new("sleep")
            .arg("30")
            .spawn()
            .expect("spawn sleep");
        let pid = child.id();
        child.kill().expect("kill child");
        child.wait().expect("reap child");

        assert!(
            super::assert_test_owns_process(pid, "probe"),
            "an unresolvable chain must not be reported as foreign"
        );
    }

    #[cfg(unix)]
    #[test]
    #[should_panic(expected = "broadcast")]
    fn a_broadcast_pid_fails_the_test_that_supplied_it() {
        // `refuse_unsafe_pid` contains no kill call at all, so exercising the
        // rejection path here is safe even if every other guard regresses.
        super::refuse_unsafe_pid(u32::MAX, "terminate_process");
    }

    // Deliberately NOT tested: calling `terminate_process(u32::MAX)` and
    // asserting a bystander process survived. That test passes by doing
    // nothing and fails by killing the developer's entire login session —
    // and this repo runs cargo-mutants, which would build exactly the
    // compromised guard that makes it fire (see kunobi-ninja/kache history
    // for the session-wipe this module now prevents). The guard is a plain
    // early return over `is_single_process_pid`, so pinning the predicate
    // above pins the behaviour without arming a live round.

    #[cfg(unix)]
    #[test]
    fn current_uid_matches_libc_getuid() {
        let expected = unsafe { libc::getuid() };
        assert_eq!(super::current_uid(), expected);
    }

    #[cfg(not(unix))]
    #[test]
    fn current_uid_is_stub_zero_off_unix() {
        assert_eq!(super::current_uid(), 0);
    }
}