running-process-platform-internal 4.10.11

Blessed platform process operations for running-process (implementation detail)
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
//! Linux implementation root for the process capability.

#[path = "platform_linux/autostart.rs"]
pub(crate) mod autostart;

#[path = "platform_linux/resources.rs"]
pub(crate) mod resources;
pub use resources::{
    fd_exhaustion_error as resources_fd_exhaustion_error,
    inode_capacity as resources_inode_capacity,
    signals_fd_exhaustion as resources_signals_fd_exhaustion,
    signals_storage_exhaustion as resources_signals_storage_exhaustion,
    storage_exhaustion_error as resources_storage_exhaustion_error,
};

pub use autostart::{
    register as autostart_register,
    render_registration as autostart_render_registration,
    unregister as autostart_unregister,
};

#[path = "platform_linux/process_inspect.rs"]
pub(crate) mod process_inspect;
pub use process_inspect::{
    process_executable_path, process_force_kill, process_same_executable_path,
    process_signal_terminate, ProcessLiveness,
};

#[path = "platform_linux/raw_write.rs"]
pub(crate) mod raw_write;
pub use raw_write::write_all_to_descriptor as fs_write_all_to_descriptor;

#[path = "platform_linux/shutdown_request.rs"]
pub(crate) mod shutdown_request;
pub use shutdown_request::install_shutdown_request_handler as process_install_shutdown_request_handler;

#[path = "platform_linux/process_owner_death.rs"]
pub(crate) mod process_owner_death;
pub use process_owner_death::{
    install_owner_death_cleanup as process_install_owner_death_cleanup,
    owner_death_cleanup_target as process_owner_death_cleanup_target,
};

#[path = "platform_linux/host.rs"]
pub(crate) mod host;
pub use host::{
    boot_id as host_boot_id, current_process_privilege as host_current_process_privilege,
    environment_keys_are_case_insensitive as host_environment_keys_are_case_insensitive,
    filesystem_device_id as host_filesystem_device_id, hostname as host_hostname,
    login_environment as host_login_environment, machine_id as host_machine_id,
    namespace_id as host_namespace_id, user_machine_identity as host_user_machine_identity,
    PrivilegedIdentity as HostPrivilegedIdentity,
};
pub use host::login_environment_block as host_login_environment_block;

#[cfg(feature = "fs")]
#[path = "platform_linux/fs.rs"]
pub(crate) mod fs;
#[cfg(feature = "fs")]
pub use fs::{
    create_private_file as fs_create_private_file,
    decode_path_bytes as fs_decode_path_bytes,
    replace_file as fs_replace_file, sync_directory as fs_sync_directory,
    user_config_dir as fs_user_config_dir,
    user_data_dir as fs_user_data_dir, encode_path_bytes as fs_encode_path_bytes,
    file_identity as fs_file_identity, is_lock_conflict as fs_is_lock_conflict,
    open_lock_file as fs_open_lock_file, path_identity as fs_path_identity,
    try_lock_exclusive as fs_try_lock_exclusive, unlock as fs_unlock,
    user_run_data_root as fs_user_run_data_root, user_runtime_dir as fs_user_runtime_dir,
    user_state_dir as fs_user_state_dir, FileIdentity as FsFileIdentity,
};

#[path = "platform_linux/executable.rs"]
pub(crate) mod executable;
pub use executable::{
    file_name as executable_file_name,
    sibling_of_current_image as executable_sibling_of_current_image,
    EXECUTABLE_EXTENSION,
};

#[cfg(feature = "ipc")]
#[path = "platform_linux/ipc.rs"]
pub(crate) mod ipc;
#[cfg(feature = "private-dir")]
#[path = "platform_linux/ipc_private_dir.rs"]
mod ipc_private_dir;
#[cfg(feature = "ipc")]
pub use ipc::{
    current_user_id as ipc_current_user_id, Endpoint as IpcEndpoint,
    endpoint_is_filesystem_backed as ipc_endpoint_is_filesystem_backed,
    nonblocking_zero_read_is_pending as ipc_nonblocking_zero_read_is_pending,
    select_endpoint_address as ipc_select_endpoint_address,
    InheritedListener as IpcInheritedListener, Listener as IpcListener,
    ListenerNonblockingMode as IpcListenerNonblockingMode, PeerIdentity as IpcPeerIdentity,
    PeerIdentitySource as IpcPeerIdentitySource, Stream as IpcStream,
};
#[cfg(feature = "ipc")]
pub const LEGACY_SCM_RIGHTS_TRANSPORT_SUPPORTED: bool = true;
#[cfg(feature = "ipc")]
pub const LEGACY_DUPLICATE_HANDLE_TRANSPORT_SUPPORTED: bool = false;
#[cfg(feature = "ipc")]
pub use ipc::{legacy_send_fd_over, legacy_send_fd_to};
#[cfg(feature = "ipc")]
pub fn legacy_duplicate_handle(
    _source_handle: usize,
    _backend_pid: u32,
) -> Result<usize, crate::LegacyHandoffError> {
    Err(crate::LegacyHandoffError::new(
        crate::platform::ipc::HandoffTransferErrorKind::Unsupported,
        None,
    ))
}
#[cfg(feature = "private-dir")]
pub use ipc_private_dir::{
    ensure_owner_private_directory as private_dir_ensure_owner_private_directory,
    owner_private_directory as private_dir_owner_private_directory,
};
#[cfg(feature = "ipc")]
pub fn ipc_broker_endpoint_name(bare_name: &str, path_scoped: bool) -> std::io::Result<String> {
    use std::fmt::Write as _;
    use std::path::PathBuf;

    if path_scoped {
        let mut hash = blake3::Hasher::new();
        hash.update(b"running-process:path-scoped-socket:v1\0");
        hash.update(bare_name.as_bytes());
        let mut leaf = String::with_capacity(32);
        for byte in hash.finalize().as_bytes().iter().take(16) { let _ = write!(leaf, "{byte:02x}"); }
        return Ok(PathBuf::from("/tmp").join(format!(".rp-path-{leaf}.sock")).to_string_lossy().into_owned());
    }
    let directory = match std::env::var_os("XDG_RUNTIME_DIR") {
        Some(value) => PathBuf::from(value).join("running-process").join("broker-v2"),
        None => PathBuf::from(format!("/tmp/running-process-{}/broker-v2", unsafe { libc::getuid() })),
    };
    Ok(directory.join(format!("{bare_name}.sock")).to_string_lossy().into_owned())
}

/// Linux `sun_path` is 108 bytes including the NUL terminator.
#[cfg(feature = "ipc")]
const LINUX_SUN_PATH_MAX: usize = 108;

#[cfg(feature = "ipc")]
pub fn ipc_endpoint_name_limit() -> crate::platform::ipc::EndpointNameLimit {
    crate::platform::ipc::EndpointNameLimit {
        max_bytes: LINUX_SUN_PATH_MAX,
        label: "Linux sun_path",
    }
}

/// Directory holding v1 broker sockets.
///
/// Deliberately performs no filesystem writes: name derivation stays pure so
/// the hash and length-limit tests remain deterministic. Callers that bind
/// create the parent directory themselves.
#[cfg(feature = "ipc")]
fn broker_v1_socket_dir() -> std::path::PathBuf {
    use std::path::PathBuf;

    match std::env::var_os("XDG_RUNTIME_DIR") {
        Some(dir) => PathBuf::from(dir).join("running-process").join("broker"),
        None => PathBuf::from(format!(
            "/tmp/running-process-{}/broker",
            unsafe { libc::getuid() }
        )),
    }
}

#[cfg(feature = "ipc")]
pub fn ipc_broker_v1_endpoint_path(
    bare_name: &str,
) -> Result<String, crate::platform::ipc::EndpointNameTooLong> {
    // Linux gets 108 bytes and a guaranteed $XDG_RUNTIME_DIR (or a short
    // /tmp fallback), so the full canonical name survives for debuggability.
    let candidate = broker_v1_socket_dir().join(format!("{bare_name}.sock"));
    let candidate = candidate.to_string_lossy();
    // sockaddr_un is NUL-terminated, so the path itself must be strictly
    // shorter than the field width.
    if candidate.len() >= LINUX_SUN_PATH_MAX {
        return Err(crate::platform::ipc::EndpointNameTooLong {
            len: candidate.len(),
            max: LINUX_SUN_PATH_MAX - 1,
            limit_label: "Linux sun_path",
        });
    }
    Ok(candidate.into_owned())
}

#[cfg(feature = "ipc")]
pub fn ipc_endpoint_scope_bytes(path: &std::path::Path) -> Vec<u8> {
    // Linux paths are opaque byte strings; no spelling difference is
    // meaningless, so the bytes are hashed exactly as the OS reports them.
    use std::os::unix::ffi::OsStrExt as _;

    path.as_os_str().as_bytes().to_vec()
}

#[cfg(feature = "ipc")]
pub fn ipc_broker_v2_runtime_dir() -> std::path::PathBuf {
    match std::env::var_os("XDG_RUNTIME_DIR") {
        Some(dir) => std::path::PathBuf::from(dir)
            .join("running-process")
            .join("broker-v2"),
        None => crate::platform::ipc::per_user_runtime_fallback(),
    }
}
#[cfg(feature = "ipc")]
pub fn into_legacy_ipc_stream(stream: IpcStream) -> interprocess::local_socket::Stream {
    stream.0
}

#[cfg(feature = "ipc")]
pub fn from_legacy_ipc_stream(stream: interprocess::local_socket::Stream) -> IpcStream {
    ipc::Stream(stream)
}
#[cfg(feature = "ipc")]
pub fn legacy_ipc_name(path: &str) -> Result<interprocess::local_socket::Name<'_>, String> {
    ipc::legacy_name(path)
}
#[cfg(feature = "ipc-async")]
pub use ipc::{
    AsyncListener as IpcAsyncListener, AsyncStream as IpcAsyncStream,
    IntoAsyncListener as IpcIntoAsyncListener, IntoAsyncStream as IpcIntoAsyncStream,
};

#[cfg(feature = "session-relay")]
#[path = "platform_linux_session_relay.rs"]
mod session_relay;
#[cfg(feature = "session-relay")]
pub use session_relay::relay_local_socket_session;

#[cfg(feature = "pty")]
#[path = "platform_linux/terminal.rs"]
pub mod terminal;
#[cfg(feature = "terminal-graphics")]
#[path = "platform_linux/terminal_graphics.rs"]
mod terminal_graphics;
#[cfg(feature = "terminal-graphics")]
pub use terminal_graphics::active_graphics_probe;
pub use crate::platform::terminal_input;

#[path = "platform_linux/window_icon.rs"]
mod window_icon;
pub use window_icon::{icon_support as window_icon_support_impl, set_icon as set_window_icon_impl};

pub fn shell_command(command: &str) -> std::process::Command {
    let mut shell = std::process::Command::new("/bin/sh");
    shell.arg("-lc").arg(command);
    shell
}

pub fn compat_shell_command(command: &str) -> std::process::Command {
    let mut shell = std::process::Command::new("/bin/sh");
    shell.arg("-lc").arg(command);
    shell
}

pub fn canonical_environment_pairs(pairs: Vec<(String, String)>) -> Vec<(String, String)> {
    pairs
}

pub fn monitor_console_windows(
    _duration: std::time::Duration,
) -> Vec<crate::platform::process::ConsoleWindowInfo> {
    Vec::new()
}

#[cfg(feature = "async-process")]
use std::ffi::OsStr;
use std::io;
use std::io::Read;
use std::os::fd::{AsRawFd, RawFd};
use std::os::unix::net::UnixStream;
use std::sync::Mutex;

#[cfg(feature = "async-process")]
use tokio::process::{Child, Command};

#[cfg(feature = "async-process")]
use crate::SpawnSpec;

#[path = "platform_linux_descendants.rs"]
mod descendants;
pub use descendants::start_descendant_monitor;

#[path = "platform_linux_trace.rs"]
mod exact_trace;
pub use exact_trace::{configure_exact_trace, start_exact_trace, TracedChild};

pub fn exact_trace_capability() -> crate::platform::process::ExactTraceCapability {
    crate::platform::process::ExactTraceCapability {
        available: true,
        backend: "linux-ptrace",
        reason: "launch-time PTRACE_TRACEME with follow-fork/clone/exec/exit supervision",
        non_invasive_backend: "proc-descendant-snapshot",
        non_invasive_grade:
            crate::platform::process::NonInvasiveObservationGrade::SnapshotInferred,
    }
}

pub struct WindowsJobHandle;

pub fn assign_child_to_windows_job(
    _child: &std::process::Child,
    _direct_pid: u32,
    _address_space_limit_bytes: Option<u64>,
    _emit: Option<Box<dyn Fn(crate::platform::process::DescendantEvent) + Send>>,
) -> io::Result<WindowsJobHandle> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "Windows Job Objects are unavailable on Linux",
    ))
}

#[derive(Default)]
pub struct CaptureCancellation {
    wakers: Mutex<CaptureWakers>,
}

#[derive(Default)]
struct CaptureWakers {
    stdout: Option<UnixStream>,
    stderr: Option<UnixStream>,
}

struct CancelableCaptureReader<R> {
    reader: R,
    wake_reader: UnixStream,
}

impl<R: Read + AsRawFd> Read for CancelableCaptureReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if buf.is_empty() { return Ok(0); }
        loop {
            let mut poll_fds = [
                libc::pollfd { fd: self.reader.as_raw_fd(), events: libc::POLLIN | libc::POLLHUP | libc::POLLERR, revents: 0 },
                libc::pollfd { fd: self.wake_reader.as_raw_fd(), events: libc::POLLIN | libc::POLLHUP | libc::POLLERR, revents: 0 },
            ];
            // SAFETY: both descriptors remain owned by this reader for the call.
            let polled = unsafe { libc::poll(poll_fds.as_mut_ptr(), poll_fds.len() as _, -1) };
            if polled < 0 {
                let error = io::Error::last_os_error();
                if error.kind() == io::ErrorKind::Interrupted { continue; }
                return Err(error);
            }
            if poll_fds[1].revents != 0 {
                return Err(io::Error::new(io::ErrorKind::Interrupted, "capture reader cancelled"));
            }
            if poll_fds[0].revents != 0 {
                match self.reader.read(buf) {
                    Err(error) if error.kind() == io::ErrorKind::WouldBlock => continue,
                    result => return result,
                }
            }
        }
    }
}

pub fn prepare_capture_reader<R>(
    reader: R,
    cancellation: &CaptureCancellation,
    stream: crate::platform::process::CaptureStream,
) -> io::Result<Box<dyn Read + Send>>
where R: Read + AsRawFd + Send + 'static {
    set_nonblocking(reader.as_raw_fd())?;
    let (wake_reader, wake_writer) = UnixStream::pair()?;
    wake_writer.set_nonblocking(true)?;
    let mut wakers = cancellation.wakers.lock().expect("capture wakers mutex poisoned");
    match stream {
        crate::platform::process::CaptureStream::Stdout => wakers.stdout = Some(wake_writer),
        crate::platform::process::CaptureStream::Stderr => wakers.stderr = Some(wake_writer),
    }
    Ok(Box::new(CancelableCaptureReader { reader, wake_reader }))
}

pub fn capture_reader_done(cancellation: &CaptureCancellation, stream: crate::platform::process::CaptureStream) {
    let mut wakers = cancellation.wakers.lock().expect("capture wakers mutex poisoned");
    match stream {
        crate::platform::process::CaptureStream::Stdout => wakers.stdout = None,
        crate::platform::process::CaptureStream::Stderr => wakers.stderr = None,
    }
}

pub fn cancel_capture_reader(cancellation: &CaptureCancellation) {
    let wakers = cancellation.wakers.lock().expect("capture wakers mutex poisoned");
    let byte = [1_u8; 1];
    for writer in [&wakers.stdout, &wakers.stderr].into_iter().flatten() {
        // SAFETY: the stored wake socket stays alive while the mutex is held.
        let _ = unsafe { libc::write(writer.as_raw_fd(), byte.as_ptr().cast(), byte.len()) };
    }
}

fn set_nonblocking(fd: RawFd) -> io::Result<()> {
    // SAFETY: `fd` is borrowed from a live reader for both calls.
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    if flags < 0 { return Err(io::Error::last_os_error()); }
    // SAFETY: `fd` is borrowed from a live reader for both calls.
    if unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

#[path = "platform_linux_file_handles.rs"]
mod file_handles;
pub use file_handles::read_process_file_handles;
#[path = "platform_linux_cmdline.rs"]
mod cmdline;
pub use cmdline::{read_process_argv, read_process_cmdline};

#[cfg(feature = "process-inspection")]
#[path = "platform/process_tree.rs"]
mod process_tree;

#[cfg(feature = "process-inspection")]
pub fn kill_tree(pid: u32, timeout: std::time::Duration) -> io::Result<u32> {
    process_tree::kill_tree(pid, timeout, |_pid, process| Ok(process.start_time()))
}

pub fn exit_code(status: std::process::ExitStatus) -> i32 {
    use std::os::unix::process::ExitStatusExt;
    status.code().unwrap_or_else(|| -status.signal().unwrap_or(1))
}

pub fn set_process_name(name: &str) {
    let truncated: String = name.chars().take(15).collect();
    let c_name = std::ffi::CString::new(truncated).unwrap_or_default();
    unsafe { libc::prctl(libc::PR_SET_NAME, c_name.as_ptr() as libc::c_ulong, 0, 0, 0); }
}

pub fn configure_trampoline_command(_command: &mut std::process::Command) {}

pub fn configure_process_command(
    command: &mut std::process::Command,
    config: crate::platform::process::ProcessCommandConfig,
) -> io::Result<()> {
    configure_process_command_inner(command, config, false)
}

/// Root-facade-only launch seam for bounded owner-death containment.
///
/// This must be `pub` because `running-process` is a separate package, but
/// applications should use its semantic bounded-run options instead of this
/// implementation-detail function.
#[doc(hidden)]
pub fn configure_process_command_for_bounded_owner_death(
    command: &mut std::process::Command,
    config: crate::platform::process::ProcessCommandConfig,
) -> io::Result<()> {
    configure_process_command_inner(command, config, true)
}

fn configure_process_command_inner(
    command: &mut std::process::Command,
    config: crate::platform::process::ProcessCommandConfig,
    kill_when_owner_dies: bool,
) -> io::Result<()> {
    let create_process_group = config.create_process_group;
    let nice = config.nice;
    let address_space_limit_bytes = config.address_space_limit_bytes;
    if !(create_process_group
        || nice.is_some()
        || address_space_limit_bytes.is_some()
        || kill_when_owner_dies)
    {
        return Ok(());
    }
    let owner_pid = if kill_when_owner_dies {
        // Read before `Command` forks so the child can detect the narrow race
        // where this process exits between fork and PR_SET_PDEATHSIG.
        unsafe { libc::getpid() }
    } else {
        0
    };
    use std::os::unix::process::CommandExt;
    unsafe {
        command.pre_exec(move || {
            if create_process_group && libc::setpgid(0, 0) == -1 {
                return Err(io::Error::last_os_error());
            }
            if let Some(nice) = nice {
                if libc::setpriority(libc::PRIO_PROCESS, 0, nice) == -1 {
                    return Err(io::Error::last_os_error());
                }
            }
            if let Some(limit) = address_space_limit_bytes {
                let rlim = libc::rlimit { rlim_cur: limit, rlim_max: limit };
                if libc::setrlimit(libc::RLIMIT_AS, &rlim) == -1 {
                    return Err(io::Error::last_os_error());
                }
            }
            if kill_when_owner_dies {
                install_parent_death_signal_with_race_guard(owner_pid)?;
            }
            Ok(())
        });
    }
    Ok(())
}

/// Install PDEATHSIG and close the fork-to-prctl owner-death race.
///
/// This runs only in `Command::pre_exec`, after fork and before exec.
fn install_parent_death_signal_with_race_guard(owner_pid: libc::pid_t) -> io::Result<()> {
    if unsafe {
        libc::prctl(
            libc::PR_SET_PDEATHSIG,
            libc::SIGTERM as libc::c_ulong,
            0,
            0,
            0,
        )
    } == -1
    {
        return Err(io::Error::last_os_error());
    }
    if unsafe { libc::getppid() } != owner_pid {
        // The owner died after fork but before PDEATHSIG was armed. A
        // caller-provided pre_exec hook may have ignored SIGTERM, so sending
        // that signal then returning would let this orphan exec. SAFETY:
        // `_exit` is async-signal-safe and bypasses Rust destructors and
        // allocation in this post-fork child.
        unsafe { libc::_exit(128 + libc::SIGTERM) };
    }
    Ok(())
}

pub fn trampoline_exit_code(status: std::process::ExitStatus) -> i32 {
    use std::os::unix::process::ExitStatusExt;
    status.signal().map_or_else(|| status.code().unwrap_or(1), |signal| 128 + signal)
}

/// Return the GNU build ID of the running executable without reading the
/// executable from disk.
///
/// The dynamic loader has already mapped the main image's `PT_NOTE` segment,
/// so callers that only need an image-generation identity do not need to hash
/// a potentially large unoptimized binary. `None` preserves a clean fallback
/// for binaries linked without a GNU build ID.
pub fn current_executable_build_id() -> Option<Vec<u8>> {
    unsafe extern "C" fn visit(
        info: *mut libc::dl_phdr_info,
        _size: libc::size_t,
        output: *mut libc::c_void,
    ) -> libc::c_int {
        const MAX_NOTE_BYTES: usize = 1024 * 1024;

        let info = unsafe { &*info };
        let is_main_executable = info.dlpi_name.is_null()
            || unsafe { std::ffi::CStr::from_ptr(info.dlpi_name) }
                .to_bytes()
                .is_empty();
        if !is_main_executable || info.dlpi_phdr.is_null() || info.dlpi_phnum == 0 {
            return 0;
        }
        let headers = unsafe {
            std::slice::from_raw_parts(info.dlpi_phdr, usize::from(info.dlpi_phnum))
        };
        #[allow(clippy::unnecessary_cast)]
        let load_bias = info.dlpi_addr as u64;
        for header in headers {
            if header.p_type != libc::PT_NOTE {
                continue;
            }
            let Ok(length) = usize::try_from(header.p_memsz) else {
                continue;
            };
            if length == 0 || length > MAX_NOTE_BYTES {
                continue;
            }
            let Some(address) = load_bias.checked_add(header.p_vaddr) else {
                continue;
            };
            let Some(note_end) = address.checked_add(length as u64) else {
                continue;
            };
            let mapped_read_only = headers.iter().any(|load| {
                if load.p_type != libc::PT_LOAD || load.p_flags & libc::PF_R == 0 {
                    return false;
                }
                let Some(start) = load_bias.checked_add(load.p_vaddr) else {
                    return false;
                };
                let Some(end) = start.checked_add(load.p_memsz) else {
                    return false;
                };
                address >= start && note_end <= end
            });
            if address == 0 || !mapped_read_only {
                continue;
            }
            let notes = unsafe { std::slice::from_raw_parts(address as *const u8, length) };
            if let Some(build_id) = gnu_build_id_from_notes(notes) {
                let output = unsafe { &mut *output.cast::<Option<Vec<u8>>>() };
                *output = Some(build_id.to_vec());
                return 1;
            }
        }
        0
    }

    let mut output = None;
    unsafe {
        libc::dl_iterate_phdr(
            Some(visit),
            (&mut output as *mut Option<Vec<u8>>).cast::<libc::c_void>(),
        );
    }
    output
}

fn gnu_build_id_from_notes(mut notes: &[u8]) -> Option<&[u8]> {
    fn aligned(value: usize) -> Option<usize> {
        value.checked_add(3).map(|value| value & !3)
    }

    while notes.len() >= 12 {
        let name_len = usize::try_from(u32::from_ne_bytes(notes[0..4].try_into().ok()?)).ok()?;
        let desc_len = usize::try_from(u32::from_ne_bytes(notes[4..8].try_into().ok()?)).ok()?;
        let kind = u32::from_ne_bytes(notes[8..12].try_into().ok()?);
        let name_end = 12usize.checked_add(name_len)?;
        let desc_start = 12usize.checked_add(aligned(name_len)?)?;
        let desc_end = desc_start.checked_add(desc_len)?;
        let next = desc_start.checked_add(aligned(desc_len)?)?;
        if next > notes.len() || name_end > notes.len() || desc_end > notes.len() {
            return None;
        }
        if kind == 3 && notes.get(12..name_end)?.starts_with(b"GNU") && desc_len > 0 {
            return notes.get(desc_start..desc_end);
        }
        notes = &notes[next..];
    }
    None
}

/// Request a graceful shutdown for a child-owned POSIX process group.
pub fn soft_terminate_process_group(pid: u32) -> io::Result<()> {
    // SAFETY: `kill` receives only the numeric child-owned group id; no Rust
    // references or borrowed state cross the OS boundary.
    let result = unsafe { libc::kill(-(pid as i32), libc::SIGTERM) };
    if result != 0 {
        let error = io::Error::last_os_error();
        if error.raw_os_error() != Some(libc::ESRCH) {
            return Err(error);
        }
    }
    Ok(())
}

pub fn process_snapshot() -> Vec<crate::platform::process::ProcessSnapshot> {
    Vec::new()
}

pub fn process_snapshot_for_pid(_pid: u32) -> Option<crate::platform::process::ProcessSnapshot> {
    None
}

/// Mark inherited descriptors close-on-exec without breaking std's exec-error pipe.
///
/// # Safety
/// This must only be called from a post-fork `pre_exec` closure.
pub unsafe fn unix_mark_extra_fds_close_on_exec() {
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "x86", target_arch = "arm", target_arch = "riscv64", target_arch = "powerpc64"))]
    {
        const SYS_CLOSE_RANGE: libc::c_long = 436;
        const CLOSE_RANGE_CLOEXEC: libc::c_uint = 4;
        if libc::syscall(SYS_CLOSE_RANGE, 3u32, libc::c_uint::MAX, CLOSE_RANGE_CLOEXEC) == 0 {
            return;
        }
    }
    mark_fds_from_directory_or_range();
}

pub fn configure_sync_daemon_command(command: &mut std::process::Command) -> io::Result<()> {
    configure_sync_daemon_command_inner(command, None)
}

pub fn configure_sync_daemon_command_with_inheritance(
    command: &mut std::process::Command,
    inheritance: crate::platform::process::DaemonExecInheritance,
) -> io::Result<()> {
    configure_sync_daemon_command_inner(command, Some(inheritance))
}

fn configure_sync_daemon_command_inner(
    command: &mut std::process::Command,
    inheritance: Option<crate::platform::process::DaemonExecInheritance>,
) -> io::Result<()> {
    use std::os::unix::process::CommandExt;
    unsafe {
        command.pre_exec(move || {
            let _ = libc::setsid();
            unix_mark_extra_fds_close_on_exec();
            if let Some(inheritance) = inheritance {
                clear_cloexec_after_sweep(inheritance.descriptor())?;
            }
            Ok(())
        });
    }
    Ok(())
}

unsafe fn clear_cloexec_after_sweep(fd: libc::c_int) -> io::Result<()> {
    let flags = libc::fcntl(fd, libc::F_GETFD);
    if flags == -1 {
        return Err(io::Error::last_os_error());
    }
    if libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) == -1 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

pub fn configure_sync_contained_command(command: &mut std::process::Command) -> io::Result<()> {
    use std::os::unix::process::CommandExt;
    unsafe {
        command.pre_exec(|| {
            if libc::setpgid(0, 0) == -1 { return Err(io::Error::last_os_error()); }
            if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) == -1 {
                return Err(io::Error::last_os_error());
            }
            if libc::getppid() == 1 { libc::_exit(1); }
            unix_mark_extra_fds_close_on_exec();
            Ok(())
        });
    }
    Ok(())
}

pub fn parent_has_console() -> bool { false }

pub fn sync_child_native_handle(_child: &std::process::Child) -> usize { 0 }

unsafe fn mark_fds_from_directory_or_range() {
    let dir = libc::opendir(c"/dev/fd".as_ptr());
    if !dir.is_null() {
        let dir_fd = libc::dirfd(dir);
        loop {
            let entry = libc::readdir(dir);
            if entry.is_null() { break; }
            let mut fd: libc::c_int = 0;
            let mut cursor = (*entry).d_name.as_ptr();
            let mut numeric = false;
            while *cursor != 0 {
                let byte = *cursor as u8;
                if !byte.is_ascii_digit() { numeric = false; break; }
                fd = fd * 10 + (byte - b'0') as libc::c_int;
                cursor = cursor.add(1);
                numeric = true;
            }
            if numeric && fd > 2 && fd != dir_fd { set_cloexec(fd); }
        }
        libc::closedir(dir);
        return;
    }
    let maximum = libc::sysconf(libc::_SC_OPEN_MAX);
    for fd in 3..if maximum < 0 { 4096 } else { maximum as libc::c_int } { set_cloexec(fd); }
}

unsafe fn set_cloexec(fd: libc::c_int) {
    let flags = libc::fcntl(fd, libc::F_GETFD);
    if flags != -1 { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC); }
}
pub fn observer_backend(scope: crate::platform::process::ObserverScope, category: crate::platform::process::ObserverCategory) -> crate::platform::process::ObserverBackend {
    use crate::platform::process::{ObserverBackend as B, ObserverCategory as C, ObserverScope as S, ObserverSupport as P};
    match (scope, category) {
        (S::SystemWide, C::File) => B { support:P::Unavailable, backend:"seccomp-user-notify", reason:"Phase 3: Linux seccomp user-notify file backend not yet implemented" },
        (S::SystemWide, C::Network) => B { support:P::Unavailable, backend:"ebpf", reason:"Phase 3: Linux eBPF network backend not yet implemented" },
        (S::SystemWide, C::Process) => B { support:P::Unavailable, backend:"seccomp-user-notify", reason:"Phase 3: Linux seccomp user-notify process backend not yet implemented" },
        (S::LaunchedProcessTree, C::File) => B { support:P::Partial, backend:"proc-fd-snapshot", reason:"Linux /proc/<pid>/fd/* snapshot via read_process_file_handles (#539 slice 6 follow-up; no streaming file events)" },
        (S::LaunchedProcessTree, C::Network) => B { support:P::Unavailable, backend:"none", reason:"#539: no-admin per-child network backend deferred to a follow-up issue" },
        (S::LaunchedProcessTree, C::Process) => B { support:P::Supported, backend:"subreaper-proc-poll", reason:"Linux PR_SET_CHILD_SUBREAPER + /proc descendant polling (#539 slice 5)" },
    }
}

pub fn unix_set_priority(pid: u32, nice: i32) -> io::Result<()> {
    if unsafe { libc::setpriority(libc::PRIO_PROCESS, pid, nice) } == -1 { Err(io::Error::last_os_error()) } else { Ok(()) }
}
pub fn unix_signal_process(pid: u32, signal: crate::platform::process::UnixSignalKind) -> io::Result<()> {
    if unsafe { libc::kill(pid as i32, unix_signal_raw(signal)) } == -1 { Err(io::Error::last_os_error()) } else { Ok(()) }
}
pub fn unix_signal_process_group(pid: i32, signal: crate::platform::process::UnixSignalKind) -> io::Result<()> {
    if unsafe { libc::killpg(pid, unix_signal_raw(signal)) } == -1 { Err(io::Error::last_os_error()) } else { Ok(()) }
}
pub fn unix_signal_raw(signal: crate::platform::process::UnixSignalKind) -> i32 {
    match signal { crate::platform::process::UnixSignalKind::Interrupt => libc::SIGINT, crate::platform::process::UnixSignalKind::Terminate => libc::SIGTERM, crate::platform::process::UnixSignalKind::Kill => libc::SIGKILL }
}

#[cfg(feature = "async-process")]
pub fn configure_compat_tokio_command(
    command: &mut Command,
    _show_console: bool,
    kill_when_owner_dies: bool,
) -> io::Result<()> {
    configure_command(command, false, kill_when_owner_dies, None)
}

/// Nothing to do on this host: the parent-death signal is installed in `pre_exec`, before the
/// child ever runs, so nothing remains to do once it has.
#[cfg(feature = "async-process")]
pub fn after_compat_tokio_spawn(
    _child: &Child,
    _kill_when_owner_dies: bool,
) -> io::Result<()> {
    Ok(())
}

#[cfg(feature = "async-process")]
pub(crate) fn configure_command(
    command: &mut Command,
    create_process_group: bool,
    kill_when_owner_dies: bool,
    nice: Option<i32>,
) -> io::Result<()> {
    if create_process_group {
        command.process_group(0);
    }
    if kill_when_owner_dies || nice.is_some() {
        let owner_pid = unsafe { libc::getpid() };
        // SAFETY: the closure invokes only async-signal-safe libc calls.
        unsafe {
            command.pre_exec(move || {
                if let Some(nice) = nice {
                    if libc::setpriority(libc::PRIO_PROCESS, 0, nice) == -1 {
                        return Err(io::Error::last_os_error());
                    }
                }
                if kill_when_owner_dies {
                    install_parent_death_signal_with_race_guard(owner_pid)?;
                }
                Ok(())
            });
        }
    }
    Ok(())
}

#[cfg(feature = "async-process")]
pub(crate) fn after_spawn(_child: &Child, _kill_when_owner_dies: bool) -> io::Result<()> {
    Ok(())
}

/// Launch-bound identity for private async controls.
///
/// `pidfd_open` supplies the race-free direct-control capability where the
/// kernel permits it. `/proc/<pid>/stat` start ticks remain available for CPU
/// accounting on older or restricted hosts, but are never a raw-PID control
/// fallback.
#[cfg(feature = "async-process")]
pub(crate) struct AsyncChildIdentity {
    pid: u32,
    start_ticks: u64,
    pidfd: Option<std::os::fd::OwnedFd>,
}

#[cfg(feature = "async-process")]
pub(crate) fn async_child_identity(child: &Child) -> Option<AsyncChildIdentity> {
    let pid = child.id()?;
    let (start_ticks, _, _) = proc_stat(pid).ok()?;
    let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid as libc::c_int, 0) } as libc::c_int;
    let pidfd = (fd >= 0).then(|| {
        // SAFETY: pidfd_open returned a newly owned descriptor above.
        unsafe { <std::os::fd::OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(fd) }
    });
    Some(AsyncChildIdentity {
        pid,
        start_ticks,
        pidfd,
    })
}

#[cfg(feature = "async-process")]
pub(crate) fn signal_async_child(identity: &AsyncChildIdentity) -> io::Result<()> {
    if identity_matches(identity) {
        pidfd_send_signal(identity, libc::SIGKILL)
    } else {
        Err(io::Error::new(
            io::ErrorKind::BrokenPipe,
            "child process launch identity no longer matches",
        ))
    }
}

#[cfg(feature = "async-process")]
pub(crate) fn signal_async_child_group(identity: &AsyncChildIdentity) -> io::Result<()> {
    if !identity_matches(identity) || !pidfd_is_live(identity)? {
        return Err(io::Error::new(
            io::ErrorKind::BrokenPipe,
            "child process launch identity no longer matches",
        ));
    }
    if unsafe { libc::kill(-(identity.pid as i32), libc::SIGTERM) } == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

#[cfg(feature = "async-process")]
pub(crate) fn async_child_cpu_time(
    identity: &AsyncChildIdentity,
) -> io::Result<Option<std::time::Duration>> {
    let Ok((start_ticks, user_ticks, system_ticks)) = proc_stat(identity.pid) else {
        return Ok(None);
    };
    if start_ticks != identity.start_ticks {
        return Ok(None);
    }
    let ticks_per_second = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
    if ticks_per_second <= 0 {
        return Ok(None);
    }
    let ticks = user_ticks.saturating_add(system_ticks);
    let hz = ticks_per_second as u64;
    Ok(Some(
        std::time::Duration::from_secs(ticks / hz)
            + std::time::Duration::from_nanos(
                ticks
                    % hz
                    .saturating_mul(1_000_000_000)
                    / hz,
            ),
    ))
}

#[cfg(feature = "async-process")]
fn identity_matches(identity: &AsyncChildIdentity) -> bool {
    matches!(proc_stat(identity.pid), Ok((start_ticks, _, _)) if start_ticks == identity.start_ticks)
}

#[cfg(feature = "async-process")]
fn pidfd_is_live(identity: &AsyncChildIdentity) -> io::Result<bool> {
    let Some(pidfd) = identity.pidfd.as_ref() else {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "pidfd control is unavailable for this child",
        ));
    };
    let result = unsafe {
        libc::syscall(
            libc::SYS_pidfd_send_signal,
            std::os::fd::AsRawFd::as_raw_fd(pidfd),
            0,
            std::ptr::null::<libc::siginfo_t>(),
            0,
        )
    };
    if result == 0 {
        return Ok(true);
    }
    let error = io::Error::last_os_error();
    if error.raw_os_error() == Some(libc::ESRCH) {
        Ok(false)
    } else {
        Err(error)
    }
}

#[cfg(feature = "async-process")]
fn pidfd_send_signal(identity: &AsyncChildIdentity, signal: libc::c_int) -> io::Result<()> {
    let Some(pidfd) = identity.pidfd.as_ref() else {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "pidfd control is unavailable for this child",
        ));
    };
    let result = unsafe {
        libc::syscall(
            libc::SYS_pidfd_send_signal,
            std::os::fd::AsRawFd::as_raw_fd(pidfd),
            signal,
            std::ptr::null::<libc::siginfo_t>(),
            0,
        )
    };
    if result == 0 {
        return Ok(());
    }
    let error = io::Error::last_os_error();
    if error.raw_os_error() == Some(libc::ESRCH) {
        Ok(())
    } else {
        Err(error)
    }
}

#[cfg(feature = "async-process")]
fn proc_stat(pid: u32) -> io::Result<(u64, u64, u64)> {
    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat"))?;
    let fields = stat
        .rsplit_once(')')
        .map(|(_, fields)| fields.split_ascii_whitespace().collect::<Vec<_>>())
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "malformed /proc stat"))?;
    let parse = |index: usize| -> io::Result<u64> {
        fields
            .get(index)
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "short /proc stat"))?
            .parse::<u64>()
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid /proc stat"))
    };
    // Fields after the closing command name begin at stat field 3: utime=11,
    // stime=12, starttime=19 in this zero-based tail.
    Ok((parse(19)?, parse(11)?, parse(12)?))
}

#[cfg(feature = "async-process")]
pub(crate) fn shell_spec(command: &OsStr) -> SpawnSpec {
    SpawnSpec::new("/bin/sh").arg("-c").arg(command)
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "async-process")]
    #[test]
    fn async_identity_mismatch_fails_closed_without_pid_signal() {
        let pid = unsafe { libc::getpid() as u32 };
        let (start_ticks, _, _) = super::proc_stat(pid).expect("read this process start key");
        let identity = super::AsyncChildIdentity {
            pid,
            start_ticks: start_ticks.saturating_add(1),
            pidfd: None,
        };
        assert!(!super::identity_matches(&identity));
        let error = super::signal_async_child(&identity)
            .expect_err("mismatched launch identity must not signal a reused PID");
        assert_eq!(error.kind(), std::io::ErrorKind::BrokenPipe);
        assert_eq!(super::async_child_cpu_time(&identity).unwrap(), None);
    }

    #[cfg(feature = "async-process")]
    #[test]
    fn async_identity_without_pidfd_keeps_cpu_but_refuses_pid_control() {
        let pid = unsafe { libc::getpid() as u32 };
        let (start_ticks, _, _) = super::proc_stat(pid).expect("read this process start key");
        let identity = super::AsyncChildIdentity {
            pid,
            start_ticks,
            pidfd: None,
        };
        assert!(super::async_child_cpu_time(&identity).unwrap().is_some());
        let error = super::signal_async_child(&identity).expect_err("no raw-PID kill fallback");
        assert_eq!(error.kind(), std::io::ErrorKind::Unsupported);
    }

    #[test]
    fn owner_death_race_guard_exits_when_sigterm_is_ignored() {
        let child = unsafe { libc::fork() };
        assert!(child >= 0, "fork owner-death race fixture");
        if child == 0 {
            // Model a caller-supplied pre_exec hook which ignored SIGTERM
            // before the bounded runner's hook is appended.
            if unsafe { libc::signal(libc::SIGTERM, libc::SIG_IGN) } == libc::SIG_ERR {
                unsafe { libc::_exit(98) };
            }
            let owner_pid = unsafe { libc::getppid() }.saturating_add(1);
            // A deliberately mismatched owner PID models the post-prctl
            // parent-death race. The helper must not return even though the
            // SIGTERM disposition above would ignore a signal-based guard.
            if super::install_parent_death_signal_with_race_guard(owner_pid).is_err() {
                unsafe { libc::_exit(99) };
            }
            unsafe { libc::_exit(100) };
        }

        let mut status = 0;
        assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child);
        assert!(libc::WIFEXITED(status), "race fixture must _exit");
        assert_eq!(
            libc::WEXITSTATUS(status),
            128 + libc::SIGTERM,
            "ignored SIGTERM must not permit the owner-dead child to continue"
        );
    }

    #[test]
    fn shell_command_preserves_login_shell_contract_and_ignores_child_path() {
        use std::ffi::OsStr;

        let command_text = "printf '%s' 'alpha beta;\"gamma\"'";
        let mut command = super::shell_command(command_text);
        assert_eq!(command.get_program(), OsStr::new("/bin/sh"));
        assert_eq!(
            command.get_args().collect::<Vec<_>>(),
            [OsStr::new("-lc"), OsStr::new(command_text)]
        );
        command
            .env_clear()
            .env("PATH", "/caller-supplied-path-override");
        let output = command
            .output()
            .expect("absolute shell command should execute independently of child PATH");
        assert!(output.status.success());
        assert_eq!(output.stdout, b"alpha beta;\"gamma\"");
    }

    #[test]
    #[cfg(not(target_env = "musl"))]
    fn current_executable_exposes_a_gnu_build_id() {
        let build_id = super::current_executable_build_id()
            .expect("Linux test executable should carry a GNU build ID");
        assert!(!build_id.is_empty());
    }
}
#[cfg(test)]
#[path = "tests/platform_linux_coverage.rs"]
mod coverage_tests;
#[path = "sync_spawn_group.rs"]
mod sync_spawn;
pub use sync_spawn::{spawn_sync, spawn_sync_daemon, spawn_sync_daemon_with_inheritance};

#[cfg(all(test, feature = "ipc"))]
mod endpoint_naming_tests {
    use super::{ipc_broker_v1_endpoint_path, ipc_endpoint_name_limit, LINUX_SUN_PATH_MAX};

    #[test]
    fn the_v1_address_keeps_the_full_name_for_debuggability() {
        let address = ipc_broker_v1_endpoint_path("rpb-v1-abc-shared").expect("derive address");
        assert!(address.contains("rpb-v1-abc-shared"));
        assert!(address.ends_with("-shared.sock"));
        assert!(address.contains("/broker/"));
    }

    #[test]
    fn an_over_long_name_is_refused_against_sun_path() {
        let err = ipc_broker_v1_endpoint_path(&"a".repeat(LINUX_SUN_PATH_MAX))
            .expect_err("must exceed sun_path");
        assert_eq!(err.max, LINUX_SUN_PATH_MAX - 1);
        assert_eq!(err.limit_label, "Linux sun_path");
    }

    #[test]
    fn an_accepted_address_is_strictly_shorter_than_the_field() {
        // sockaddr_un is NUL-terminated, so equality with the field width
        // would truncate the terminator.
        let address = ipc_broker_v1_endpoint_path("rpb-v1-abc-shared").expect("derive address");
        assert!(address.len() < LINUX_SUN_PATH_MAX);
    }

    #[test]
    fn the_reported_budget_is_sun_path() {
        let limit = ipc_endpoint_name_limit();
        assert_eq!(limit.max_bytes, LINUX_SUN_PATH_MAX);
        assert_eq!(limit.label, "Linux sun_path");
    }

    #[test]
    fn the_scope_spelling_is_the_verbatim_path_bytes() {
        // Paths are opaque byte strings here: no spelling difference is
        // meaningless, and case is significant. This pins the spelling --
        // changing it re-scopes every deployed broker, and the stability
        // tests upstream would not notice.
        use super::ipc_endpoint_scope_bytes;

        let bytes = ipc_endpoint_scope_bytes(std::path::Path::new("/usr/local/bin/Broker"));
        assert_eq!(bytes, b"/usr/local/bin/Broker".to_vec());

        let lowered = ipc_endpoint_scope_bytes(std::path::Path::new("/usr/local/bin/broker"));
        assert_ne!(bytes, lowered, "case must remain significant");
    }

}

/// Replace this process's image with `command`.
///
/// Returns only on failure: on success `execve` has already replaced the
/// program and there is nothing left to return to. That is why the signature
/// yields `io::Error` rather than `io::Result<()>` -- an `Ok` would name a
/// state that cannot be observed.
pub fn process_replace_current_image(command: &mut std::process::Command) -> std::io::Error {
    use std::os::unix::process::CommandExt as _;
    command.exec()
}

/// This host replaces a running image in place; see the facade for what that
/// means for a caller that cannot accept a successor instead.
pub const fn process_can_replace_current_image() -> bool {
    true
}