vvland 0.1.1

Run one Wayland app or compositor inside Vivido over Vivid
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
//! Launcher scaffolding shared by every compositor backend.
//!
//! The sessions independently grew the same private runtime directory, private file writer,
//! bounded log drain, process-group teardown, and PATH probe (plan D7). They live here once; the
//! backends keep only what genuinely differs — readiness protocols, the launcher mechanism
//! (Weston and Hyprland spawn directly, Sway execs through its IPC), and the input transport.

use std::ffi::OsStr;
use std::fs::{self, DirBuilder, File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::os::fd::{FromRawFd, OwnedFd};
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};

use crate::cli::Xwayland;

pub const MAX_LOG_BYTES: u64 = 1_048_576;
pub const ERROR_LOG_BYTES: usize = 8_192;

/// A private 0700 directory holding the compositor socket, generated config, and bounded log.
pub struct RuntimeDirectory {
    pub path: PathBuf,
}

/// The longest path a `sockaddr_un` can carry, once the NUL terminator is subtracted.
pub const MAX_UNIX_SOCKET_PATH: usize = 107;

/// `vv` plus six hex digits, and the `/` that joins it to its base.
const SHORT_NAME_LENGTH: usize = 9;

impl RuntimeDirectory {
    pub fn create() -> io::Result<Self> {
        Self::create_in(&default_base(), "vvland-", 8)
    }

    /// A private runtime directory short enough for a compositor that binds sockets below it.
    ///
    /// Hyprland binds `<directory>/hypr/<instance signature>/.socket.sock`, and the signature
    /// alone is its sixty-odd-character build hash, timestamp and nonce. The ordinary name
    /// overruns `sun_path` on a perfectly normal `/run/user/<uid>`, and Hyprland's answer to that
    /// is to log "IPC will not work" and carry on — so the room is reserved up front, and `/tmp`
    /// stands in when even a short name does not fit under `XDG_RUNTIME_DIR`.
    ///
    /// `reserve` is the longest path the caller will append, the joining `/` included.
    pub fn create_short(reserve: usize) -> io::Result<Self> {
        let mut bases = vec![default_base()];
        if bases[0] != Path::new("/tmp") {
            bases.push(PathBuf::from("/tmp"));
        }
        for base in &bases {
            if base.as_os_str().len() + SHORT_NAME_LENGTH + reserve <= MAX_UNIX_SOCKET_PATH {
                return Self::create_in(base, "vv", 3);
            }
        }
        Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "no runtime directory is short enough to hold a {reserve}-byte socket path; \
                 tried {}",
                bases
                    .iter()
                    .map(|base| base.display().to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        ))
    }

    fn create_in(base: &Path, prefix: &str, random_bytes: usize) -> io::Result<Self> {
        for _ in 0..32 {
            let mut random = [0_u8; 8];
            getrandom::fill(&mut random[..random_bytes])
                .map_err(|error| io::Error::other(error.to_string()))?;
            let width = random_bytes * 2;
            let path = base.join(format!(
                "{prefix}{:0width$x}",
                u64::from_be_bytes(random) >> (64 - random_bytes * 8)
            ));
            match DirBuilder::new().mode(0o700).create(&path) {
                Ok(()) => return Ok(Self { path }),
                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
                Err(error) => return Err(error),
            }
        }
        Err(io::Error::new(
            io::ErrorKind::AlreadyExists,
            "could not allocate a private vvland runtime directory",
        ))
    }
}

fn default_base() -> PathBuf {
    std::env::var_os("XDG_RUNTIME_DIR")
        .map(PathBuf::from)
        .filter(|path| path.is_dir())
        .unwrap_or_else(std::env::temp_dir)
}

impl Drop for RuntimeDirectory {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.path);
    }
}

pub fn write_private_file(path: &Path, bytes: &[u8], mode: u32) -> io::Result<()> {
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(mode)
        .open(path)?;
    file.write_all(bytes)?;
    file.flush()
}

/// The largest `--extra-config` file a session will splice into its generated configuration.
///
/// The text is held in memory, written into the private runtime directory, and parsed by the
/// compositor, so it is bounded like every other caller-supplied input.
pub const MAX_EXTRA_CONFIG_BYTES: u64 = 65_536;

/// Read the `--extra-config` file that is appended to a generated compositor configuration.
///
/// The file is the session's escape hatch for directives vvland does not generate — `exec-once`
/// for a dock or a status bar, extra binds, window rules — because the generated configuration is
/// self-contained and the user's own `hyprland.conf` or `config` is never read. The bytes reach a
/// line-oriented parser verbatim, so the size is bounded and the control characters that parser
/// cannot carry are refused here rather than silently truncating a directive.
pub fn read_extra_config(path: &Path) -> io::Result<String> {
    let describe = |error: io::Error| {
        io::Error::new(
            error.kind(),
            format!("--extra-config {}: {error}", path.display()),
        )
    };
    let metadata = fs::metadata(path).map_err(describe)?;
    if !metadata.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("--extra-config {} is not a regular file", path.display()),
        ));
    }
    if metadata.len() > MAX_EXTRA_CONFIG_BYTES {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "--extra-config {} is {} bytes; the limit is {MAX_EXTRA_CONFIG_BYTES}",
                path.display(),
                metadata.len()
            ),
        ));
    }
    let text = fs::read_to_string(path).map_err(describe)?;
    if let Some(offending) = text
        .chars()
        .find(|character| character.is_control() && !matches!(character, '\n' | '\t'))
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "--extra-config {} contains {offending:?}, which a compositor configuration \
                 cannot carry",
                path.display()
            ),
        ));
    }
    Ok(text)
}

/// Append the user's extra configuration to a generated one, under a banner naming its origin.
///
/// It goes last deliberately: a compositor configuration resolves a repeated directive in favour
/// of the later line, so the escape hatch can override what vvland generated. Overriding the
/// output directives breaks capture, which is the user's call to make.
pub fn push_extra_config(config: &mut String, extra: Option<&str>) {
    let Some(extra) = extra else {
        return;
    };
    if !config.ends_with('\n') {
        config.push('\n');
    }
    config
        .push_str("# --extra-config, appended verbatim; it overrides the generated lines above.\n");
    config.push_str(extra);
    if !extra.ends_with('\n') {
        config.push('\n');
    }
}

pub fn pipe() -> io::Result<(OwnedFd, OwnedFd)> {
    let mut descriptors = [-1; 2];
    // SAFETY: descriptors points to exactly two writable integers.
    if unsafe { libc::pipe2(descriptors.as_mut_ptr(), libc::O_CLOEXEC) } < 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: pipe2 returned two newly owned descriptors.
    Ok(unsafe {
        (
            OwnedFd::from_raw_fd(descriptors[0]),
            OwnedFd::from_raw_fd(descriptors[1]),
        )
    })
}

pub fn socketpair() -> io::Result<(OwnedFd, OwnedFd)> {
    let mut descriptors = [-1; 2];
    // SAFETY: descriptors points to exactly two writable integers.
    let result = unsafe {
        libc::socketpair(
            libc::AF_UNIX,
            libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC,
            0,
            descriptors.as_mut_ptr(),
        )
    };
    if result < 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: socketpair returned two newly owned descriptors.
    Ok(unsafe {
        (
            OwnedFd::from_raw_fd(descriptors[0]),
            OwnedFd::from_raw_fd(descriptors[1]),
        )
    })
}

pub fn start_bounded_log(
    thread_name: &str,
    read_fd: OwnedFd,
    path: PathBuf,
) -> io::Result<thread::JoinHandle<()>> {
    thread::Builder::new()
        .name(thread_name.to_owned())
        .spawn(move || {
            let mut input = File::from(read_fd);
            let Ok(mut output) = OpenOptions::new()
                .create(true)
                .truncate(true)
                .write(true)
                .mode(0o600)
                .open(path)
            else {
                return;
            };
            let mut written = 0_u64;
            let mut buffer = [0_u8; 8192];
            while let Ok(count) = input.read(&mut buffer) {
                if count == 0 {
                    break;
                }
                if written.saturating_add(count as u64) > MAX_LOG_BYTES {
                    if output.set_len(0).is_err() || output.seek(SeekFrom::Start(0)).is_err() {
                        break;
                    }
                    written = 0;
                }
                if output.write_all(&buffer[..count]).is_err() {
                    break;
                }
                written = written.saturating_add(count as u64);
            }
        })
}

/// Append the bounded tail of a compositor log to a startup failure.
pub fn startup_error(summary: String, compositor_name: &str, log_path: &Path) -> io::Error {
    let Ok(log) = fs::read(log_path) else {
        return io::Error::other(summary);
    };
    let start = log.len().saturating_sub(ERROR_LOG_BYTES);
    let tail = String::from_utf8_lossy(&log[start..]);
    let tail = tail.trim();
    if tail.is_empty() {
        io::Error::other(summary)
    } else {
        io::Error::other(format!("{summary}; {compositor_name} log:\n{tail}"))
    }
}

pub fn terminate_group(group: i32, child: &mut Child) {
    // SAFETY: the negative PID targets only the process group created for this compositor child.
    unsafe {
        libc::kill(-group, libc::SIGTERM);
    }
    let deadline = Instant::now() + Duration::from_secs(2);
    while Instant::now() < deadline {
        let _ = child.try_wait();
        if !process_group_exists(group) {
            return;
        }
        thread::sleep(Duration::from_millis(20));
    }
    // SAFETY: the owned process group did not exit after SIGTERM.
    unsafe {
        libc::kill(-group, libc::SIGKILL);
    }
    let _ = child.wait();
}

pub fn process_group_exists(group: i32) -> bool {
    // SAFETY: signal zero only checks whether the owned process group still exists.
    if unsafe { libc::kill(-group, 0) } == 0 {
        return true;
    }
    io::Error::last_os_error().kind() == io::ErrorKind::PermissionDenied
}

pub fn command_in_path(program: &str) -> bool {
    std::env::var_os("PATH").is_some_and(|paths| {
        std::env::split_paths(&paths).any(|path| {
            let candidate = path.join(program);
            candidate.is_file()
                && candidate
                    .metadata()
                    .is_ok_and(|metadata| metadata.permissions().mode() & 0o111 != 0)
        })
    })
}

pub fn xwayland_enabled(policy: Xwayland) -> bool {
    match policy {
        Xwayland::On => true,
        Xwayland::Off => false,
        Xwayland::Auto => command_in_path("Xwayland"),
    }
}

/// Strip every variable that would leak this session's credentials or the host's display.
///
/// Unified on the Sway superset and applied to every compositor and every launched program:
/// a nested client that inherits the outer `WAYLAND_DISPLAY` connects to the wrong compositor,
/// and `VIVID_*` carries the root secret. `PIPEWIRE_RUNTIME_DIR` and the private Pulse routing
/// are re-set explicitly afterwards by the backends that need them.
pub fn sanitize_child_environment(command: &mut Command) {
    for (name, _) in std::env::vars_os() {
        if remove_child_environment(&name) {
            command.env_remove(name);
        }
    }
}

pub fn remove_child_environment(name: &OsStr) -> bool {
    let name = name.to_string_lossy();
    name.starts_with("VIVID_")
        || name.starts_with("WLR_")
        || matches!(
            name.as_ref(),
            "WAYLAND_DISPLAY"
                | "WAYLAND_SOCKET"
                | "DISPLAY"
                | "SWAYSOCK"
                | "I3SOCK"
                // An outer Hyprland's instance signature would point a nested client's `hyprctl`
                // at the host compositor rather than this session's.
                | "HYPRLAND_INSTANCE_SIGNATURE"
                | "HYPRLAND_CMD"
                | "PULSE_SERVER"
                | "PULSE_SINK"
                | "PULSE_SOURCE"
        )
}

/// How long a launched application is given to fall over before it counts as running.
const LIVENESS_PROBE: Duration = Duration::from_millis(500);

/// Whether launched children should keep their stdout/stderr.
///
/// Off by default: a chatty browser writing to the producer's terminal corrupts the very display
/// this session is streaming. `VVLAND_CHILD_LOGS` turns it back on for debugging.
pub fn child_logs_enabled() -> bool {
    std::env::var_os("VVLAND_CHILD_LOGS").is_some_and(|value| !value.is_empty())
}

pub fn child_output() -> (Stdio, Stdio) {
    if child_logs_enabled() {
        (Stdio::inherit(), Stdio::inherit())
    } else {
        (Stdio::null(), Stdio::null())
    }
}

/// Confirm a freshly spawned application did not exit immediately.
///
/// A Wayland client that cannot reach the compositor — wrong `WAYLAND_DISPLAY`, missing binary
/// dependency, snap confinement refusing the socket — dies within milliseconds and otherwise
/// leaves a silent black desktop with no explanation (kitweb `browser.rs:41-44, 95-98`).
pub fn confirm_started(name: &str, child: &mut Child) -> io::Result<()> {
    thread::sleep(LIVENESS_PROBE);
    match child.try_wait()? {
        Some(status) => Err(io::Error::other(format!(
            "{name} exited immediately with status {status}"
        ))),
        None => Ok(()),
    }
}

/// Point a launched client at one session: its private runtime directory, display, and Pulse
/// routing. Shared because every direct-spawn backend needs exactly this set.
pub fn set_client_environment(
    command: &mut Command,
    runtime: &Path,
    wayland_display: &str,
    pulse_server: Option<&OsStr>,
    pulse_sink: Option<&OsStr>,
) {
    command
        .env("XDG_RUNTIME_DIR", runtime)
        .env("WAYLAND_DISPLAY", wayland_display);
    set_pulse_environment(command, pulse_server, pulse_sink);
}

pub fn set_pulse_environment(
    command: &mut Command,
    pulse_server: Option<&OsStr>,
    pulse_sink: Option<&OsStr>,
) {
    if let Some(server) = pulse_server {
        command.env("PULSE_SERVER", server);
    }
    if let Some(sink) = pulse_sink {
        command.env("PULSE_SINK", sink);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extra_config_is_read_bounded_and_single_line_safe() {
        let directory = RuntimeDirectory::create().expect("private runtime directory");
        let path = directory.path.join("extra.conf");

        fs::write(&path, "exec-once = nwg-dock-hyprland\n").expect("write extra config");
        assert_eq!(
            read_extra_config(&path).expect("readable extra config"),
            "exec-once = nwg-dock-hyprland\n"
        );

        // A NUL or an escape sequence would be truncated or reinterpreted by the parser.
        fs::write(&path, "exec-once = dock\u{1b}[2J\n").expect("write hostile extra config");
        let error = read_extra_config(&path).expect_err("control characters are refused");
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);

        fs::write(&path, vec![b'#'; MAX_EXTRA_CONFIG_BYTES as usize + 1]).expect("write oversize");
        let error = read_extra_config(&path).expect_err("oversize files are refused");
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);

        let error =
            read_extra_config(&directory.path).expect_err("a directory is not a config file");
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);

        let error = read_extra_config(&directory.path.join("absent.conf"))
            .expect_err("a missing file is reported, not ignored");
        assert_eq!(error.kind(), io::ErrorKind::NotFound);
    }

    #[test]
    fn extra_config_is_appended_last_and_newline_terminated() {
        let mut config = "monitor = , disable\n".to_owned();
        push_extra_config(&mut config, None);
        assert_eq!(config, "monitor = , disable\n");

        // The generated body stays intact and the extra directives follow it, so a repeated
        // directive resolves in the caller's favour.
        push_extra_config(&mut config, Some("exec-once = waybar"));
        assert!(config.starts_with("monitor = , disable\n"), "{config}");
        assert!(config.ends_with("exec-once = waybar\n"), "{config}");
        assert!(config.contains("# --extra-config"), "{config}");
    }

    #[test]
    fn child_environment_filter_excludes_credentials_and_host_display() {
        // The 1.5 discovery names and the root secret must never reach a launched child, and a
        // nested client must never inherit the host compositor's display.
        for name in [
            "VIVID_ENDPOINT_CONTROL",
            "VIVID_ENDPOINT_INTERACTIVE",
            "VIVID_ENDPOINT_REALTIME",
            "VIVID_ENDPOINT_BULK",
            "VIVID_ROOT_SECRET",
            "VIVID_TOKEN",
            "WLR_RENDERER",
            "WAYLAND_DISPLAY",
            "WAYLAND_SOCKET",
            "DISPLAY",
            "SWAYSOCK",
            "I3SOCK",
            "HYPRLAND_INSTANCE_SIGNATURE",
            "HYPRLAND_CMD",
            "PULSE_SERVER",
            "PULSE_SINK",
            "PULSE_SOURCE",
        ] {
            assert!(remove_child_environment(OsStr::new(name)), "{name}");
        }
        assert!(!remove_child_environment(OsStr::new("PATH")));
        assert!(!remove_child_environment(OsStr::new("HOME")));
        assert!(!remove_child_environment(OsStr::new(
            "PIPEWIRE_RUNTIME_DIR"
        )));
    }

    #[test]
    fn sanitized_child_environment_strips_every_vivid_secret() {
        let _guard = crate::cli::tests::TEST_ENV_LOCK.lock().unwrap();
        // SAFETY: test-only environment mutation, isolated to this test's process.
        unsafe {
            std::env::set_var("VIVID_ROOT_SECRET", "0123456789abcdef0123456789abcdef");
            std::env::set_var("VIVID_ENDPOINT_CONTROL", "unix:/tmp/vivid.sock");
            std::env::set_var("SWAYSOCK", "/run/user/1000/sway.sock");
        }
        let mut command = Command::new("true");
        sanitize_child_environment(&mut command);
        for (name, value) in command.get_envs() {
            // A removed variable appears with a `None` value; a leaked one keeps its value.
            if value.is_none() {
                continue;
            }
            let name = name.to_string_lossy();
            assert!(
                !name.starts_with("VIVID_") && !name.starts_with("SWAYSOCK"),
                "child environment leaked {name}"
            );
        }
        // The ordinary environment survives.
        assert!(std::env::var_os("PATH").is_some());
    }

    #[test]
    fn child_logs_are_off_unless_explicitly_enabled() {
        let _guard = crate::cli::tests::TEST_ENV_LOCK.lock().unwrap();
        // SAFETY: test-only environment mutation, isolated to this test's process.
        unsafe { std::env::remove_var("VVLAND_CHILD_LOGS") };
        assert!(!child_logs_enabled());
        // SAFETY: test-only environment mutation, reverted below.
        unsafe { std::env::set_var("VVLAND_CHILD_LOGS", "") };
        assert!(!child_logs_enabled(), "an empty value stays off");
        // SAFETY: test-only environment mutation, reverted below.
        unsafe { std::env::set_var("VVLAND_CHILD_LOGS", "1") };
        assert!(child_logs_enabled());
        // SAFETY: test-only environment mutation, restoring the default.
        unsafe { std::env::remove_var("VVLAND_CHILD_LOGS") };
    }

    #[test]
    fn an_application_that_exits_immediately_is_reported() {
        let mut failing = Command::new("sh")
            .args(["-c", "exit 3"])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .unwrap();
        let error = confirm_started("google-chrome", &mut failing).unwrap_err();
        let message = error.to_string();
        assert!(message.contains("google-chrome"), "{message}");
        assert!(message.contains("exited immediately"), "{message}");

        let mut living = Command::new("sleep")
            .arg("30")
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .unwrap();
        assert!(confirm_started("google-chrome", &mut living).is_ok());
        let _ = living.kill();
        let _ = living.wait();
    }

    #[test]
    fn runtime_directory_is_private_and_removed() {
        let runtime = RuntimeDirectory::create().unwrap();
        let path = runtime.path.clone();
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o700
        );
        drop(runtime);
        assert!(!path.exists());
    }

    #[test]
    fn bounded_log_never_exceeds_its_cap() {
        let runtime = RuntimeDirectory::create().unwrap();
        let log = runtime.path.join("bounded.log");
        let (read, write) = pipe().unwrap();
        let logger = start_bounded_log("vvland-test-log", read, log.clone()).unwrap();
        let mut writer = File::from(write);
        writer
            .write_all(&vec![b'x'; MAX_LOG_BYTES as usize + 1])
            .unwrap();
        drop(writer);
        logger.join().unwrap();
        assert!(fs::metadata(log).unwrap().len() <= MAX_LOG_BYTES);
    }

    #[test]
    fn termination_cleans_descendants_after_the_compositor_exits() {
        use std::io::BufRead;
        use std::os::unix::process::CommandExt;
        use std::process::Stdio;
        let mut command = Command::new("sh");
        command
            .args(["-c", "sleep 30 & printf '%s\n' \"$!\""])
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::null());
        // SAFETY: setpgid is async-signal-safe and creates a group owned by this test child.
        unsafe {
            command.pre_exec(|| {
                if libc::setpgid(0, 0) < 0 {
                    return Err(io::Error::last_os_error());
                }
                Ok(())
            });
        }
        let mut child = command.spawn().unwrap();
        let group = i32::try_from(child.id()).unwrap();
        let mut descendant = String::new();
        std::io::BufReader::new(child.stdout.take().unwrap())
            .read_line(&mut descendant)
            .unwrap();
        let descendant = descendant.trim().parse::<i32>().unwrap();
        assert!(child.wait().unwrap().success());
        assert!(process_group_exists(group));

        terminate_group(group, &mut child);

        assert!(!process_group_exists(group));
        // SAFETY: signal zero only verifies that the reported descendant PID is gone.
        assert_eq!(unsafe { libc::kill(descendant, 0) }, -1);
    }
}