targeted-mutation 0.20.2

Targeted mutation testing for Rust: find the wrong implementations your tests let through
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
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use anyhow::{Context, Result, bail};

/// Holds the work directory's lock until the OS closes the file handle.
pub(crate) struct WorkLock {
    _file: Arc<File>,
}

impl WorkLock {
    /// Keep the lock across exec in a child that uses the working copy. A
    /// command that has been configured but not started keeps the file alive
    /// so it cannot accidentally inherit a reused descriptor.
    #[cfg(unix)]
    pub(crate) fn retain_for(&self, command: &mut Command) {
        use std::os::fd::AsRawFd;
        use std::os::unix::process::CommandExt;

        let file = Arc::clone(&self._file);
        // SAFETY: the child's inherited File is still open, and the hook only
        // borrows its descriptor and performs async-signal-safe fcntl calls.
        unsafe { command.pre_exec(move || inherit_lock(file.as_raw_fd())) };
    }

    #[cfg(not(unix))]
    pub(crate) fn retain_for(&self, _: &mut Command) {
        // The exclusive Windows handle is owned by the parent.
    }

    pub(crate) fn take(work: &Path) -> Result<Self> {
        let dir = lock_directory(work)?;
        let path = dir.join("owner");
        match acquire(&path) {
            Ok(file) => {
                write_holder_pid(&dir);
                Ok(Self {
                    _file: Arc::new(file),
                })
            }
            Err(err) if contended(&err) => {
                let holder = read_holder_pid(&dir)
                    .map(|pid| format!(" (last recorded pid {pid})"))
                    .unwrap_or_default();
                bail!(
                    "another tmt run is using {}{holder}; pass a separate --work-dir to run in parallel",
                    work.display()
                )
            }
            Err(err) => Err(err).with_context(|| format!("locking {}", path.display())),
        }
    }
}

/// Best-effort atomic write of the lock holder's PID for contention diagnostics.
/// Never fails lock acquisition and never follows a symlink at the destination.
fn write_holder_pid(dir: &Path) {
    static NEXT_TMP: AtomicUsize = AtomicUsize::new(0);
    let pid = std::process::id();
    let seq = NEXT_TMP.fetch_add(1, Ordering::Relaxed);
    let tmp = dir.join(format!(".pid.{pid}.{seq}.tmp"));
    let target = dir.join("pid");
    let created = OpenOptions::new().write(true).create_new(true).open(&tmp);
    let Ok(mut file) = created else {
        let _ = fs::remove_file(&target);
        return;
    };
    if writeln!(file, "{pid}").is_err() {
        drop(file);
        let _ = fs::remove_file(&tmp);
        let _ = fs::remove_file(&target);
        return;
    }
    drop(file);
    if fs::rename(&tmp, &target).is_err() {
        let _ = fs::remove_file(&tmp);
        let _ = fs::remove_file(&target);
    }
}

fn read_holder_pid(dir: &Path) -> Option<u32> {
    let path = dir.join("pid");
    let mut options = OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        // O_NOFOLLOW rejects symlinks atomically; O_NONBLOCK prevents blocking on a FIFO.
        #[cfg(any(
            target_os = "macos",
            target_os = "ios",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd",
            target_os = "dragonfly"
        ))]
        const FLAGS: i32 = 0x0100 | 0x0004; // O_NOFOLLOW | O_NONBLOCK
        #[cfg(all(target_os = "linux", any(target_arch = "x86_64", target_arch = "x86")))]
        const FLAGS: i32 = 0o400000 | 0o4000; // O_NOFOLLOW | O_NONBLOCK
        #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
        const FLAGS: i32 = 0o100000 | 0o4000; // O_NOFOLLOW | O_NONBLOCK
        #[cfg(not(any(
            target_os = "macos",
            target_os = "ios",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd",
            target_os = "dragonfly",
            all(
                target_os = "linux",
                any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64")
            )
        )))]
        const FLAGS: i32 = 0;
        if FLAGS == 0 {
            return None;
        }
        options.custom_flags(FLAGS);
    }
    #[cfg(windows)]
    {
        use std::os::windows::fs::OpenOptionsExt;
        const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x00200000;
        options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
    }
    let file = options.open(&path).ok()?;
    let meta = file.metadata().ok()?;
    if is_link(&meta) || !meta.is_file() || meta.len() > 64 {
        return None;
    }
    let mut buf = String::new();
    file.take(65).read_to_string(&mut buf).ok()?;
    if buf.len() > 64 {
        return None;
    }
    buf.trim().parse::<u32>().ok().filter(|&pid| pid > 0)
}

/// A directory at the old sentinel's path makes the two protocols exclude
/// one another. Creating the directory is atomic. If stopped before opening
/// its owner file, the next run can still initialize it.
fn lock_directory(work: &Path) -> Result<PathBuf> {
    let path = work.join(".tmt-lock");
    match fs::create_dir(&path) {
        Ok(()) => {}
        // tmt:ignore any other failure to create the directory is a failure all the same: there is then no lock directory to inspect or to open the owner file in
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
            let existing = fs::symlink_metadata(&path)
                .with_context(|| format!("inspecting {}", path.display()))?;
            // tmt:ignore on Unix a link is never reported as a file; the test for a link is for Windows reparse points
            if !is_link(&existing) && existing.is_file() {
                bail!(
                    "{} is a legacy TMT lock file. Choose a fresh --work-dir, or remove \
                     the legacy file after all older TMT runs using this directory have ended",
                    path.display()
                );
            }
            // tmt:ignore on Unix a link is never reported as a directory (the test for a link is for Windows reparse points), and what is not a directory cannot hold the owner file, so taking the lock fails without this too; this says why
            if is_link(&existing) || !existing.is_dir() {
                bail!("{} must be a real lock directory", path.display());
            }
        }
        Err(error) => return Err(error).with_context(|| format!("creating {}", path.display())),
    }
    Ok(path)
}

#[cfg(unix)]
pub(crate) fn inherit_lock(fd: std::os::fd::RawFd) -> io::Result<()> {
    use std::os::raw::c_int;

    unsafe extern "C" {
        fn fcntl(fd: c_int, command: c_int, ...) -> c_int;
    }
    const F_GETFD: c_int = 1;
    const F_SETFD: c_int = 2;
    const FD_CLOEXEC: c_int = 1;

    // SAFETY: the borrowed descriptor belongs to the command's open lock.
    let flags = unsafe { fcntl(fd, F_GETFD) };
    if flags == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: F_SETFD accepts one c_int argument. This updates only the
    // descriptor in the child, leaving other spawned commands unaffected.
    if unsafe { fcntl(fd, F_SETFD, flags & !FD_CLOEXEC) } == -1 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

pub(crate) fn acquire(path: &Path) -> io::Result<File> {
    let mut options = OpenOptions::new();
    options.read(true).write(true);
    #[cfg(windows)]
    {
        use std::os::windows::fs::OpenOptionsExt;
        const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x00200000;
        // No other handle may open the file for read, write or delete.
        options
            .share_mode(0)
            .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
    }

    let file = match options.create_new(true).open(path) {
        Ok(file) => file,
        // tmt:ignore after any other failure to create the file there is nothing to open: inspecting the path fails as well
        Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
            // tmt:ignore refuses a link before its target is opened; the checks after the open refuse the same paths
            require_regular(&fs::symlink_metadata(path)?)?;
            options.create_new(false).open(path)?
        }
        Err(err) => return Err(err),
    };
    let opened = file.metadata()?;
    // tmt:ignore differs from the check before the open only if the path is replaced in between, which a test cannot provoke
    require_regular(&opened)?;
    lock_open_file(&file)?;

    // Do not unlink this path on release: another contender may already have
    // opened this inode. Also check that it wasn't replaced during acquisition.
    let named = fs::symlink_metadata(path)?;
    // tmt:ignore differs from the checks above only if the path is replaced during acquisition, which a test cannot provoke
    require_regular(&named)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        // tmt:ignore true only if the path is replaced during acquisition, which a test cannot provoke
        if (opened.dev(), opened.ino()) != (named.dev(), named.ino()) {
            return Err(io::Error::other(
                "lock file was replaced during acquisition",
            ));
        }
    }
    Ok(file)
}

fn require_regular(metadata: &fs::Metadata) -> io::Result<()> {
    // tmt:ignore on Unix a link is never reported as a file; the test for a link is for Windows reparse points
    if metadata.is_file() && !is_link(metadata) {
        Ok(())
    } else {
        Err(io::Error::other("lock path must be a regular file"))
    }
}

// tmt:ignore on Unix every caller also requires a file or a directory, which a link is not; this matters for Windows reparse points
fn is_link(metadata: &fs::Metadata) -> bool {
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
        if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            return true;
        }
    }
    metadata.file_type().is_symlink()
}

pub(crate) fn contended(error: &io::Error) -> bool {
    #[cfg(windows)]
    if error.raw_os_error() == Some(32) {
        // ERROR_SHARING_VIOLATION
        return true;
    }
    error.kind() == io::ErrorKind::WouldBlock
}

#[cfg(unix)]
pub(crate) fn lock_open_file(file: &File) -> io::Result<()> {
    use std::os::fd::AsRawFd;
    use std::os::raw::c_int;

    unsafe extern "C" {
        fn flock(fd: c_int, operation: c_int) -> c_int;
    }
    const LOCK_EX: c_int = 2;
    const LOCK_NB: c_int = 4;

    loop {
        // SAFETY: the File owns this descriptor throughout the call, and the
        // two flags request a nonblocking exclusive lock.
        // tmt:ignore the bits do not overlap, so `^` joins them just as well
        if unsafe { flock(file.as_raw_fd(), LOCK_EX | LOCK_NB) } == 0 {
            return Ok(());
        }
        let error = io::Error::last_os_error();
        // tmt:ignore a nonblocking flock is interrupted only by a signal at the right instant, which a test cannot provoke
        if error.kind() != io::ErrorKind::Interrupted {
            return Err(error);
        }
    }
}

#[cfg(windows)]
pub(crate) fn lock_open_file(_: &File) -> io::Result<()> {
    // The exclusive open acquired the lock.
    Ok(())
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn lock_open_file(_: &File) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "work directory locking is unavailable on this platform",
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use std::path::PathBuf;
    use std::process::{Child, Command, Stdio};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::{Duration, Instant};

    struct Scratch(PathBuf);

    impl Scratch {
        fn new() -> Self {
            static NEXT: AtomicUsize = AtomicUsize::new(0);
            let dir = std::env::temp_dir().join(format!(
                "tmt-work-lock-{}-{}",
                std::process::id(),
                NEXT.fetch_add(1, Ordering::Relaxed)
            ));
            fs::create_dir(&dir).unwrap();
            Self(dir)
        }
    }

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

    struct LockChild(Child);

    impl Drop for LockChild {
        fn drop(&mut self) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }

    fn seed_owner(work: &Path, contents: &[u8]) {
        let reserved = work.join(".tmt-lock");
        fs::create_dir(&reserved).unwrap();
        fs::write(reserved.join("owner"), contents).unwrap();
    }

    const TEST_DIR: &str = "TMT_WORK_LOCK_UNIT_TEST_DIR";

    #[test]
    fn child_owns_lock_until_stdin_or_process_ends() {
        if let Some(work) = std::env::var_os(TEST_DIR) {
            let work = Path::new(&work);
            let _lock = WorkLock::take(work).unwrap();
            fs::write(work.join("ready"), []).unwrap();
            let _ = std::io::stdin().read_line(&mut String::new()).unwrap();
        }
    }

    fn lock_child(work: &Path) -> LockChild {
        let module = module_path!().split_once("::").unwrap().1;
        let mut child = LockChild(
            Command::new(std::env::current_exe().unwrap())
                .args([
                    "--exact",
                    &format!("{module}::child_owns_lock_until_stdin_or_process_ends"),
                    "--nocapture",
                ])
                .env(TEST_DIR, work)
                .stdin(Stdio::piped())
                .stdout(Stdio::null())
                .spawn()
                .unwrap(),
        );
        let started = Instant::now();
        while !work.join("ready").is_file() {
            assert_eq!(
                child.0.try_wait().unwrap(),
                None,
                "holder exited before taking lock"
            );
            assert!(
                started.elapsed() < Duration::from_secs(5),
                "holder never took lock"
            );
            std::thread::sleep(Duration::from_millis(10));
        }
        child
    }

    /// Takes a lock that this process has just let go of. Tests run on threads of one
    /// process, and a child that another test starts holds a copy of every open file
    /// between its fork and its exec, the lock that was just released among them: for
    /// that moment the lock still looks taken. (A run takes its lock once and keeps it,
    /// so only tests see this.)
    fn take_released(work: &Path) -> WorkLock {
        let patience = std::time::Instant::now() + std::time::Duration::from_secs(10);
        loop {
            match WorkLock::take(work) {
                Ok(lock) => return lock,
                Err(err) if std::time::Instant::now() < patience => {
                    assert!(
                        err.to_string().contains("another tmt run is using"),
                        "{err:#}"
                    );
                    std::thread::sleep(std::time::Duration::from_millis(5));
                }
                Err(err) => panic!("the released lock stayed taken: {err:#}"),
            }
        }
    }

    fn assert_contended(work: &Path) {
        let err = WorkLock::take(work).err().expect("second owner took lock");
        assert!(
            err.to_string().contains("another tmt run is using"),
            "{err:#}"
        );
        assert!(err.to_string().contains("--work-dir"), "{err:#}");
        assert!(!err.to_string().contains("delete"), "{err:#}");
    }

    #[test]
    fn live_owner_is_exclusive_and_operations_reuse_the_same_file() {
        // All six valid rows of the three-way lock PICT table.
        for (existing_owner, child, killed) in [
            (false, false, false),
            (true, true, true),
            (true, true, false),
            (true, false, false),
            (false, true, true),
            (false, true, false),
        ] {
            let work = Scratch::new();
            let marker = work.0.join(".tmt-lock/owner");
            if existing_owner {
                seed_owner(&work.0, &[]);
            }
            if child {
                let mut holder = lock_child(&work.0);
                assert_contended(&work.0);
                if killed {
                    holder.0.kill().unwrap();
                } else {
                    holder.0.stdin.take().unwrap().write_all(b"done\n").unwrap();
                }
                assert_eq!(holder.0.wait().unwrap().success(), !killed);
            } else {
                let _holder = WorkLock::take(&work.0).unwrap();
                assert_contended(&work.0);
            }
            assert!(marker.is_file(), "release removed the lock file");
            let _next = take_released(&work.0);
            assert_contended(&work.0);
        }
    }

    #[cfg(unix)]
    #[test]
    fn registered_child_keeps_the_lock_until_it_exits() {
        // All eight rows of the child handoff PICT table.
        for (existing_owner, parent_first, killed) in [
            (false, true, true),
            (true, false, false),
            (true, true, true),
            (true, true, false),
            (true, false, true),
            (false, true, false),
            (false, false, true),
            (false, false, false),
        ] {
            let work = Scratch::new();
            if existing_owner {
                seed_owner(&work.0, &[]);
            }
            let lock = WorkLock::take(&work.0).unwrap();
            let mut cmd = Command::new("sh");
            cmd.args(["-c", "read -r line"]).stdin(Stdio::piped());
            lock.retain_for(&mut cmd);
            // A command that was not registered never inherits the lock.
            let unrelated = LockChild(
                Command::new("sh")
                    .args(["-c", "read -r line"])
                    .stdin(Stdio::piped())
                    .spawn()
                    .unwrap(),
            );
            let mut child = LockChild(cmd.spawn().unwrap());
            drop(cmd);
            let mut parent = Some(lock);
            if parent_first {
                parent.take();
            }
            assert_contended(&work.0);

            if killed {
                child.0.kill().unwrap();
            } else {
                child.0.stdin.take().unwrap().write_all(b"done\n").unwrap();
            }
            assert_eq!(child.0.wait().unwrap().success(), !killed);
            if !parent_first {
                assert_contended(&work.0);
            }
            drop(parent);
            let _next = take_released(&work.0);
            drop(unrelated);
        }
    }

    #[test]
    fn leaves_an_existing_regular_file_intact_and_rejects_a_directory() {
        let work = Scratch::new();
        let marker = work.0.join(".tmt-lock/owner");
        fs::create_dir_all(&marker).unwrap();
        assert!(WorkLock::take(&work.0).is_err());
        assert!(marker.is_dir());
        fs::remove_dir(&marker).unwrap();

        fs::write(&marker, "keep this content").unwrap();
        drop(WorkLock::take(&work.0).unwrap());
        assert_eq!(fs::read_to_string(&marker).unwrap(), "keep this content");
    }

    #[test]
    fn an_unusable_owner_path_is_not_reported_as_another_run() {
        let work = Scratch::new();
        let marker = work.0.join(".tmt-lock/owner");
        fs::create_dir_all(&marker).unwrap();
        let error = WorkLock::take(&work.0).err().expect("locked a directory");
        let text = format!("{error:#}");
        // Waiting for the other run to end would never help here.
        assert!(!text.contains("another tmt run"), "{text}");
        assert!(text.contains("locking"), "{text}");
        assert!(text.contains(&marker.display().to_string()), "{text}");
        assert!(text.contains("must be a regular file"), "{text}");
    }

    #[cfg(unix)]
    #[test]
    fn rejects_an_owner_that_is_neither_a_file_nor_a_link() {
        let work = Scratch::new();
        let marker = work.0.join(".tmt-lock/owner");
        fs::create_dir(marker.parent().unwrap()).unwrap();
        let made = Command::new("mkfifo").arg(&marker).status().unwrap();
        assert!(made.success());
        // A FIFO can be opened for reading and writing, and some systems lock one.
        for _ in 0..2 {
            let error = WorkLock::take(&work.0).err().expect("locked a FIFO");
            let text = format!("{error:#}");
            assert!(text.contains("must be a regular file"), "{text}");
            assert!(!text.contains("another tmt run"), "{text}");
        }
        use std::os::unix::fs::FileTypeExt;
        assert!(fs::symlink_metadata(&marker).unwrap().file_type().is_fifo());
    }

    #[test]
    fn legacy_sentinel_requires_migration_and_cannot_race_current_lock() {
        let work = Scratch::new();
        let marker = work.0.join(".tmt-lock");
        let legacy_open = || {
            OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&marker)
        };
        let legacy = legacy_open().unwrap();

        let check_migration = || {
            let error = WorkLock::take(&work.0)
                .err()
                .expect("new process acquired a legacy lock");
            assert!(error.to_string().contains("legacy TMT lock"), "{error:#}");
            assert!(error.to_string().contains("--work-dir"), "{error:#}");
        };
        check_migration();
        drop(legacy);
        check_migration();
        fs::remove_file(&marker).unwrap();

        let current = WorkLock::take(&work.0).unwrap();
        assert!(legacy_open().is_err());
        drop(current);
        assert!(legacy_open().is_err());
    }

    #[test]
    fn recovers_after_interruption_before_owner_file_creation() {
        let work = Scratch::new();
        let reserved = work.0.join(".tmt-lock");
        fs::create_dir(&reserved).unwrap();

        let current = WorkLock::take(&work.0).unwrap();
        assert!(reserved.join("owner").is_file());
        assert_contended(&work.0);
        drop(current);
        drop(take_released(&work.0));
    }

    #[cfg(unix)]
    #[test]
    fn rejects_symlinks_without_creating_or_changing_their_targets() {
        let work = Scratch::new();
        let marker = work.0.join(".tmt-lock");
        let target = work.0.join("target");
        std::os::unix::fs::symlink(&target, &marker).unwrap();
        assert!(WorkLock::take(&work.0).is_err());
        assert!(!target.exists());
        fs::create_dir(&target).unwrap();
        assert!(WorkLock::take(&work.0).is_err());
        assert!(!target.join("owner").exists());
        fs::remove_dir(&target).unwrap();
        fs::remove_file(&marker).unwrap();

        fs::create_dir(&marker).unwrap();
        std::os::unix::fs::symlink(&target, marker.join("owner")).unwrap();
        fs::write(&target, "outside the reserved path").unwrap();
        assert!(WorkLock::take(&work.0).is_err());
        assert_eq!(
            fs::read_to_string(&target).unwrap(),
            "outside the reserved path"
        );
    }

    #[test]
    fn contention_reports_holder_pid_and_handles_missing_or_corrupt_pid_file() {
        let work = Scratch::new();
        let mut holder = lock_child(&work.0);
        let child_pid = holder.0.id();
        let err = WorkLock::take(&work.0)
            .err()
            .expect("second owner took lock")
            .to_string();
        assert!(err.contains("another tmt run is using"), "{err}");
        assert!(
            err.contains(&format!("(last recorded pid {child_pid})")),
            "expected holder pid in error: {err}"
        );
        assert!(err.contains("--work-dir"), "{err}");

        // Corrupt, oversized, symlink, FIFO, or missing PID file still produces the
        // contention error and --work-dir hint without blocking.
        let pid_path = work.0.join(".tmt-lock/pid");
        fs::write(&pid_path, "not-a-pid\n").unwrap();
        let err = WorkLock::take(&work.0).err().unwrap().to_string();
        assert!(!err.contains("last recorded pid"), "{err}");
        assert!(err.contains("--work-dir"), "{err}");

        fs::write(&pid_path, "0\n").unwrap();
        let err = WorkLock::take(&work.0).err().unwrap().to_string();
        assert!(!err.contains("last recorded pid"), "{err}");
        assert!(err.contains("--work-dir"), "{err}");

        fs::write(&pid_path, "1".repeat(80)).unwrap();
        let err = WorkLock::take(&work.0).err().unwrap().to_string();
        assert!(!err.contains("last recorded pid"), "{err}");
        assert!(err.contains("--work-dir"), "{err}");

        #[cfg(unix)]
        {
            let outside = work.0.join("outside-pid");
            fs::write(&outside, "99999\n").unwrap();
            fs::remove_file(&pid_path).unwrap();
            std::os::unix::fs::symlink(&outside, &pid_path).unwrap();
            let err = WorkLock::take(&work.0).err().unwrap().to_string();
            assert!(!err.contains("99999"), "{err}");
            assert!(!err.contains("last recorded pid"), "{err}");
            assert!(err.contains("--work-dir"), "{err}");

            fs::remove_file(&pid_path).unwrap();
            assert!(
                Command::new("mkfifo")
                    .arg(&pid_path)
                    .status()
                    .unwrap()
                    .success()
            );
            let err = WorkLock::take(&work.0).err().unwrap().to_string();
            assert!(!err.contains("last recorded pid"), "{err}");
            assert!(err.contains("--work-dir"), "{err}");
        }

        fs::remove_file(&pid_path).unwrap();
        let err = WorkLock::take(&work.0).err().unwrap().to_string();
        assert!(!err.contains("last recorded pid"), "{err}");
        assert!(err.contains("--work-dir"), "{err}");

        holder.0.stdin.take().unwrap().write_all(b"done\n").unwrap();
        assert!(holder.0.wait().unwrap().success());
    }
}