proc-cli 2.0.2

Semantic CLI tool for process management. Target by port, PID, name or path.
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
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
//! Cross-platform process abstraction
//!
//! Provides a unified interface for discovering and managing processes
//! across macOS, Linux, and Windows.

use crate::core::name_match::{classify, Hit, NameMatch, Names};
use crate::error::{ProcError, Result};
use serde::{Deserialize, Serialize};
use std::sync::OnceLock;
use std::time::Duration;
use sysinfo::{Pid, ProcessStatus as SysProcessStatus, System, Uid, Users};

/// Resolve a user ID to its user name, falling back to the ID itself.
/// The user list is read once per run.
fn user_name(uid: &Uid) -> String {
    static USERS: OnceLock<Users> = OnceLock::new();
    USERS
        .get_or_init(Users::new_with_refreshed_list)
        .get_user_by_id(uid)
        .map(|user| user.name().to_string())
        .unwrap_or_else(|| uid.to_string())
}

/// Make text from other processes safe to print: control characters become
/// visible escapes, as `lsof` and `ps` do. Names, command lines and paths are
/// set by whoever runs a process, and printed raw an ESC sequence could
/// recolour, retitle or rewrite the terminal of whoever runs proc (and a
/// newline would split a table row). Applied where process data is read, so
/// every view and the JSON show the same text.
///
/// Escaped: C0 controls and DEL (`\x1b`, with `\n`, `\r`, `\t` by name), C1
/// controls (`\x9b`), and bidirectional overrides that reorder text on screen
/// (`\u{202e}`). Everything else, non-ASCII included, is unchanged. Works on
/// chars, never byte offsets, so it can't split a character.
pub fn escape_control(text: &str) -> std::borrow::Cow<'_, str> {
    fn needs_escape(c: char) -> bool {
        c.is_control()
            || matches!(c, '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
    }
    if !text.chars().any(needs_escape) {
        return std::borrow::Cow::Borrowed(text);
    }
    let mut out = String::with_capacity(text.len() + 8);
    for c in text.chars() {
        match c {
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c.is_control() => out.push_str(&format!("\\x{:02x}", c as u32)),
            c if needs_escape(c) => out.push_str(&format!("\\u{{{:x}}}", c as u32)),
            c => out.push(c),
        }
    }
    std::borrow::Cow::Owned(out)
}

/// `stuck` and `unstick` take this many readings, this far apart, and a process
/// must look stuck in every one
const STUCK_READINGS: usize = 2;
const STUCK_READING_GAP: Duration = Duration::from_secs(1);

/// Stuck in one reading: busy (over half a core), or in uninterruptible sleep,
/// blocked in the kernel (usually on I/O) where it can't even be interrupted
fn looks_stuck(cpu_percent: f32, status: SysProcessStatus) -> bool {
    cpu_percent > 50.0 || status == SysProcessStatus::UninterruptibleDiskSleep
}

/// CPU use in percent of one core: the CPU time a process used between two
/// reads (`accumulated_cpu_time`, in ms) over the wall time between them.
/// sysinfo's own `cpu_usage` can't be trusted across two reads: on Windows a
/// process's first update stores no baseline, so the next one divides its
/// lifetime CPU by all CPU time since boot and reads ~0% for a full core.
fn cpu_percent_between(used_before_ms: u64, used_after_ms: u64, wall: Duration) -> f32 {
    let wall_ms = wall.as_secs_f64() * 1000.0;
    if wall_ms <= 0.0 {
        return 0.0;
    }
    (used_after_ms.saturating_sub(used_before_ms) as f64 / wall_ms * 100.0) as f32
}

/// The error for finding orphans on Windows (shared by the library call and the command)
#[cfg(not(unix))]
pub(crate) fn orphans_not_supported() -> ProcError {
    ProcError::NotSupported(
        "orphans is not supported on Windows: Windows doesn't re-parent processes, \
         so there is no reliable way to tell an orphan"
            .to_string(),
    )
}

/// Why a command such as `taskkill` failed, in its own words: what it wrote to
/// stderr, else to stdout, else its exit status
/// (compiled on Unix for the tests only)
#[cfg(any(windows, test))]
fn command_failure(stdout: &[u8], stderr: &[u8], status: &str) -> String {
    [stderr, stdout]
        .iter()
        .map(|out| {
            // one line, whatever the tool wrapped its reason over
            String::from_utf8_lossy(out)
                .lines()
                .map(str::trim)
                .filter(|line| !line.is_empty())
                .collect::<Vec<_>>()
                .join(" ")
        })
        .find(|text| !text.is_empty())
        .unwrap_or_else(|| format!("exited with {status}"))
}

/// The result of asking sysinfo to kill process `pid`, which says whether the
/// kill was delivered
fn kill_outcome(delivered: bool, pid: u32) -> Result<()> {
    if delivered {
        Ok(())
    } else {
        Err(ProcError::SignalError(format!(
            "Failed to kill process {}",
            pid
        )))
    }
}

/// What a `taskkill` run (no `/F`) came to: success, or the reason it gave
/// (compiled on Unix for the tests only)
#[cfg(any(windows, test))]
fn taskkill_outcome(output: &std::process::Output) -> Result<()> {
    if output.status.success() {
        Ok(())
    } else {
        Err(ProcError::SignalError(command_failure(
            &output.stdout,
            &output.stderr,
            &output.status.to_string(),
        )))
    }
}

/// The CPU time each process in `sys` has used so far, in ms
fn cpu_used(sys: &System) -> std::collections::HashMap<Pid, u64> {
    sys.processes()
        .iter()
        .map(|(pid, p)| (*pid, p.accumulated_cpu_time()))
        .collect()
}

/// Whether a process has been running for `timeout_secs`. A process's age is in whole
/// seconds, so a process under a second old reads 0 and must still count for
/// `--timeout 0`: "longer than" means this many seconds or more.
fn ran_long_enough(run_time: u64, timeout_secs: u64) -> bool {
    run_time >= timeout_secs
}

/// Whether one reading of a process counts toward "stuck": a process, not a
/// thread, that has run for `timeout_secs` and looks stuck. `find_stuck` filters
/// through this, so a test of it guards the comparison where it is used.
fn counts_as_stuck(is_thread: bool, run_time: u64, timeout_secs: u64, looks_stuck: bool) -> bool {
    !is_thread && ran_long_enough(run_time, timeout_secs) && looks_stuck
}

/// macOS: sysinfo drops zombies, because they have no executable path or arguments
/// left to read, so `proc list --status zombie` could never find one. Read every
/// process from the kernel, as `ps` does, and keep the zombies sysinfo didn't return.
#[cfg(target_os = "macos")]
fn macos_zombies(known: &std::collections::HashSet<u32>) -> Vec<Process> {
    let table = read_proc_table(|buf, size| {
        let mut mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_ALL, 0];
        let null = std::ptr::null_mut();
        // SAFETY: `buf` is null (report the size needed) or points to `*size`
        // writable bytes, which is how read_proc_table calls it
        unsafe { libc::sysctl(mib.as_mut_ptr(), 4, buf, size, null, 0) }
    });
    zombies_in(&table, known)
}

/// libc has no kinfo_proc for macOS, so the few fields we need are read at their
/// offsets in the 64-bit layout (checked against a live process's known values)
#[cfg(target_os = "macos")]
const KINFO_PROC_SIZE: usize = 648;

/// The kernel's table of every process, as raw kinfo_proc records; empty if the
/// kernel refuses. `sysctl` is the call to make (a buffer or null, and the size
/// in and out), so a test can make it fail.
#[cfg(target_os = "macos")]
fn read_proc_table(
    sysctl: impl Fn(*mut libc::c_void, &mut libc::size_t) -> libc::c_int,
) -> Vec<u8> {
    let mut size: libc::size_t = 0;
    // the first call only reports the size needed
    if sysctl(std::ptr::null_mut(), &mut size) != 0 {
        return Vec::new();
    }
    // room for processes started in between
    size += 64 * KINFO_PROC_SIZE;
    let mut buf: Vec<u8> = vec![0; size];
    if sysctl(buf.as_mut_ptr().cast(), &mut size) != 0 {
        return Vec::new();
    }
    buf.truncate(size);
    buf
}

/// The zombies in a table read by `read_proc_table` that `known` doesn't list
#[cfg(target_os = "macos")]
fn zombies_in(buf: &[u8], known: &std::collections::HashSet<u32>) -> Vec<Process> {
    const P_STARTTIME_SEC: usize = 0;
    const P_STAT: usize = 36;
    const P_PID: usize = 40;
    const P_COMM: usize = 243; // MAXCOMLEN + 1 bytes
    const P_RUID: usize = 392;
    const E_PPID: usize = 560;
    const SZOMB: u8 = 5;

    if !buf.len().is_multiple_of(KINFO_PROC_SIZE) {
        return Vec::new(); // a layout we don't know; better to show nothing than garbage
    }

    let read_u32 = |p: &[u8], at: usize| u32::from_ne_bytes(p[at..at + 4].try_into().unwrap());
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    buf.as_chunks::<KINFO_PROC_SIZE>()
        .0
        .iter()
        .filter(|p| p[P_STAT] == SZOMB)
        .filter_map(|p| {
            let pid = read_u32(p, P_PID);
            if pid == 0 || known.contains(&pid) {
                return None;
            }
            let comm = &p[P_COMM..P_COMM + 17];
            let comm = &comm[..comm.iter().position(|&c| c == 0).unwrap_or(comm.len())];
            let name = escape_control(&String::from_utf8_lossy(comm)).into_owned();
            let start =
                u64::from_ne_bytes(p[P_STARTTIME_SEC..P_STARTTIME_SEC + 8].try_into().unwrap());
            Some(Process {
                pid,
                name: if name.is_empty() {
                    "<defunct>".to_string()
                } else {
                    name
                },
                exe_path: None,
                cwd: None,
                command: None,
                argv0: None,
                raw: None,
                cpu_percent: 0.0,
                memory_mb: 0.0,
                status: ProcessStatus::Zombie,
                user: Uid::try_from(read_u32(p, P_RUID) as usize)
                    .ok()
                    .map(|uid| escape_control(&user_name(&uid)).into_owned()),
                parent_pid: Some(read_u32(p, E_PPID)),
                start_time: (start > 0).then_some(start),
                uptime_secs: (start > 0).then(|| now.saturating_sub(start)),
            })
        })
        .collect()
}

/// On Linux, sysinfo lists every thread of a process as an entry of its own,
/// with the process's command line, so a node server shows up a dozen times.
/// Process listings skip them; `thread_kind` is always `None` elsewhere.
pub fn is_thread(proc: &sysinfo::Process) -> bool {
    proc.thread_kind().is_some()
}

/// Linux reports a working directory that was deleted as "/path (deleted)".
/// Strip that marker so the cwd matches `--in` and reads the same as on macOS;
/// a real directory with that name still exists, so it is kept as is.
fn strip_deleted_marker(cwd: String) -> String {
    match cwd.strip_suffix(" (deleted)") {
        Some(path) if !std::path::Path::new(&cwd).exists() => path.to_string(),
        _ => cwd,
    }
}

/// Process status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProcessStatus {
    /// Process is actively executing on CPU
    Running,
    /// Process is waiting for an event or resource
    Sleeping,
    /// Process has been stopped (e.g., by SIGSTOP)
    Stopped,
    /// Process has terminated but not yet been reaped by parent
    Zombie,
    /// Process is being terminated
    Dead,
    /// Process status could not be determined
    Unknown,
}

impl From<SysProcessStatus> for ProcessStatus {
    fn from(status: SysProcessStatus) -> Self {
        match status {
            SysProcessStatus::Run => ProcessStatus::Running,
            SysProcessStatus::Sleep => ProcessStatus::Sleeping,
            SysProcessStatus::Stop => ProcessStatus::Stopped,
            SysProcessStatus::Zombie => ProcessStatus::Zombie,
            SysProcessStatus::Dead => ProcessStatus::Dead,
            _ => ProcessStatus::Unknown,
        }
    }
}

/// Represents a system process with relevant information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Process {
    /// Process ID
    pub pid: u32,
    /// Process name (executable name)
    pub name: String,
    /// Path to the executable
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exe_path: Option<String>,
    /// Current working directory
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    /// Full command line (if available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    /// The first word of the command line, kept whole (a path with spaces in
    /// it stays one piece) and exactly as the OS gave it, for matching names;
    /// never printed, and not part of the JSON
    #[serde(skip)]
    pub argv0: Option<String>,
    /// The name, executable and command line exactly as the OS gave them, when
    /// escaping control characters for display changed any of them. Matching
    /// reads these, so a name matches the same way whether it is looked up in
    /// the process list or against a record; `None` when nothing was escaped
    /// (the fields above are then the raw text). Not part of the JSON.
    #[serde(skip)]
    pub raw: Option<Box<RawText>>,
    /// CPU usage percentage (0.0 - 100.0+)
    pub cpu_percent: f32,
    /// Memory usage in megabytes
    pub memory_mb: f64,
    /// Process status
    pub status: ProcessStatus,
    /// User who owns the process
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    /// Parent process ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_pid: Option<u32>,
    /// Process start time (Unix timestamp)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<u64>,
    /// Seconds the process has been running
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uptime_secs: Option<u64>,
}

/// This process and its ancestors, as far up as ten levels (proc → shell →
/// shell wrapper → IDE → ...). A name lookup skips them all: their command
/// lines hold proc's own arguments (`zsh -c 'proc by node'`).
pub(crate) fn self_and_ancestors(sys: &System) -> std::collections::HashSet<Pid> {
    let self_pid = Pid::from_u32(std::process::id());
    let mut pids = std::collections::HashSet::new();
    pids.insert(self_pid);
    let mut current = self_pid;
    for _ in 0..10 {
        if let Some(parent) = sys.process(current).and_then(|p| p.parent()) {
            pids.insert(parent);
            current = parent;
        } else {
            break;
        }
    }
    pids
}

/// The text of a process that name matching reads, as the OS gave it: control
/// characters unescaped, unlike the fields a process is displayed from
#[derive(Debug, Clone)]
pub struct RawText {
    /// The process name
    pub name: String,
    /// Path of the executable
    pub exe_path: Option<String>,
    /// The full command line
    pub command: Option<String>,
    /// The working directory
    pub cwd: Option<String>,
}

/// How a name relates to a process sysinfo listed, under `mode`. Reads the
/// name, executable and command line straight from sysinfo, so no record is
/// built for the many processes that don't match.
pub(crate) fn classify_sysinfo(pattern: &str, proc: &sysinfo::Process, mode: NameMatch) -> Hit {
    let name = proc.name().to_string_lossy();
    let exe = proc.exe().map(|exe| exe.to_string_lossy());
    let argv0 = proc.cmd().first().map(|arg| arg.to_string_lossy());
    // the joined command line is only needed to search inside it
    let command = (!proc.cmd().is_empty()).then(|| {
        proc.cmd()
            .iter()
            .map(|arg| arg.to_string_lossy())
            .collect::<Vec<_>>()
            .join(" ")
    });
    classify(
        pattern,
        &Names {
            name: &name,
            exe: exe.as_deref(),
            argv0: argv0.as_deref(),
            command: command.as_deref(),
        },
        mode,
    )
}

impl Process {
    /// The names a name target is compared with
    pub fn names(&self) -> Names<'_> {
        match &self.raw {
            Some(raw) => Names {
                name: &raw.name,
                exe: raw.exe_path.as_deref(),
                argv0: self.argv0.as_deref(),
                command: raw.command.as_deref(),
            },
            None => Names {
                name: &self.name,
                exe: self.exe_path.as_deref(),
                argv0: self.argv0.as_deref(),
                command: self.command.as_deref(),
            },
        }
    }

    /// The working directory exactly as the OS gave it, for matching `--in`.
    /// `cwd` is what is shown, with control characters escaped, so a directory
    /// named `a<newline>b` and one named `a\nb` (backslash, `n`) both read
    /// `a\nb` there; this one tells them apart.
    pub fn raw_cwd(&self) -> Option<&str> {
        match &self.raw {
            Some(raw) => raw.cwd.as_deref(),
            None => self.cwd.as_deref(),
        }
    }

    /// Find all processes a name matches (see [`NameMatch`]): by default the
    /// whole name, with `--cmd` any part of the name or command line.
    ///
    /// Proc itself and its ancestor shells never match. When nothing matches by
    /// name but processes have the text in their command line, the error says
    /// so: it costs nothing, the same pass over the processes counts them.
    pub fn find_by_name(pattern: &str, mode: NameMatch) -> Result<Vec<Process>> {
        let mut sys = System::new_all();
        sys.refresh_all();

        // Exclude the entire ancestor chain — their command lines contain proc's
        // arguments (e.g. "zsh -c proc by node"), causing false positives
        let ancestor_pids = self_and_ancestors(&sys);
        let mut in_command_line_only = 0;
        let mut processes: Vec<Process> = sys
            .processes()
            .iter()
            .filter_map(|(pid, proc)| {
                // Exclude self, ancestor shells, and Linux threads
                if ancestor_pids.contains(pid) || is_thread(proc) {
                    return None;
                }
                match classify_sysinfo(pattern, proc, mode) {
                    Hit::Match => Some(Process::from_sysinfo(*pid, proc)),
                    Hit::CommandLineOnly => {
                        in_command_line_only += 1;
                        None
                    }
                    Hit::No => None,
                }
            })
            .collect();
        // sysinfo keeps its processes in a randomly ordered map: PID ascending
        // makes every list that starts here the same on every run
        processes.sort_by_key(|p| p.pid);

        if processes.is_empty() {
            return Err(ProcError::name_not_found(pattern, in_command_line_only));
        }

        Ok(processes)
    }

    /// Find a specific process by PID
    pub fn find_by_pid(pid: u32) -> Result<Option<Process>> {
        let mut sys = System::new_all();
        sys.refresh_all();

        let sysinfo_pid = Pid::from_u32(pid);

        Ok(sys
            .processes()
            .get(&sysinfo_pid)
            .map(|proc| Process::from_sysinfo(sysinfo_pid, proc)))
    }

    /// Get all running processes (excludes proc's own process)
    pub fn find_all() -> Result<Vec<Process>> {
        let mut sys = System::new_all();
        sys.refresh_all();

        let self_pid = sysinfo::Pid::from_u32(std::process::id());
        #[allow(unused_mut)]
        let mut processes: Vec<Process> = sys
            .processes()
            .iter()
            .filter(|(pid, proc)| **pid != self_pid && !is_thread(proc))
            .map(|(pid, proc)| Process::from_sysinfo(*pid, proc))
            .collect();

        #[cfg(target_os = "macos")]
        {
            let known: std::collections::HashSet<u32> = processes.iter().map(|p| p.pid).collect();
            processes.extend(macos_zombies(&known));
        }

        // sysinfo keeps its processes in a randomly ordered map (and the
        // zombies are appended after them): PID ascending makes every list
        // that starts here the same on every run
        processes.sort_by_key(|p| p.pid);

        Ok(processes)
    }

    /// Find processes running a specific executable path
    pub fn find_by_exe_path(path: &std::path::Path) -> Result<Vec<Process>> {
        let all = Self::find_all()?;
        let path_str = path.to_string_lossy();

        Ok(all
            .into_iter()
            .filter(|p| {
                if let Some(ref exe) = p.exe_path {
                    // Exact match (compare as strings to avoid PathBuf allocation)
                    exe == &*path_str || std::path::Path::new(exe) == path
                } else {
                    false
                }
            })
            .collect())
    }

    /// Find processes that have a file open (Unix only via lsof)
    #[cfg(unix)]
    pub fn find_by_open_file(path: &std::path::Path) -> Result<Vec<Process>> {
        Self::find_by_open_file_with("lsof", path)
    }

    /// `find_by_open_file` with the lsof program to run, so a test can have it missing
    #[cfg(unix)]
    fn find_by_open_file_with(lsof: &str, path: &std::path::Path) -> Result<Vec<Process>> {
        use std::process::Command;

        let output = crate::ui::interrupt::unblocked_in_child(&mut Command::new(lsof))
            .args(["-t", &path.to_string_lossy()]) // -t = terse (PIDs only)
            .output();

        let output = match output {
            Ok(o) => o,
            Err(_) => return Ok(vec![]), // lsof not available
        };

        if !output.status.success() {
            return Ok(vec![]); // No processes have file open
        }

        let pids: Vec<u32> = String::from_utf8_lossy(&output.stdout)
            .lines()
            .filter_map(|line| line.trim().parse().ok())
            .collect();

        let mut processes = Vec::new();
        for pid in pids {
            if let Ok(Some(proc)) = Self::find_by_pid(pid) {
                processes.push(proc);
            }
        }

        Ok(processes)
    }

    /// Find processes that have a file open (Windows stub)
    #[cfg(not(unix))]
    pub fn find_by_open_file(_path: &std::path::Path) -> Result<Vec<Process>> {
        // Windows: Could use handle.exe from Sysinternals, but skip for now
        Ok(vec![])
    }

    /// Find processes that look stuck: running longer than `timeout`, and in each
    /// of two readings a second apart either using over half a core or blocked in
    /// uninterruptible sleep. One reading
    /// used to be enough, so a momentary spike counted. A long build at full CPU
    /// still looks the same as a loop that never ends; only the user can tell.
    pub fn find_stuck(timeout: Duration) -> Result<Vec<Process>> {
        let timeout_secs = timeout.as_secs();
        // each read is timed from its start, as in `measure_cpu`
        let mut read_at = std::time::Instant::now();
        let mut sys = System::new_all();
        let mut used = cpu_used(&sys);
        let mut cpu: std::collections::HashMap<Pid, f32> = std::collections::HashMap::new();
        let mut stuck: Option<std::collections::HashSet<Pid>> = None;

        for _ in 0..STUCK_READINGS {
            std::thread::sleep(STUCK_READING_GAP);
            let started = std::time::Instant::now();
            sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
            let wall = started - read_at;
            read_at = started;
            // a process first seen in this read has no CPU figure yet
            cpu = sys
                .processes()
                .iter()
                .filter_map(|(pid, p)| {
                    let before = used.get(pid)?;
                    Some((
                        *pid,
                        cpu_percent_between(*before, p.accumulated_cpu_time(), wall),
                    ))
                })
                .collect();
            used = cpu_used(&sys);
            let now: std::collections::HashSet<Pid> = sys
                .processes()
                .iter()
                .filter(|(pid, p)| {
                    let busy = cpu.get(pid).copied().unwrap_or(0.0);
                    counts_as_stuck(
                        is_thread(p),
                        p.run_time(),
                        timeout_secs,
                        looks_stuck(busy, p.status()),
                    )
                })
                .map(|(pid, _)| *pid)
                .collect();
            stuck = Some(match stuck {
                None => now,
                Some(before) => before.intersection(&now).copied().collect(),
            });
        }

        let stuck = stuck.unwrap_or_default();
        let mut found: Vec<Process> = sys
            .processes()
            .iter()
            .filter(|(pid, _)| stuck.contains(pid))
            .map(|(pid, p)| {
                let mut process = Process::from_sysinfo(*pid, p);
                // the figure the last read measured, not sysinfo's own
                if let Some(&busy) = cpu.get(pid) {
                    process.cpu_percent = busy;
                }
                process
            })
            .collect();
        // sysinfo keeps its processes in a randomly ordered map: PID ascending
        found.sort_by_key(|p| p.pid);
        Ok(found)
    }

    /// Whether this process looks stuck now, measured the way `find_stuck` does
    /// (stuck in two readings a second apart), for a process named as a target.
    pub fn looks_stuck_now(&self) -> bool {
        let pid = Pid::from_u32(self.pid);
        let mut sys = System::new();
        let mut read_at = std::time::Instant::now();
        sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
        let mut used = sys
            .process(pid)
            .filter(|p| self.is_same(p))
            .map(|p| p.accumulated_cpu_time());
        (0..STUCK_READINGS).all(|_| {
            std::thread::sleep(STUCK_READING_GAP);
            let started = std::time::Instant::now();
            sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
            let wall = started - read_at;
            read_at = started;
            let (Some(before), Some(p)) = (used, sys.process(pid).filter(|p| self.is_same(p)))
            else {
                return false;
            };
            let after = p.accumulated_cpu_time();
            used = Some(after);
            looks_stuck(cpu_percent_between(before, after, wall), p.status())
        })
    }

    /// CPU use over `window` (at least sysinfo's minimum), in percent of one core;
    /// None if the process is gone. A reading over a few milliseconds is ~0 for
    /// any process, so a real window is needed.
    ///
    /// Unix only (the method does not exist on Windows): its one caller is the gentle recovery `unstick` tries there;
    /// on Windows `unstick` only terminates.
    #[cfg(unix)]
    pub fn cpu_over(&self, window: Duration) -> Option<f32> {
        let pid = Pid::from_u32(self.pid);
        let mut sys = System::new();
        let started = std::time::Instant::now();
        sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
        let before = sys
            .process(pid)
            .filter(|p| self.is_same(p))
            .map(|p| p.accumulated_cpu_time())?;
        std::thread::sleep(window.max(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL));
        let wall = started.elapsed();
        sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
        sys.process(pid)
            .filter(|p| self.is_same(p))
            .map(|p| cpu_percent_between(before, p.accumulated_cpu_time(), wall))
    }

    /// Measure the CPU use of these processes over 0.2 s and set `cpu_percent`,
    /// in percent of one core. A lookup reads CPU a few milliseconds after its
    /// first refresh, which is ~0% even for a process using a whole core, so
    /// commands call this before they show, filter or sort by CPU. One 0.2 s wait
    /// covers the whole batch; commands that never show CPU skip it.
    ///
    /// CPU is the CPU time each process used between two reads, over the wall
    /// time we measure between them. sysinfo's own `cpu_usage` divides by its
    /// system-wide tick interval instead, which read about 2% for a process
    /// spinning at 100% in some runs.
    pub fn measure_cpu(processes: &mut [Process]) {
        if processes.is_empty() {
            return;
        }
        let pids: Vec<Pid> = processes.iter().map(|p| Pid::from_u32(p.pid)).collect();
        let which = sysinfo::ProcessesToUpdate::Some(&pids);
        let cpu_only = sysinfo::ProcessRefreshKind::nothing().with_cpu();
        let mut sys = System::new();

        let first = std::time::Instant::now();
        sys.refresh_processes_specifics(which, true, cpu_only);
        let before = cpu_used(&sys);
        std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
        // each refresh reads the processes in the same order, so timing both
        // from their start gives every process the same window
        let wall = first.elapsed();
        sys.refresh_processes_specifics(which, true, cpu_only);

        for process in processes.iter_mut() {
            let pid = Pid::from_u32(process.pid);
            let (Some(current), Some(&cpu_before)) = (sys.process(pid), before.get(&pid)) else {
                continue;
            };
            if process.is_same(current) {
                process.cpu_percent =
                    cpu_percent_between(cpu_before, current.accumulated_cpu_time(), wall);
            }
        }
    }

    /// Force kill the process (SIGKILL on Unix, taskkill /F on Windows)
    pub fn kill(&self) -> Result<()> {
        let mut sys = System::new();
        sys.refresh_processes(
            sysinfo::ProcessesToUpdate::Some(&[Pid::from_u32(self.pid)]),
            true,
        );

        match sys.process(Pid::from_u32(self.pid)) {
            Some(proc) if self.is_same(proc) => kill_outcome(proc.kill(), self.pid),
            // gone, or the PID now belongs to a new process
            _ => Err(ProcError::ProcessNotFound(self.pid.to_string())),
        }
    }

    /// Whether `current`, the process now holding this PID, is the one this record
    /// describes. A different start time means the PID was reused by a new process.
    fn is_same(&self, current: &sysinfo::Process) -> bool {
        match self.start_time {
            Some(ours) if current.start_time() > 0 => current.start_time().abs_diff(ours) <= 1,
            _ => true,
        }
    }

    /// Checked right before each signal, so a delayed one (stop's SIGKILL comes up
    /// to --timeout seconds after the target was resolved) can't reach a new
    /// process that reused the PID.
    fn ensure_same_process(&self) -> Result<()> {
        let mut sys = System::new();
        let pid = Pid::from_u32(self.pid);
        sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
        match sys.process(pid) {
            Some(current) if self.is_same(current) => Ok(()),
            _ => Err(ProcError::ProcessNotFound(self.pid.to_string())),
        }
    }

    /// Force kill and wait up to 5 seconds for the process to be gone.
    ///
    /// Never blocks forever (sysinfo's own kill_and_wait polls with no limit and
    /// never ends for a zombie). A process still alive after 5 seconds, such as
    /// one stuck in the kernel, is an error.
    pub fn kill_and_wait(&self) -> Result<()> {
        self.kill_and_wait_within(Duration::from_secs(5))
    }

    /// `kill_and_wait` with the time to wait for the process to be gone
    fn kill_and_wait_within(&self, wait: Duration) -> Result<()> {
        self.kill_then_wait(wait, Process::kill)
    }

    /// `kill_and_wait_within` with the kill to send, so a test can send one that
    /// leaves the process running (a real kill is over before it returns on
    /// Windows, though the process can stay listed for a moment after)
    fn kill_then_wait(&self, wait: Duration, kill: impl Fn(&Process) -> Result<()>) -> Result<()> {
        match kill(self) {
            // it exited on its own just before the kill
            Err(ProcError::ProcessNotFound(_)) => return Ok(()),
            other => other?,
        }
        let deadline = std::time::Instant::now() + wait;
        while std::time::Instant::now() < deadline {
            if !self.is_running() {
                return Ok(());
            }
            std::thread::sleep(Duration::from_millis(50));
        }
        Err(ProcError::SignalError(format!(
            "Process {} is still running {} seconds after SIGKILL",
            self.pid,
            wait.as_secs()
        )))
    }

    /// Send SIGTERM for graceful termination (Unix) or taskkill (Windows)
    #[cfg(unix)]
    pub fn terminate(&self) -> Result<()> {
        use nix::sys::signal::{kill, Signal};
        use nix::unistd::Pid as NixPid;

        self.ensure_same_process()?;
        kill(NixPid::from_raw(self.pid as i32), Signal::SIGTERM)
            .map_err(|e| ProcError::SignalError(e.to_string()))
    }

    /// Graceful termination (Windows): `taskkill` without `/F` asks the
    /// process to close its windows, so it fails for a console program, which
    /// has none. That failure is returned, with taskkill's reason, rather than
    /// reported as success.
    #[cfg(windows)]
    pub fn terminate(&self) -> Result<()> {
        use std::process::Command;

        self.ensure_same_process()?;
        let output = Command::new("taskkill")
            .args(["/PID", &self.pid.to_string()])
            .output()
            .map_err(|e| ProcError::SystemError(e.to_string()))?;

        taskkill_outcome(&output)
    }

    /// Send an arbitrary signal to the process (Unix only)
    #[cfg(unix)]
    pub fn send_signal(&self, signal: nix::sys::signal::Signal) -> Result<()> {
        use nix::sys::signal::kill;
        use nix::unistd::Pid as NixPid;
        self.ensure_same_process()?;
        kill(NixPid::from_raw(self.pid as i32), signal)
            .map_err(|e| ProcError::SignalError(format!("{}: {}", signal, e)))
    }

    // Note: On Windows, send_signal is not available. Commands that use it
    // (freeze, thaw) have their own #[cfg(not(unix))] stubs that return NotSupported.

    /// Find orphaned processes (parent is PID 1 / init / launchd, excluding system daemons)
    ///
    /// Unix only: on Windows this returns `ProcError::NotSupported`, because
    /// Windows has no PID 1 and does not re-parent a process whose parent exited,
    /// so an empty list would claim "no orphans" where nothing could be checked.
    #[cfg(unix)]
    pub fn find_orphans() -> Result<Vec<Process>> {
        Ok(Self::orphans_among(Self::find_all()?))
    }

    /// Windows: orphans cannot be told, so this is an error, not an empty list
    #[cfg(not(unix))]
    pub fn find_orphans() -> Result<Vec<Process>> {
        Err(orphans_not_supported())
    }

    /// The orphans among `all`
    #[cfg(unix)]
    fn orphans_among(all: Vec<Process>) -> Vec<Process> {
        all.into_iter()
            .filter(|p| {
                if let Some(ppid) = p.parent_pid {
                    ppid == 1 && p.pid != 1 && !Self::is_system_process(p)
                } else {
                    false
                }
            })
            .collect()
    }

    /// Check if a process is a system daemon (naturally has PPID 1)
    ///
    /// Filters out processes that legitimately have PPID 1 — system daemons,
    /// kernel threads, and services managed by init/systemd/launchd.
    /// Heuristic: no cwd or cwd is "/" with exe in system paths.
    #[cfg(unix)]
    fn is_system_process(p: &Process) -> bool {
        if p.cwd.is_none() || p.cwd.as_deref() == Some("/") {
            if let Some(ref exe) = p.exe_path {
                // macOS system paths
                if exe.starts_with("/System/") || exe.starts_with("/usr/libexec/") {
                    return true;
                }
                // Shared Unix system paths (macOS + Linux)
                if exe.starts_with("/usr/sbin/")
                    || exe.starts_with("/sbin/")
                    || exe.starts_with("/usr/bin/")
                    || exe.starts_with("/usr/lib/")
                    || exe.starts_with("/usr/lib64/")
                    || exe.starts_with("/lib/")
                    || exe.starts_with("/lib64/")
                    || exe.starts_with("/opt/")
                    || exe.starts_with("/snap/")
                {
                    return true;
                }
            }
            return true; // No exe path = likely kernel thread
        }
        false
    }

    /// Check if the process is still alive. A zombie (exited, not yet reaped by
    /// its parent) has exited, and a process with a different start time is a new
    /// one that reused the PID, so neither counts.
    pub fn exists(&self) -> bool {
        let mut sys = System::new();
        let pid = Pid::from_u32(self.pid);
        sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
        match sys.process(pid) {
            None => false,
            Some(current) if current.status() == SysProcessStatus::Zombie => false,
            Some(current) => self.is_same(current),
        }
    }

    /// Check if the process is still running (alias for exists for compatibility)
    pub fn is_running(&self) -> bool {
        self.exists()
    }

    /// Convert from sysinfo Process
    pub(crate) fn from_sysinfo(pid: Pid, proc: &sysinfo::Process) -> Self {
        let cmd_vec = proc.cmd();
        // Every text field is set by whoever runs the process: escape control
        // characters before anything prints them. Name matching reads the raw
        // text (`raw`, kept only when escaping changed something).
        let raw_command = (!cmd_vec.is_empty()).then(|| {
            cmd_vec
                .iter()
                .map(|s| s.to_string_lossy())
                .collect::<Vec<_>>()
                .join(" ")
        });
        let raw_name = proc.name().to_string_lossy();
        let raw_exe = proc.exe().map(|p| p.to_string_lossy());
        let raw_cwd = proc
            .cwd()
            .map(|p| strip_deleted_marker(p.to_string_lossy().to_string()));
        let changed = |text: &str| matches!(escape_control(text), std::borrow::Cow::Owned(_));
        let raw = (changed(&raw_name)
            || raw_exe.as_deref().is_some_and(changed)
            || raw_command.as_deref().is_some_and(changed)
            || raw_cwd.as_deref().is_some_and(changed))
        .then(|| {
            Box::new(RawText {
                name: raw_name.to_string(),
                exe_path: raw_exe.as_ref().map(|exe| exe.to_string()),
                command: raw_command.clone(),
                cwd: raw_cwd.clone(),
            })
        });
        let command = raw_command
            .as_deref()
            .map(|joined| escape_control(joined).into_owned());

        let exe_path = raw_exe
            .as_deref()
            .map(|exe| escape_control(exe).into_owned());
        let cwd = raw_cwd
            .as_deref()
            .map(|path| escape_control(path).into_owned());

        Process {
            pid: pid.as_u32(),
            name: escape_control(&raw_name).into_owned(),
            exe_path,
            cwd,
            command,
            argv0: cmd_vec
                .first()
                .map(|arg| arg.to_string_lossy().into_owned()),
            raw,
            cpu_percent: proc.cpu_usage(),
            memory_mb: proc.memory() as f64 / 1024.0 / 1024.0,
            status: ProcessStatus::from(proc.status()),
            user: proc
                .user_id()
                .map(|uid| escape_control(&user_name(uid)).into_owned()),
            parent_pid: proc.parent().map(|p| p.as_u32()),
            // sysinfo reports 0 when it can't read the start time (on macOS, any
            // other user's process), which would make the uptime about 56 years
            start_time: (proc.start_time() > 0).then(|| proc.start_time()),
            uptime_secs: (proc.start_time() > 0).then(|| proc.run_time()),
        }
    }
}

/// Parse a signal name to a nix Signal (Unix only)
///
/// Accepts: "HUP", "SIGHUP", "hup" (signal names only, not numbers —
/// numeric signal values differ between macOS and Linux)
#[cfg(unix)]
pub fn parse_signal_name(name: &str) -> Result<nix::sys::signal::Signal> {
    use nix::sys::signal::Signal;

    let upper = name.to_uppercase();
    let upper = upper.trim_start_matches("SIG");
    match upper {
        "HUP" => Ok(Signal::SIGHUP),
        "INT" => Ok(Signal::SIGINT),
        "QUIT" => Ok(Signal::SIGQUIT),
        "ABRT" => Ok(Signal::SIGABRT),
        "KILL" => Ok(Signal::SIGKILL),
        "TERM" => Ok(Signal::SIGTERM),
        "STOP" => Ok(Signal::SIGSTOP),
        "CONT" => Ok(Signal::SIGCONT),
        "USR1" => Ok(Signal::SIGUSR1),
        "USR2" => Ok(Signal::SIGUSR2),
        _ => Err(ProcError::InvalidInput(format!(
            "Unknown signal: '{}'. Valid signals: HUP, INT, QUIT, ABRT, KILL, TERM, STOP, CONT, USR1, USR2",
            name
        ))),
    }
}

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

    #[test]
    fn cpu_is_the_cpu_time_used_over_the_wall_time() {
        let second = Duration::from_secs(1);
        // a full core for a second, half a core, and nothing
        assert_eq!(cpu_percent_between(5_000, 6_000, second), 100.0);
        assert_eq!(cpu_percent_between(5_000, 5_500, second), 50.0);
        assert_eq!(cpu_percent_between(5_000, 5_000, second), 0.0);
        // two cores' worth reads 200%, in percent of one core
        assert_eq!(cpu_percent_between(0, 2_000, second), 200.0);
        // a counter that went backwards (a reused PID) or no time passing is 0
        assert_eq!(cpu_percent_between(6_000, 5_000, second), 0.0);
        assert_eq!(cpu_percent_between(0, 1_000, Duration::ZERO), 0.0);
    }

    #[test]
    fn a_failed_command_is_explained_in_its_own_words() {
        let reason = "ERROR: The process with PID 7 could not be terminated.";
        assert_eq!(
            command_failure(b"", reason.as_bytes(), "exit code: 1"),
            reason
        );
        // stdout when stderr is empty, trimmed
        assert_eq!(
            command_failure(b"  not here\r\n", b"", "exit code: 1"),
            "not here"
        );
        // taskkill wraps its reason over several lines; the error keeps them on one
        assert_eq!(
            command_failure(
                b"",
                b"ERROR: first part\r\n  second part.\r\n\r\n",
                "exit code: 1"
            ),
            "ERROR: first part second part."
        );
        assert_eq!(
            command_failure(b"", b"  \n", "exit code: 128"),
            "exited with exit code: 128"
        );
    }

    #[test]
    fn busy_means_over_half_a_core_or_blocked_in_the_kernel() {
        assert!(looks_stuck(50.1, SysProcessStatus::Run));
        assert!(!looks_stuck(50.0, SysProcessStatus::Run));
        assert!(!looks_stuck(0.0, SysProcessStatus::Sleep));
        assert!(looks_stuck(0.0, SysProcessStatus::UninterruptibleDiskSleep));
    }

    #[test]
    fn a_reading_counts_as_stuck_from_the_timeout_on() {
        assert!(counts_as_stuck(false, 0, 0, true));
        assert!(!counts_as_stuck(false, 59, 60, true));
        assert!(counts_as_stuck(false, 60, 60, true));
        assert!(counts_as_stuck(false, 61, 60, true));
        // and only a busy process, never a thread
        assert!(!counts_as_stuck(false, 60, 60, false));
        assert!(!counts_as_stuck(true, 60, 60, true));
    }

    #[test]
    fn a_process_that_ran_the_timeout_has_run_long_enough() {
        // --timeout 0 finds a process that reads 0 seconds old
        assert!(ran_long_enough(0, 0));
        assert!(ran_long_enough(5, 5));
        assert!(ran_long_enough(6, 5));
        assert!(!ran_long_enough(4, 5));
    }

    #[test]
    fn test_find_all_processes() {
        let processes = Process::find_all().unwrap();
        assert!(!processes.is_empty(), "Should find at least one process");
    }

    #[test]
    fn every_process_source_lists_pid_ascending() {
        use crate::test_support::{end, idle_child, record_of};

        let mut children: Vec<_> = (0..3).map(|_| idle_child()).collect();
        let mine: Vec<u32> = children.iter().map(|c| record_of(c).pid).collect();
        let name = record_of(&children[0]).name;

        let ascending = |what: &str, list: &[Process]| {
            let pids: Vec<u32> = list.iter().map(|p| p.pid).collect();
            let mut sorted = pids.clone();
            sorted.sort_unstable();
            sorted.dedup();
            assert_eq!(pids, sorted, "{what} is not PID ascending");
            pids
        };
        let all = ascending("find_all", &Process::find_all().unwrap());
        let named = ascending(
            "find_by_name",
            &Process::find_by_name(&name, NameMatch::Exact).unwrap(),
        );
        ascending("find_stuck", &Process::find_stuck(Duration::ZERO).unwrap());
        for pid in &mine {
            assert!(all.contains(pid), "find_all has {pid}");
            assert!(named.contains(pid), "find_by_name has {pid}");
        }
        children.iter_mut().for_each(end);
    }

    #[test]
    fn test_find_by_pid_self() {
        let pid = std::process::id();
        let process = Process::find_by_pid(pid).unwrap();
        assert!(process.is_some(), "Should find own process");
    }

    #[test]
    fn test_is_running_tells_a_reused_pid_apart() {
        let mut me = Process::find_by_pid(std::process::id()).unwrap().unwrap();
        assert!(me.is_running());
        // Same PID, different start time: a new process that reused the PID
        let start = me.start_time.expect("a running process has a start time");
        me.start_time = Some(start - 3600);
        assert!(!me.is_running(), "a reused PID counted as the same process");
    }

    #[test]
    fn test_escape_control_makes_terminal_input_harmless() {
        // Ordinary text, including non-ASCII, is untouched
        assert_eq!(escape_control("node server.js"), "node server.js");
        assert_eq!(escape_control("café ✓ 日本"), "café ✓ 日本");
        // ESC sequences: colours, window title (OSC), clipboard (OSC 52)
        assert_eq!(escape_control("a\x1b[31mb"), "a\\x1b[31mb");
        assert_eq!(escape_control("\x1b]0;pwned\x07"), "\\x1b]0;pwned\\x07");
        // Line breaks and tabs would split or shift a table row
        assert_eq!(escape_control("one\ntwo\tthree\r"), "one\\ntwo\\tthree\\r");
        // DEL, and C1 controls such as the 8-bit CSI (U+009B)
        assert_eq!(escape_control("x\x7fy\u{9b}2J"), "x\\x7fy\\x9b2J");
        // Bidirectional overrides can reorder text on screen ("Trojan Source")
        assert_eq!(escape_control("ab\u{202e}cd"), "ab\\u{202e}cd");
    }

    #[cfg(unix)]
    #[test]
    fn test_looks_stuck_needs_sustained_cpu() {
        let spawn = |script: &str| {
            std::process::Command::new("sh")
                .args(["-c", script])
                .spawn()
                .unwrap()
        };
        let mut spinning = spawn("while :; do :; done");
        let mut idle = spawn("exec sleep 300");
        std::thread::sleep(Duration::from_millis(300));
        let record = |pid: u32| Process::find_by_pid(pid).unwrap().unwrap();

        let spinning_stuck = record(spinning.id()).looks_stuck_now();
        let idle_stuck = record(idle.id()).looks_stuck_now();
        for child in [&mut spinning, &mut idle] {
            let _ = child.kill();
            let _ = child.wait();
        }
        assert!(
            spinning_stuck,
            "a process spinning at 100% CPU wasn't stuck"
        );
        assert!(!idle_stuck, "an idle process counted as stuck");
    }

    #[test]
    fn test_signals_never_reach_a_process_that_reused_the_pid() {
        let mut child = crate::test_support::idle_child();
        let mut stale = crate::test_support::record_of(&child);
        // A record from before the PID was reused: same PID, older start time
        stale.start_time = stale.start_time.map(|t| t - 3600);

        let kill = stale.kill();
        let term = stale.terminate();
        #[cfg(unix)]
        let sig = stale.send_signal(nix::sys::signal::Signal::SIGKILL);
        let alive = child.try_wait().unwrap().is_none();
        let _ = child.kill();
        let _ = child.wait();

        assert!(
            alive,
            "a stale record signalled the process now using its PID"
        );
        assert!(
            matches!(kill, Err(ProcError::ProcessNotFound(_))),
            "{kill:?}"
        );
        assert!(
            matches!(term, Err(ProcError::ProcessNotFound(_))),
            "{term:?}"
        );
        #[cfg(unix)]
        assert!(matches!(sig, Err(ProcError::ProcessNotFound(_))), "{sig:?}");
    }

    /// A control character in a process's name, executable or command line is
    /// shown escaped, but name matching reads what the OS gave: a process found
    /// by `find_by_name` is also kept by `--by`, and the other way round
    #[cfg(unix)]
    #[test]
    fn text_with_control_characters_matches_as_typed_and_displays_escaped() {
        use crate::core::matches_by_filter;
        use std::os::unix::process::CommandExt;

        let word = format!("zz\u{7}ctl{}x", std::process::id());
        let mut child = std::process::Command::new("sleep")
            .arg0(&word)
            .arg("300")
            .spawn()
            .unwrap();
        let pid = child.id();
        // `spawn` returns once the exec has begun, not once it has finished:
        // measured on Linux, /proc/<pid>/cmdline is still empty for a moment
        // after it (name and exe are already the new program's). A record taken
        // in that moment has no first argument, so wait for the command line.
        let record = std::iter::repeat_with(|| {
            std::thread::sleep(Duration::from_millis(5));
            Process::find_by_pid(pid).unwrap().unwrap()
        })
        .take(1000)
        .find(|record| record.argv0.is_some());
        let part = format!("\u{7}ctl{}", std::process::id());

        let found = |pattern: &str, mode| {
            Process::find_by_name(pattern, mode)
                .map(|found| found.iter().any(|p| p.pid == pid))
                .unwrap_or(false)
        };
        let named = found(&word, NameMatch::Exact);
        let named_in_command = found(&part, NameMatch::Command);
        let _ = child.kill();
        let _ = child.wait();

        let record = record.expect("the child's command line never appeared");
        assert!(named, "find_by_name read the escaped first argument");
        assert!(
            named_in_command,
            "find_by_name read the escaped command line"
        );
        assert!(
            matches_by_filter(&record, &word, NameMatch::Exact),
            "--by read the escaped first argument"
        );
        assert!(
            matches_by_filter(&record, &part, NameMatch::Command),
            "--by --cmd read the escaped command line"
        );
        // what is shown is escaped
        let shown = record.command.as_deref().unwrap();
        assert!(shown.contains("\\x07ctl"), "{shown}");
        assert!(!shown.contains('\u{7}'), "{shown:?}");
    }

    /// The same, on Windows, where a process has no `arg0` to set: a control
    /// character in the command line (the listener example ignores extra
    /// arguments) is shown escaped and still matches as typed with `--cmd`
    #[cfg(windows)]
    #[test]
    fn a_control_character_in_a_windows_command_line_matches_as_typed_and_displays_escaped() {
        use crate::core::matches_by_filter;

        let mut exe = std::env::current_exe().unwrap();
        exe.pop();
        exe.pop();
        exe.push("examples");
        exe.push("listener.exe");
        assert!(exe.exists(), "build the example first: {}", exe.display());
        let part = format!("\u{7}ctl{}", std::process::id());
        let mut child = std::process::Command::new(&exe)
            .arg(&part)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap();
        let pid = child.id();
        let record = std::iter::repeat_with(|| {
            std::thread::sleep(Duration::from_millis(20));
            Process::find_by_pid(pid).unwrap()
        })
        .take(500)
        .flatten()
        .find(|record| record.command.is_some())
        .expect("the child's command line never appeared");
        let found = Process::find_by_name(&part, NameMatch::Command)
            .map(|found| found.iter().any(|p| p.pid == pid))
            .unwrap_or(false);
        let kept = matches_by_filter(&record, &part, NameMatch::Command);
        crate::test_support::end(&mut child);

        assert!(found, "find_by_name read the escaped command line");
        assert!(kept, "--by --cmd read the escaped command line");
        let shown = record.command.as_deref().unwrap();
        assert!(shown.contains("\\x07ctl"), "{shown}");
        assert!(!shown.contains('\u{7}'), "{shown:?}");
    }

    #[test]
    fn a_name_is_read_from_the_raw_text_when_escaping_changed_it() {
        let record = Process {
            name: "a\\x07b".to_string(),
            raw: Some(Box::new(RawText {
                name: "a\u{7}b".to_string(),
                exe_path: Some("c\u{7}d".to_string()),
                command: Some("e\u{7}f".to_string()),
                cwd: None,
            })),
            argv0: Some("g".to_string()),
            ..ghost()
        };
        let names = record.names();
        assert_eq!(names.name, "a\u{7}b");
        assert_eq!(names.exe, Some("c\u{7}d"));
        assert_eq!(names.argv0, Some("g"));
        assert_eq!(names.command, Some("e\u{7}f"));
    }

    #[test]
    fn the_ancestors_stop_where_the_process_list_does() {
        // A list that holds only this process: its parent is named but not
        // listed, so the climb ends there instead of going on
        let me = Pid::from_u32(std::process::id());
        let mut sys = System::new();
        sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[me]), true);
        let parent = sys.process(me).and_then(|p| p.parent());
        let expected: std::collections::HashSet<Pid> = std::iter::once(me).chain(parent).collect();
        assert_eq!(self_and_ancestors(&sys), expected);
    }

    #[test]
    fn test_strip_deleted_marker() {
        assert_eq!(
            strip_deleted_marker("/nonexistent/proc-gone (deleted)".to_string()),
            "/nonexistent/proc-gone"
        );
        assert_eq!(
            strip_deleted_marker("/tmp/project".to_string()),
            "/tmp/project"
        );

        // A directory really named "x (deleted)" keeps its name
        let real = std::env::temp_dir().join(format!("proc-real-{} (deleted)", std::process::id()));
        std::fs::create_dir_all(&real).unwrap();
        let path = real.to_string_lossy().to_string();
        assert_eq!(strip_deleted_marker(path.clone()), path);
        std::fs::remove_dir(&real).unwrap();
    }

    #[test]
    fn a_name_nothing_has_is_plain_not_found_in_both_modes() {
        for mode in [NameMatch::Exact, NameMatch::Command] {
            let result = Process::find_by_name("nonexistent_process_12345", mode);
            assert!(
                matches!(&result, Err(ProcError::ProcessNotFound(n)) if n == "nonexistent_process_12345"),
                "{result:?}"
            );
        }
    }

    /// A shell waiting for input that never comes, with a marker in its command
    /// line: it is named `sh`, and the marker is only in `sh -c ...`. It runs
    /// nothing else, so there is no child to leave behind.
    #[cfg(unix)]
    fn waiting_shell_with(marker: &str) -> std::process::Child {
        std::process::Command::new("sh")
            .args(["-c", &format!("read line; : {marker}")])
            .stdin(std::process::Stdio::piped())
            .spawn()
            .unwrap()
    }

    #[cfg(unix)]
    #[test]
    fn a_word_only_in_a_command_line_is_found_with_cmd_and_hinted_without() {
        let marker = format!("hintmarker{}", std::process::id());
        let mut child = waiting_shell_with(&marker);
        let pid = child.id();
        let exact = Process::find_by_name(&marker, NameMatch::Exact);
        let cmd = Process::find_by_name(&marker, NameMatch::Command);
        let _ = child.kill();
        let _ = child.wait();

        // by default no process is named that, and the error says one has it
        // in its command line
        assert!(
            matches!(&exact, Err(ProcError::NameNotFound { name, in_command_line })
                if name == &marker && *in_command_line >= 1),
            "{exact:?}"
        );
        // with --cmd that process is the match, and the only one
        let found = cmd.unwrap();
        assert_eq!(found.iter().map(|p| p.pid).collect::<Vec<_>>(), vec![pid]);
    }

    #[cfg(unix)]
    #[test]
    fn test_find_orphans_returns_ok() {
        // Should not error — may or may not find orphans depending on system state
        let result = Process::find_orphans();
        assert!(result.is_ok());
    }

    #[cfg(not(unix))]
    #[test]
    fn find_orphans_is_not_supported_on_windows() {
        let result = Process::find_orphans();
        assert!(
            matches!(&result, Err(ProcError::NotSupported(m)) if m.starts_with("orphans is not supported on Windows")),
            "{result:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_is_system_process_system_paths() {
        let make_proc = |exe: Option<&str>, cwd: Option<&str>| Process {
            pid: 100,
            name: "test".to_string(),
            exe_path: exe.map(String::from),
            cwd: cwd.map(String::from),
            command: None,
            argv0: None,
            raw: None,
            cpu_percent: 0.0,
            memory_mb: 0.0,
            status: ProcessStatus::Running,
            user: None,
            parent_pid: Some(1),
            start_time: None,
            uptime_secs: None,
        };

        // System daemons with cwd "/" and system exe paths
        assert!(Process::is_system_process(&make_proc(
            Some("/usr/sbin/sshd"),
            Some("/")
        )));
        assert!(Process::is_system_process(&make_proc(
            Some("/System/Library/foo"),
            Some("/")
        )));
        assert!(Process::is_system_process(&make_proc(
            Some("/usr/bin/systemd"),
            Some("/")
        )));
        assert!(Process::is_system_process(&make_proc(
            Some("/usr/lib/snapd/snapd"),
            Some("/")
        )));

        // No exe path with cwd "/" = kernel thread
        assert!(Process::is_system_process(&make_proc(None, Some("/"))));

        // No cwd at all = likely kernel thread
        assert!(Process::is_system_process(&make_proc(
            Some("/usr/bin/foo"),
            None
        )));

        // Every system directory counts, each checked on its own
        for exe in [
            "/System/x",
            "/usr/libexec/x",
            "/usr/sbin/x",
            "/sbin/x",
            "/usr/bin/x",
            "/usr/lib/x",
            "/usr/lib64/x",
            "/lib/x",
            "/lib64/x",
            "/opt/x",
            "/snap/x",
        ] {
            assert!(
                Process::is_system_process(&make_proc(Some(exe), Some("/"))),
                "{exe}"
            );
        }
        // a daemon with cwd "/" outside them still counts: nothing says it is a user's
        assert!(Process::is_system_process(&make_proc(
            Some("/srv/x"),
            Some("/")
        )));

        // User process with user cwd = NOT system
        assert!(!Process::is_system_process(&make_proc(
            Some("/usr/bin/node"),
            Some("/home/user/project")
        )));
        assert!(!Process::is_system_process(&make_proc(
            Some("/home/user/.local/bin/app"),
            Some("/home/user")
        )));
    }

    #[cfg(unix)]
    #[test]
    fn test_parse_signal_name_valid() {
        use nix::sys::signal::Signal;

        assert_eq!(parse_signal_name("HUP").unwrap(), Signal::SIGHUP);
        assert_eq!(parse_signal_name("hup").unwrap(), Signal::SIGHUP);
        assert_eq!(parse_signal_name("SIGHUP").unwrap(), Signal::SIGHUP);
        assert_eq!(parse_signal_name("sighup").unwrap(), Signal::SIGHUP);
        assert_eq!(parse_signal_name("INT").unwrap(), Signal::SIGINT);
        assert_eq!(parse_signal_name("QUIT").unwrap(), Signal::SIGQUIT);
        assert_eq!(parse_signal_name("ABRT").unwrap(), Signal::SIGABRT);
        assert_eq!(parse_signal_name("KILL").unwrap(), Signal::SIGKILL);
        assert_eq!(parse_signal_name("TERM").unwrap(), Signal::SIGTERM);
        assert_eq!(parse_signal_name("STOP").unwrap(), Signal::SIGSTOP);
        assert_eq!(parse_signal_name("CONT").unwrap(), Signal::SIGCONT);
        assert_eq!(parse_signal_name("USR1").unwrap(), Signal::SIGUSR1);
        assert_eq!(parse_signal_name("USR2").unwrap(), Signal::SIGUSR2);
    }

    #[cfg(unix)]
    #[test]
    fn test_parse_signal_name_invalid() {
        assert!(parse_signal_name("INVALID").is_err());
        assert!(parse_signal_name("FOO").is_err());
        assert!(parse_signal_name("").is_err());
    }

    #[cfg(unix)]
    #[test]
    fn test_parse_signal_name_case_insensitive() {
        use nix::sys::signal::Signal;

        assert_eq!(parse_signal_name("term").unwrap(), Signal::SIGTERM);
        assert_eq!(parse_signal_name("Term").unwrap(), Signal::SIGTERM);
        assert_eq!(parse_signal_name("TERM").unwrap(), Signal::SIGTERM);
        assert_eq!(parse_signal_name("sigterm").unwrap(), Signal::SIGTERM);
        assert_eq!(parse_signal_name("SigTerm").unwrap(), Signal::SIGTERM);
    }

    #[cfg(unix)]
    #[test]
    fn test_send_signal_nonexistent_process() {
        use nix::sys::signal::Signal;

        // PID 99999999 almost certainly doesn't exist
        let proc = Process {
            pid: 99999999,
            name: "ghost".to_string(),
            exe_path: None,
            cwd: None,
            command: None,
            argv0: None,
            raw: None,
            cpu_percent: 0.0,
            memory_mb: 0.0,
            status: ProcessStatus::Running,
            user: None,
            parent_pid: None,
            start_time: None,
            uptime_secs: None,
        };

        let result = proc.send_signal(Signal::SIGCONT);
        assert!(result.is_err());
    }

    /// A record of a process that doesn't exist
    fn ghost() -> Process {
        Process {
            pid: 99999999,
            name: "ghost".to_string(),
            exe_path: None,
            cwd: None,
            command: None,
            argv0: None,
            raw: None,
            cpu_percent: 0.0,
            memory_mb: 0.0,
            status: ProcessStatus::Running,
            user: None,
            parent_pid: None,
            start_time: None,
            uptime_secs: None,
        }
    }

    #[test]
    fn every_sysinfo_status_maps_to_ours() {
        for (sys, ours) in [
            (SysProcessStatus::Run, ProcessStatus::Running),
            (SysProcessStatus::Sleep, ProcessStatus::Sleeping),
            (SysProcessStatus::Stop, ProcessStatus::Stopped),
            (SysProcessStatus::Zombie, ProcessStatus::Zombie),
            (SysProcessStatus::Dead, ProcessStatus::Dead),
            (SysProcessStatus::Idle, ProcessStatus::Unknown),
        ] {
            assert_eq!(ProcessStatus::from(sys), ours, "{sys:?}");
        }
    }

    #[test]
    fn a_process_that_is_gone_does_not_look_stuck() {
        assert!(!ghost().looks_stuck_now());
    }

    #[test]
    fn killing_a_process_that_is_already_gone_is_success() {
        assert!(matches!(ghost().kill(), Err(ProcError::ProcessNotFound(_))));
        ghost().kill_and_wait().unwrap();
    }

    #[test]
    fn a_kill_that_was_not_delivered_is_an_error() {
        kill_outcome(true, 7).unwrap();
        let err = kill_outcome(false, 7).unwrap_err();
        assert!(
            matches!(&err, ProcError::SignalError(m) if m == "Failed to kill process 7"),
            "{err:?}"
        );
    }

    #[test]
    fn taskkill_without_force_reports_what_it_said() {
        #[cfg(unix)]
        use std::os::unix::process::ExitStatusExt;
        #[cfg(windows)]
        use std::os::windows::process::ExitStatusExt;
        use std::process::{ExitStatus, Output};

        let output = |raw, stdout: &str, stderr: &str| Output {
            status: ExitStatus::from_raw(raw),
            stdout: stdout.as_bytes().to_vec(),
            stderr: stderr.as_bytes().to_vec(),
        };
        taskkill_outcome(&output(0, "SUCCESS: sent termination signal", "")).unwrap();

        // exit code 1 on Windows; the same wait status on Unix
        #[cfg(unix)]
        let failed = 1 << 8;
        #[cfg(windows)]
        let failed = 1;
        let err =
            taskkill_outcome(&output(failed, "", "ERROR: could not be terminated")).unwrap_err();
        assert!(
            matches!(&err, ProcError::SignalError(m) if m == "ERROR: could not be terminated"),
            "{err:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn orphans_are_the_children_of_init_that_are_not_system_daemons() {
        let proc = |pid: u32, ppid: Option<u32>, exe: Option<&str>, cwd: Option<&str>| Process {
            pid,
            name: format!("p{pid}"),
            exe_path: exe.map(String::from),
            cwd: cwd.map(String::from),
            parent_pid: ppid,
            ..ghost()
        };
        let orphans = Process::orphans_among(vec![
            // a user's process whose parent died
            proc(10, Some(1), Some("/home/z/app"), Some("/home/z")),
            // a system daemon: cwd "/" and an exe in a system directory
            proc(11, Some(1), Some("/usr/sbin/sshd"), Some("/")),
            // init itself, and a process with a live parent
            proc(1, Some(1), Some("/sbin/init"), Some("/home/z")),
            proc(12, Some(500), Some("/home/z/app"), Some("/home/z")),
            // no parent known
            proc(13, None, Some("/home/z/app"), Some("/home/z")),
        ]);
        let pids: Vec<u32> = orphans.iter().map(|p| p.pid).collect();
        assert_eq!(pids, vec![10]);
    }

    #[cfg(unix)]
    #[test]
    fn a_missing_lsof_finds_no_open_file_owners() {
        let found = Process::find_by_open_file_with("proc-no-such-lsof", std::path::Path::new("/"));
        assert!(found.unwrap().is_empty());
    }

    #[test]
    fn a_wait_for_a_process_that_stays_is_a_wait_and_then_an_error() {
        let mut child = crate::test_support::idle_child();
        let record = crate::test_support::record_of(&child);
        let started = std::time::Instant::now();
        // a kill that does nothing: the process is still there, however long
        // it is looked at
        let result = record.kill_then_wait(Duration::from_millis(300), |_| Ok(()));
        let waited = started.elapsed();
        let still_there = child.try_wait().unwrap().is_none();
        crate::test_support::end(&mut child);
        assert!(
            matches!(&result, Err(ProcError::SignalError(_))),
            "{result:?}"
        );
        assert!(waited >= Duration::from_millis(300), "{waited:?}");
        assert!(still_there);
    }

    #[test]
    fn a_process_still_alive_when_the_wait_ends_is_an_error() {
        let mut child = crate::test_support::idle_child();
        let record = crate::test_support::record_of(&child);
        // no time to wait: the SIGKILL is sent, but the process isn't seen gone
        let result = record.kill_and_wait_within(Duration::ZERO);
        let _ = child.kill();
        let _ = child.wait();
        assert!(
            matches!(&result, Err(ProcError::SignalError(m))
                if m == &format!("Process {} is still running 0 seconds after SIGKILL", record.pid)),
            "{result:?}"
        );
    }

    /// One kinfo_proc record, with the fields `zombies_in` reads
    #[cfg(target_os = "macos")]
    fn kinfo(pid: u32, stat: u8, comm: &str, ruid: u32, ppid: u32, start: u64) -> Vec<u8> {
        let mut rec = vec![0u8; KINFO_PROC_SIZE];
        rec[0..8].copy_from_slice(&start.to_ne_bytes());
        rec[36] = stat;
        rec[40..44].copy_from_slice(&pid.to_ne_bytes());
        rec[243..243 + comm.len()].copy_from_slice(comm.as_bytes());
        rec[392..396].copy_from_slice(&ruid.to_ne_bytes());
        rec[560..564].copy_from_slice(&ppid.to_ne_bytes());
        rec
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn zombies_are_read_from_the_kernels_table() {
        let known = std::collections::HashSet::from([30]);
        let table: Vec<u8> = [
            kinfo(10, 5, "defunct-app", 0, 99, 1_700_000_000),
            // no name left, and no start time
            kinfo(11, 5, "", 0, 1, 0),
            // alive, not a zombie
            kinfo(20, 2, "alive", 0, 1, 1_700_000_000),
            // already listed by sysinfo
            kinfo(30, 5, "known", 0, 1, 1_700_000_000),
            // the kernel's own slot
            kinfo(0, 5, "kernel", 0, 0, 0),
        ]
        .concat();

        let zombies = zombies_in(&table, &known);
        let pids: Vec<u32> = zombies.iter().map(|z| z.pid).collect();
        assert_eq!(pids, vec![10, 11]);

        let named = &zombies[0];
        assert_eq!(named.name, "defunct-app");
        assert_eq!(named.status, ProcessStatus::Zombie);
        assert_eq!(named.parent_pid, Some(99));
        assert_eq!(named.start_time, Some(1_700_000_000));
        assert!(named.uptime_secs.unwrap() > 0);
        assert_eq!(named.user.as_deref(), Some("root"));

        let unnamed = &zombies[1];
        assert_eq!(unnamed.name, "<defunct>");
        assert_eq!(unnamed.start_time, None);
        assert_eq!(unnamed.uptime_secs, None);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn a_table_of_an_unknown_layout_shows_no_zombies() {
        let known = std::collections::HashSet::new();
        let mut table = kinfo(10, 5, "z", 0, 1, 0);
        table.push(0);
        assert!(zombies_in(&table, &known).is_empty());
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn a_refused_sysctl_gives_an_empty_table() {
        use std::cell::Cell;

        // refused when asked for the size
        assert!(read_proc_table(|_, _| -1).is_empty());

        // refused when asked for the table
        let calls = Cell::new(0);
        let table = read_proc_table(|_, size| {
            calls.set(calls.get() + 1);
            if calls.get() == 1 {
                *size = 2 * KINFO_PROC_SIZE;
                0
            } else {
                -1
            }
        });
        assert_eq!(calls.get(), 2);
        assert!(table.is_empty());

        // answered: the table is cut to the size the kernel reports
        let calls = Cell::new(0);
        let table = read_proc_table(|buf, size| {
            calls.set(calls.get() + 1);
            if calls.get() == 1 {
                *size = 2 * KINFO_PROC_SIZE;
            } else {
                assert_eq!(*size, 66 * KINFO_PROC_SIZE, "room for 64 newcomers");
                // SAFETY: `buf` has `*size` writable bytes
                unsafe { buf.cast::<u8>().write(7) };
                *size = KINFO_PROC_SIZE;
            }
            0
        });
        assert_eq!(table.len(), KINFO_PROC_SIZE);
        assert_eq!(table[0], 7);
    }
}