boxlite 0.10.1

Embeddable virtual machine runtime for secure, isolated code execution
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
//! On-disk record of a running shim's identity (`shim.pid`).
//!
//! Three public types:
//! * [`PidRecord`] — the on-disk format. Owns encode/decode and the
//!   "capture current process" factory. All methods on it are
//!   async-signal-safe except [`PidRecord::decode`], which allocates.
//! * [`PidFileReader`] — parent-side handle for reading and managing
//!   the file. May allocate, log, take locks.
//! * [`PidFileWriter`] — pre-allocated, async-signal-safe writer.
//!   Construct via [`PidFileWriter::at`] in the parent before fork; the
//!   resulting handle is safe to capture in a `pre_exec` closure and
//!   invoke from the child without further allocation.
//!
//! ## Format
//!
//! ```text
//! <pid>
//! <start_time>           (optional; absent in legacy files)
//! services-mux-v1        (optional; emitted by shims with runtime port control)
//! ```
//!
//! Line 2 is the OS-reported process start-time fingerprint captured at
//! spawn. Recovery compares it against the live PID's current
//! start-time — a mismatch reliably detects PID reuse.
//! Line 3 is deliberately backward compatible: older readers ignore it,
//! while newer readers use it to distinguish a legacy shim's custom port
//! listeners from ServicesMux-owned forwards.

use std::ffi::CString;
use std::path::{Path, PathBuf};

use boxlite_shared::errors::{BoxliteError, BoxliteResult};

/// Max bytes any encoded [`PidRecord`] can produce. PID is u32 (≤10
/// digits), start-time is u64 (≤20 digits), plus two newlines.
pub const PID_RECORD_MAX_BYTES: usize = 48;

const RUNTIME_PORT_CONTROL_CAPABILITY: &[u8] = b"services-mux-v1";
const SHIM_PID_RECORD_MAX_BYTES: usize =
    PID_RECORD_MAX_BYTES + RUNTIME_PORT_CONTROL_CAPABILITY.len() + 1;

// ============================================================================
// PID RECORD — the codec
// ============================================================================

/// On-disk identity of a shim process: its PID and (optionally) the
/// start-time fingerprint captured at spawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PidRecord {
    pub pid: u32,
    /// Start-time fingerprint. `None` for legacy single-line files;
    /// `Some` for the new two-line format.
    pub start_time: Option<u64>,
}

impl PidRecord {
    /// Capture the current process's PID + start-time.
    ///
    /// Async-signal-safe: uses only `getpid()` and a stack-buffer parse
    /// of `/proc/self/stat` (Linux) or `proc_pidinfo` (macOS). Safe to
    /// call from a `pre_exec` closure.
    pub fn current() -> Self {
        let pid = unsafe { libc::getpid() } as u32;
        let start_time = read_self_start_time_raw();
        Self { pid, start_time }
    }

    /// Parse bytes into a record. Accepts both single-line (`PID\n`)
    /// and two-line (`PID\nSTART_TIME\n`) formats. Returns
    /// [`BoxliteError::Storage`] for empty or unparseable input.
    pub fn decode(bytes: &[u8]) -> BoxliteResult<Self> {
        let text = std::str::from_utf8(bytes)
            .map_err(|e| BoxliteError::Storage(format!("PID file is not valid UTF-8: {e}")))?;
        let mut lines = text.lines();
        let pid_line = lines.next().unwrap_or("").trim();
        let pid: u32 = pid_line
            .parse()
            .map_err(|e| BoxliteError::Storage(format!("Invalid PID '{pid_line}': {e}")))?;
        // A garbled second line downgrades to legacy (None) rather than
        // failing — the PID is still trustworthy.
        let start_time = lines
            .next()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .and_then(|s| s.parse::<u64>().ok());
        Ok(Self { pid, start_time })
    }

    /// Encode into a caller-provided stack buffer; returns bytes written.
    ///
    /// Async-signal-safe. The buffer must be at least
    /// [`PID_RECORD_MAX_BYTES`] long.
    pub fn encode(&self, buf: &mut [u8]) -> usize {
        debug_assert!(buf.len() >= PID_RECORD_MAX_BYTES);
        let mut pos = format_u64(self.pid as u64, buf, 0);
        buf[pos] = b'\n';
        pos += 1;
        if let Some(st) = self.start_time {
            pos = format_u64(st, buf, pos);
            buf[pos] = b'\n';
            pos += 1;
        }
        pos
    }
}

/// Internal shim lifecycle record: process identity plus capabilities written
/// at the child pre-exec boundary.
///
/// Keeping the capability in `shim.pid` makes identity publication the commit
/// point. Recovery can never observe a new live PID without also knowing which
/// port-forwarding implementation that exact shim lifecycle owns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ShimPidRecord {
    identity: PidRecord,
    has_runtime_port_control: bool,
}

impl ShimPidRecord {
    pub(crate) fn current() -> Self {
        Self {
            identity: PidRecord::current(),
            has_runtime_port_control: true,
        }
    }

    #[cfg(test)]
    pub(crate) fn legacy(identity: PidRecord) -> Self {
        Self {
            identity,
            has_runtime_port_control: false,
        }
    }

    #[cfg(test)]
    pub(crate) fn with_runtime_port_control(identity: PidRecord) -> Self {
        Self {
            identity,
            has_runtime_port_control: true,
        }
    }

    pub(crate) fn identity(&self) -> PidRecord {
        self.identity
    }

    pub(crate) fn has_runtime_port_control(&self) -> bool {
        self.has_runtime_port_control
    }

    fn decode(bytes: &[u8]) -> BoxliteResult<Self> {
        let identity = PidRecord::decode(bytes)?;
        let text = std::str::from_utf8(bytes)
            .map_err(|e| BoxliteError::Storage(format!("PID file is not valid UTF-8: {e}")))?;
        let has_runtime_port_control = text
            .lines()
            .nth(2)
            .is_some_and(|line| line.trim() == "services-mux-v1");
        Ok(Self {
            identity,
            has_runtime_port_control,
        })
    }

    fn encode(&self, buf: &mut [u8]) -> usize {
        debug_assert!(buf.len() >= SHIM_PID_RECORD_MAX_BYTES);
        let mut pos = self.identity.encode(buf);
        if self.has_runtime_port_control {
            // Capability is always line 3. Preserve the empty start-time line
            // on platforms where the OS fingerprint is unavailable.
            if self.identity.start_time.is_none() {
                buf[pos] = b'\n';
                pos += 1;
            }
            let end = pos + RUNTIME_PORT_CONTROL_CAPABILITY.len();
            buf[pos..end].copy_from_slice(RUNTIME_PORT_CONTROL_CAPABILITY);
            pos = end;
            buf[pos] = b'\n';
            pos += 1;
        }
        pos
    }
}

// ============================================================================
// PID FILE READER — parent-side I/O
// ============================================================================

/// Parent-side reader for a `shim.pid` file. Read-only; lifecycle ops
/// (existence checks, removal) are direct filesystem calls on the path.
#[derive(Debug, Clone)]
pub struct PidFileReader {
    path: PathBuf,
}

impl PidFileReader {
    pub fn at(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    pub fn read(&self) -> BoxliteResult<PidRecord> {
        Ok(self.read_shim()?.identity())
    }

    pub(crate) fn read_shim(&self) -> BoxliteResult<ShimPidRecord> {
        let bytes = std::fs::read(&self.path).map_err(|e| {
            BoxliteError::Storage(format!(
                "Failed to read PID file {}: {e}",
                self.path.display(),
            ))
        })?;
        ShimPidRecord::decode(&bytes)
    }

    /// Return the verified lifecycle together with the shim's capabilities.
    /// This is the trust boundary for runtime operations that must not attach
    /// to a recycled PID or attribute resources to the wrong VM lifecycle.
    pub(crate) fn verified_shim(&self) -> Option<ShimPidRecord> {
        let record = self.read_shim().ok()?;
        let identity = record.identity();
        let expected_start_time = identity.start_time?;
        if !crate::util::is_process_alive(identity.pid)
            || crate::util::process_start_time(identity.pid) != Some(expected_start_time)
        {
            return None;
        }
        Some(record)
    }

    /// Read the PID file and classify the recorded process against the
    /// live OS view. `Absent` collapses three failure modes (file gone,
    /// process dead, fingerprint mismatch) — all map to "nothing to act on".
    pub fn process_identity(&self) -> ProcessIdentity {
        let Ok(record) = self.read() else {
            return ProcessIdentity::Absent;
        };
        if !crate::util::is_process_alive(record.pid) {
            return ProcessIdentity::Absent;
        }
        match record.start_time {
            None => ProcessIdentity::Legacy(record.pid),
            Some(expected) if crate::util::process_start_time(record.pid) == Some(expected) => {
                ProcessIdentity::Verified(record.pid)
            }
            Some(_) => ProcessIdentity::Absent,
        }
    }
}

// ============================================================================
// PROCESS IDENTITY — classification of a recorded PID against the live OS
// ============================================================================

/// Result of comparing a recorded `shim.pid` entry to the live OS state.
///
/// Variants carry the PID only when it's safe to act on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessIdentity {
    /// Alive + recorded start-time matches the OS reading.
    Verified(u32),
    /// Alive + no start-time recorded (pre-fingerprint legacy file).
    /// Safe to adopt with a warning; cannot prove identity.
    Legacy(u32),
    /// No actionable shim: file missing, process dead, or fingerprint
    /// differs (PID reuse).
    Absent,
}

// ============================================================================
// PID FILE WRITER — pre-allocated, async-signal-safe child-side I/O
// ============================================================================

/// Async-signal-safe writer for a `shim.pid` file.
///
/// Construct in the parent before fork via [`PidFileWriter::at`]; the
/// returned handle owns a pre-allocated `CString` for the path. Capture
/// the handle in a `pre_exec` closure and call [`PidFileWriter::write_shim`]
/// from the child — no further allocation is performed.
///
/// Internal: the record it writes is a [`ShimPidRecord`], whose capability
/// line the runtime owns. Readers outside the crate use [`PidFileReader`].
#[derive(Debug, Clone)]
pub(crate) struct PidFileWriter {
    path: CString,
}

impl PidFileWriter {
    /// Validate the path and pre-allocate its `CString` form. Call from
    /// the parent before fork; fails if the path contains interior NUL.
    pub(crate) fn at(path: &Path) -> BoxliteResult<Self> {
        let cstr = CString::new(path.to_string_lossy().as_bytes()).map_err(|e| {
            BoxliteError::Storage(format!(
                "PID file path {} contains interior NUL: {e}",
                path.display(),
            ))
        })?;
        Ok(Self { path: cstr })
    }

    /// Write `record` to the file. Async-signal-safe: uses only
    /// `open`/`write`/`close` syscalls and a stack buffer.
    pub(crate) fn write_shim(&self, record: &ShimPidRecord) -> Result<(), i32> {
        let mut buf = [0u8; SHIM_PID_RECORD_MAX_BYTES];
        let len = record.encode(&mut buf);
        self.write_bytes(&buf[..len])
    }

    fn write_bytes(&self, bytes: &[u8]) -> Result<(), i32> {
        unsafe {
            let fd = libc::open(
                self.path.as_ptr(),
                libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC,
                0o644 as libc::c_uint,
            );
            if fd < 0 {
                return Err(errno());
            }

            let mut offset = 0;
            let mut write_errno = None;
            while offset < bytes.len() {
                let written = libc::write(
                    fd,
                    bytes[offset..].as_ptr() as *const libc::c_void,
                    bytes.len() - offset,
                );
                if written > 0 {
                    offset += written as usize;
                    continue;
                }
                if written < 0 {
                    let error = errno();
                    if error == libc::EINTR {
                        continue;
                    }
                    write_errno = Some(error);
                } else {
                    write_errno = Some(libc::EIO);
                }
                break;
            }
            if libc::close(fd) < 0 && write_errno.is_none() {
                write_errno = Some(errno());
            }
            if let Some(e) = write_errno {
                return Err(e);
            }
        }
        Ok(())
    }
}

// ============================================================================
// PRIVATE HELPERS — all async-signal-safe
// ============================================================================

/// `errno()` for the current thread; async-signal-safe.
unsafe fn errno() -> i32 {
    #[cfg(target_os = "linux")]
    unsafe {
        *libc::__errno_location()
    }
    #[cfg(target_os = "macos")]
    unsafe {
        *libc::__error()
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        0
    }
}

/// Format a u64 in decimal into `buf` starting at `offset`; returns the
/// new write position. Async-signal-safe, no allocation.
fn format_u64(mut value: u64, buf: &mut [u8], offset: usize) -> usize {
    if value == 0 {
        buf[offset] = b'0';
        return offset + 1;
    }
    let mut tmp = [0u8; 24];
    let mut len = 0;
    while value > 0 {
        tmp[len] = b'0' + (value % 10) as u8;
        value /= 10;
        len += 1;
    }
    let mut pos = offset;
    for i in 0..len {
        buf[pos] = tmp[len - 1 - i];
        pos += 1;
    }
    pos
}

#[cfg(target_os = "linux")]
fn read_self_start_time_raw() -> Option<u64> {
    let path = c"/proc/self/stat";
    unsafe {
        let fd = libc::open(path.as_ptr(), libc::O_RDONLY);
        if fd < 0 {
            return None;
        }
        let mut buf = [0u8; 1024];
        let n = libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len());
        libc::close(fd);
        if n <= 0 {
            return None;
        }
        parse_start_time_from_stat(&buf[..n as usize])
    }
}

#[cfg(target_os = "linux")]
fn parse_start_time_from_stat(slice: &[u8]) -> Option<u64> {
    // /proc/PID/stat: PID (COMM) STATE PPID ... START_TIME(22) ...
    // COMM may contain spaces/close-parens; split on the LAST `)`.
    let close = slice.iter().rposition(|&b| b == b')')?;
    let tail = &slice[close + 1..];
    let mut field_idx = 0usize;
    let mut i = 0;
    while i < tail.len() {
        while i < tail.len() && tail[i] == b' ' {
            i += 1;
        }
        let start = i;
        while i < tail.len() && tail[i] != b' ' && tail[i] != b'\n' {
            i += 1;
        }
        if start == i {
            return None;
        }
        field_idx += 1;
        // STARTTIME is field 22 in the full line; tail consumed pid+comm,
        // so it's field 20 here.
        if field_idx == 20 {
            let mut value: u64 = 0;
            for &b in &tail[start..i] {
                if !b.is_ascii_digit() {
                    return None;
                }
                value = value.checked_mul(10)?.checked_add((b - b'0') as u64)?;
            }
            return Some(value);
        }
    }
    None
}

#[cfg(target_os = "macos")]
fn read_self_start_time_raw() -> Option<u64> {
    let mut info = std::mem::MaybeUninit::<libc::proc_bsdinfo>::uninit();
    let expected_size = std::mem::size_of::<libc::proc_bsdinfo>() as i32;
    let bytes = unsafe {
        libc::proc_pidinfo(
            libc::getpid(),
            libc::PROC_PIDTBSDINFO,
            0,
            info.as_mut_ptr().cast(),
            expected_size,
        )
    };
    if bytes != expected_size {
        return None;
    }
    let info = unsafe { info.assume_init() };
    Some(info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec)
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn read_self_start_time_raw() -> Option<u64> {
    None
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn temp_with(content: &str) -> NamedTempFile {
        let mut f = NamedTempFile::new().expect("tempfile");
        f.write_all(content.as_bytes()).expect("write");
        f.flush().expect("flush");
        f
    }

    // ---- PidRecord codec ----------------------------------------------------

    #[test]
    fn decode_two_line_format() {
        let r = PidRecord::decode(b"1234\n98765432\n").expect("decode");
        assert_eq!(r.pid, 1234);
        assert_eq!(r.start_time, Some(98765432));
    }

    #[test]
    fn decode_legacy_one_line_format() {
        let r = PidRecord::decode(b"4321\n").expect("decode");
        assert_eq!(r.pid, 4321);
        assert_eq!(r.start_time, None);
    }

    #[test]
    fn decode_no_trailing_newline() {
        let r = PidRecord::decode(b"67890").expect("decode");
        assert_eq!(r.pid, 67890);
        assert_eq!(r.start_time, None);
    }

    #[test]
    fn decode_corrupt_start_time_downgrades() {
        let r = PidRecord::decode(b"5555\nnot-a-number\n").expect("decode");
        assert_eq!(r.pid, 5555);
        assert_eq!(r.start_time, None);
    }

    #[test]
    fn decode_leading_whitespace_pid() {
        let r = PidRecord::decode(b"  12345\n  88  \n").expect("decode");
        assert_eq!(r.pid, 12345);
        assert_eq!(r.start_time, Some(88));
    }

    #[test]
    fn decode_max_linux_pid() {
        let r = PidRecord::decode(b"4194304\n").expect("decode");
        assert_eq!(r.pid, 4194304);
    }

    #[test]
    fn decode_negative_pid_rejected() {
        assert!(PidRecord::decode(b"-1\n").is_err());
    }

    #[test]
    fn decode_overflow_pid_rejected() {
        assert!(PidRecord::decode(b"99999999999\n").is_err());
    }

    #[test]
    fn decode_invalid_pid_rejected() {
        assert!(PidRecord::decode(b"not-a-pid\n").is_err());
    }

    #[test]
    fn decode_empty_rejected() {
        assert!(PidRecord::decode(b"").is_err());
    }

    #[test]
    fn encode_round_trips_with_start_time() {
        let r = PidRecord {
            pid: 12345,
            start_time: Some(67890),
        };
        let mut buf = [0u8; PID_RECORD_MAX_BYTES];
        let len = r.encode(&mut buf);
        assert_eq!(&buf[..len], b"12345\n67890\n");
        assert_eq!(PidRecord::decode(&buf[..len]).unwrap(), r);
    }

    #[test]
    fn encode_round_trips_legacy() {
        let r = PidRecord {
            pid: 7,
            start_time: None,
        };
        let mut buf = [0u8; PID_RECORD_MAX_BYTES];
        let len = r.encode(&mut buf);
        assert_eq!(&buf[..len], b"7\n");
        assert_eq!(PidRecord::decode(&buf[..len]).unwrap(), r);
    }

    #[test]
    fn current_captures_self() {
        let r = PidRecord::current();
        assert_eq!(r.pid, std::process::id());
        // start_time may be None on unsupported OS; on Linux/macOS must
        // be present.
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        assert!(r.start_time.is_some(), "start_time must be captured");
    }

    #[test]
    fn shim_record_round_trips_runtime_port_control() {
        let record = ShimPidRecord::with_runtime_port_control(PidRecord {
            pid: 12345,
            start_time: Some(67890),
        });
        let mut buf = [0u8; SHIM_PID_RECORD_MAX_BYTES];
        let len = record.encode(&mut buf);

        assert_eq!(&buf[..len], b"12345\n67890\nservices-mux-v1\n");
        assert_eq!(ShimPidRecord::decode(&buf[..len]).unwrap(), record);
    }

    #[test]
    fn shim_record_without_start_time_round_trips_runtime_port_control() {
        let record = ShimPidRecord::with_runtime_port_control(PidRecord {
            pid: 7,
            start_time: None,
        });
        let mut buf = [0u8; SHIM_PID_RECORD_MAX_BYTES];
        let len = record.encode(&mut buf);

        assert_eq!(&buf[..len], b"7\n\nservices-mux-v1\n");
        assert_eq!(ShimPidRecord::decode(&buf[..len]).unwrap(), record);
    }

    #[test]
    fn legacy_shim_record_has_no_runtime_port_control() {
        let record = ShimPidRecord::decode(b"4321\n98765432\n").unwrap();

        assert_eq!(
            record.identity(),
            PidRecord {
                pid: 4321,
                start_time: Some(98765432),
            }
        );
        assert!(!record.has_runtime_port_control());
    }

    // ---- PidFileReader ------------------------------------------------------

    #[test]
    fn reader_read_round_trips() {
        let f = temp_with("1234\n98765432\n");
        let r = PidFileReader::at(f.path()).read().expect("read");
        assert_eq!(r.pid, 1234);
        assert_eq!(r.start_time, Some(98765432));
    }

    #[test]
    fn reader_missing_file_is_storage_error() {
        let err = PidFileReader::at("/nonexistent/shim.pid")
            .read()
            .unwrap_err();
        assert!(matches!(err, BoxliteError::Storage(_)));
    }

    // ---- PidFileWriter ------------------------------------------------------

    #[test]
    fn writer_writes_record_readable_by_reader() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("shim.pid");
        let writer = PidFileWriter::at(&path).expect("at");
        let record = ShimPidRecord::with_runtime_port_control(PidRecord {
            pid: 999,
            start_time: Some(424242),
        });
        writer.write_shim(&record).expect("write");

        let read_back = PidFileReader::at(&path).read_shim().expect("read");
        assert_eq!(read_back, record);
    }

    #[test]
    fn writer_truncates_on_repeated_write() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("shim.pid");
        let writer = PidFileWriter::at(&path).expect("at");
        writer
            .write_shim(&ShimPidRecord::with_runtime_port_control(PidRecord {
                pid: 111111,
                start_time: Some(1),
            }))
            .expect("first write");
        // Shorter than the first record on every line, so a stale tail would
        // survive without O_TRUNC.
        writer
            .write_shim(&ShimPidRecord::legacy(PidRecord {
                pid: 22,
                start_time: None,
            }))
            .expect("second write");

        let read_back = PidFileReader::at(&path).read_shim().expect("read");
        assert_eq!(read_back.identity().pid, 22);
        assert_eq!(read_back.identity().start_time, None);
        assert!(!read_back.has_runtime_port_control());
    }

    #[test]
    fn writer_rejects_path_with_interior_nul() {
        // PathBuf::new() with a NUL byte; CString::new will reject.
        let p = std::path::PathBuf::from("/tmp/\0bad");
        let err = PidFileWriter::at(&p).unwrap_err();
        assert!(matches!(err, BoxliteError::Storage(_)));
    }
}