sys-lib 0.5.1

System facts for Rust services: OS, CPU, memory, disks, network, host, this process, virtualization, power, and device identity, container-aware by default, plus build info, instance info, and a process guard. No subprocesses, zero third-party dependencies.
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
//! Live comparison: sys-lib's answers on this machine against the OS's own
//! tools (PLAN.md 19.1). Tests may start programs; the library never does.
//! Outside CI a missing tool skips its comparison; on CI it fails, so a runner
//! image change cannot quietly turn a test off.

use std::process::Command;

use sys_lib::{cpu, host, os, process};

/// A tool's trimmed standard output, or `None` when it is missing or fails.
fn tool(program: &str, args: &[&str]) -> Option<String> {
    let out = Command::new(program)
        .args(args)
        // nproc honours these; the comparison is with the affinity mask itself.
        .env_remove("OMP_NUM_THREADS")
        .env_remove("OMP_THREAD_LIMIT")
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&out.stdout).trim().to_owned())
}

/// The tool's output, required on CI.
fn need(program: &str, args: &[&str]) -> Option<String> {
    let value = tool(program, args);
    if value.is_none() {
        assert!(
            std::env::var_os("CI").is_none(),
            "{program} {args:?} is missing on CI"
        );
        eprintln!("skipped: {program} {args:?} is not available here");
    }
    value
}

#[cfg_attr(
    not(any(target_os = "linux", target_os = "macos", windows)),
    allow(dead_code)
)]
fn number(text: &str) -> usize {
    text.trim()
        .parse()
        .unwrap_or_else(|_| panic!("not a number: {text:?}"))
}

#[cfg(unix)]
#[test]
fn test_live_unix_kernel_host_and_user_match_the_tools() {
    if let Some(release) = need("uname", &["-r"]) {
        assert_eq!(os::kernel(), release);
    }
    if let Some(node) = need("uname", &["-n"]) {
        assert_eq!(host::name().unwrap(), node);
    }
    let user = process::user().unwrap();
    if let Some(name) = need("id", &["-un"]) {
        assert_eq!(user.name, name);
    }
    if let Some(uid) = need("id", &["-u"]) {
        assert_eq!(user.id, Some(uid.parse().unwrap()));
        assert_eq!(process::is_elevated().unwrap(), uid == "0");
        assert_eq!(user.is_admin, uid == "0");
    }
}

#[cfg(target_os = "linux")]
#[test]
fn test_live_linux_cpu_counts_match_getconf_and_nproc() {
    if let Some(conf) = need("getconf", &["_NPROCESSORS_CONF"]) {
        assert_eq!(cpu::logical(), number(&conf));
    }
    if let Some(nproc) = need("nproc", &[]) {
        // nproc is the affinity mask; available() also applies the cgroup
        // cpuset and CPU quota, so it can only be lower. CI runners set no quota.
        assert!(cpu::available() <= number(&nproc));
        if std::env::var_os("CI").is_some() {
            assert_eq!(cpu::available(), number(&nproc));
        }
    }
    if let Some(machine) = need("uname", &["-m"]) {
        let wide = matches!(
            machine.as_str(),
            "x86_64" | "aarch64" | "ppc64le" | "ppc64" | "s390x" | "riscv64"
        );
        assert_eq!(cpu::is_64bit(), wide, "uname -m says {machine}");
    }
}

#[cfg(target_os = "linux")]
#[test]
fn test_live_linux_distro_matches_a_shell_reading_os_release() {
    // The shell is the reference parser os-release(5) was written for.
    let path = ["/etc/os-release", "/usr/lib/os-release"]
        .into_iter()
        .find(|p| std::path::Path::new(p).exists());
    let Some(path) = path else {
        assert_eq!(os::distro(), "Linux");
        return;
    };
    let script = format!(
        ". {path} && printf '%s\\n' \"$ID\" \"$NAME\" \"$PRETTY_NAME\" \"$VERSION_ID\" \"$ID_LIKE\""
    );
    let Some(out) = need("sh", &["-c", &script]) else {
        return;
    };
    let mut fields = out.split('\n').chain(std::iter::repeat(""));
    let mut next = || fields.next().unwrap().to_owned();
    let (id, name, pretty, version_id, id_like) = (next(), next(), next(), next(), next());
    assert_eq!(os::distro_id(), if id.is_empty() { "linux" } else { &id });
    assert_eq!(os::distro(), if name.is_empty() { "Linux" } else { &name });
    let expected_name = [&pretty, &name]
        .into_iter()
        .find(|s| !s.is_empty())
        .map_or("Linux", |s| s.as_str());
    assert_eq!(os::name(), expected_name);
    assert_eq!(
        os::version().map(|v| v.text),
        (!version_id.is_empty()).then_some(version_id.as_str())
    );
    for like in id_like.split_whitespace() {
        assert!(
            os::is_like(like),
            "is_like({like:?}) with ID_LIKE={id_like:?}"
        );
    }
    assert!(os::is_like(os::distro_id()));
}

#[cfg(target_os = "macos")]
#[test]
fn test_live_macos_matches_sysctl_and_sw_vers() {
    let sysctl = |name: &str| need("sysctl", &["-n", name]);
    if let Some(n) = sysctl("hw.logicalcpu_max") {
        assert_eq!(cpu::logical(), number(&n));
    }
    if let Some(n) = sysctl("hw.physicalcpu_max") {
        assert_eq!(cpu::physical(), number(&n));
    }
    if let Some(n) = sysctl("hw.activecpu") {
        assert_eq!(cpu::available(), number(&n));
    }
    if let Some(brand) = sysctl("machdep.cpu.brand_string") {
        assert_eq!(cpu::raw_name(), Some(brand.as_str()));
    }
    if let Some(v) = need("sw_vers", &["-productVersion"]) {
        assert_eq!(os::version().map(|v| v.text), Some(v.as_str()));
        assert!(
            os::name().starts_with(&format!("macOS {v}")),
            "{}",
            os::name()
        );
    }
    assert_eq!(os::distro(), "macOS");
    assert_eq!(os::distro_id(), "macos");
}

#[cfg(windows)]
#[test]
fn test_live_windows_matches_cim_and_dotnet() {
    let script = "$p = @(Get-CimInstance Win32_Processor); $o = Get-CimInstance Win32_OperatingSystem; \
        $id = [Security.Principal.WindowsIdentity]::GetCurrent(); \
        ($p | Measure-Object NumberOfLogicalProcessors -Sum).Sum; \
        ($p | Measure-Object NumberOfCores -Sum).Sum; \
        $p[0].Name.Trim(); $o.Version; [System.Net.Dns]::GetHostName(); [Environment]::UserName; \
        ([Security.Principal.WindowsPrincipal]$id).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)";
    let Some(out) = need(
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script],
    ) else {
        return;
    };
    let lines: Vec<&str> = out.lines().map(str::trim).collect();
    assert_eq!(lines.len(), 7, "{out}");
    assert_eq!(cpu::logical(), number(lines[0]));
    assert_eq!(cpu::physical(), number(lines[1]));
    assert!(cpu::available() <= cpu::logical());
    if std::env::var_os("CI").is_some() {
        assert_eq!(cpu::available(), cpu::logical());
    }
    assert_eq!(cpu::raw_name(), Some(lines[2]));

    // "10.0.26200": major.minor.build; sys-lib's version text adds the update revision.
    let v = os::version().expect("Windows always has a version");
    assert_eq!(format!("{}.{}.{}", v.major, v.minor, v.patch), lines[3]);
    assert!(os::name().starts_with("Windows "), "{}", os::name());
    assert_eq!(os::distro(), "Windows");

    assert!(host::name().unwrap().eq_ignore_ascii_case(lines[4]));
    let user = process::user().unwrap();
    assert!(
        user.name.eq_ignore_ascii_case(lines[5]),
        "{} vs {}",
        user.name,
        lines[5]
    );
    // IsInRole sees the filtered token under UAC, as TokenElevation does.
    assert_eq!(
        process::is_elevated().unwrap(),
        lines[6].eq_ignore_ascii_case("true")
    );
}

#[cfg(target_os = "macos")]
#[test]
fn test_live_macos_identity_matches_sysctl_and_sw_vers() {
    use sys_lib::{cpu::Arch, virt};
    let sysctl = |name: &str| need("sysctl", &["-n", name]);
    if let Some(v) = need("sw_vers", &["-productVersion"]) {
        let major: u32 = v.split('.').next().unwrap().parse().unwrap();
        if (11..=15).contains(&major) || major == 26 {
            let codename = os::codename().expect("a released major has a codename");
            assert!(os::name().ends_with(codename), "{}", os::name());
        }
    }
    assert_eq!(os::edition(), None);
    assert_eq!(os::is_server_edition(), None);
    if let Some(n) = tool("sysctl", &["-n", "hw.optional.arm64"]) {
        let arch = if n == "1" { Arch::Aarch64 } else { cpu::arch() };
        assert_eq!(cpu::native_arch(), arch);
    }
    assert_eq!(
        cpu::is_translated(),
        tool("sysctl", &["-n", "sysctl.proc_translated"]).as_deref() == Some("1")
    );
    let model = sysctl("hw.model");
    if let Some(m) = &model {
        let found = host::model().expect("hw.model answers");
        assert_eq!(found.name, m);
        assert_eq!(found.vendor, Some("Apple Inc."));
        if m.starts_with("MacBook") && !virt::is_vm() {
            assert_eq!(os::form_factor(), os::FormFactor::Laptop);
        }
        if m.starts_with("VirtualMac") {
            assert_eq!(
                virt::hypervisor(),
                Some(virt::Hypervisor::AppleVirtualization)
            );
        }
    }
    if tool("sysctl", &["-n", "kern.hv_vmm_present"]).as_deref() == Some("1") {
        assert!(virt::is_vm());
        assert_eq!(os::form_factor(), os::FormFactor::Unknown);
    }
    assert_eq!(virt::cloud(), None);
    assert!(virt::detect().evidence.iter().all(|e| !e.check.is_empty()));
}

#[cfg(target_os = "macos")]
#[test]
fn test_live_macos_topology_matches_sysctl() {
    let sysctl = |name: &str| need("sysctl", &["-n", name]);
    let cores = &cpu::topology().cores;
    assert_eq!(cores.len(), cpu::physical());
    let logical: usize = cores.iter().map(|c| c.logical.len()).sum();
    assert_eq!(logical, cpu::logical());
    assert_eq!(cpu::numa_nodes().len(), 1);
    assert_eq!(cpu::numa_nodes()[0].cpus.len(), cpu::logical());
    if let Some(n) = sysctl("hw.memsize") {
        let memory = cpu::numa_nodes()[0].memory.map(|m| m.raw());
        assert_eq!(memory, Some(n.parse().unwrap()));
    }
    if let Some(n) = sysctl("hw.cachelinesize") {
        assert_eq!(cpu::cache_line(), number(&n));
    }
    if let Some(n) = sysctl("hw.nperflevels") {
        assert_eq!(cpu::is_hybrid(), number(&n) > 1);
    }
    for level in 0..2 {
        let Some(n) = tool(
            "sysctl",
            &["-n", &format!("hw.perflevel{level}.physicalcpu_max")],
        ) else {
            continue;
        };
        if cpu::is_hybrid() {
            let kind = if level == 0 {
                cpu::CoreKind::Performance
            } else {
                cpu::CoreKind::Efficiency
            };
            let found = cores.iter().filter(|c| c.kind == kind).count();
            assert_eq!(found, number(&n), "perflevel {level}");
        }
    }
}

#[cfg(target_os = "macos")]
#[test]
fn test_live_macos_disk_of_matches_df_and_stat() {
    use sys_lib::{disk, virt};
    let found = disk::of("/").unwrap();
    assert_eq!(found.mount_point, std::path::Path::new("/"));
    if let Some(df) = need("df", &["/"]) {
        let device = df
            .lines()
            .nth(1)
            .unwrap()
            .split_whitespace()
            .next()
            .unwrap();
        assert_eq!(found.device, device);
    }
    if let Some(volume) = tool("diskutil", &["info", "/"]) {
        let field = |name: &str| {
            volume
                .lines()
                .find_map(|l| l.trim().strip_prefix(name))
                .map(|v| v.trim_start_matches(':').trim().to_owned())
        };
        if let Some(name) = field("Volume Name") {
            assert_eq!(found.label.as_deref(), Some(name.as_str()));
        }
        // A virtual disk may report no medium to the registry.
        match field("Solid State").as_deref() {
            Some("Yes") if !virt::is_vm() => assert_eq!(found.kind, disk::DiskKind::Ssd),
            Some("No") if !virt::is_vm() => assert_eq!(found.kind, disk::DiskKind::Hdd),
            _ => {}
        }
    }
}

#[cfg(target_os = "macos")]
#[test]
fn test_live_macos_network_matches_route_and_scutil() {
    use sys_lib::net;
    // `route get` follows the longest match, so a VPN's `0.0.0.0/1` answers for
    // it; the two are comparable when the default route itself matched.
    let route = tool("route", &["-n", "get", "default"]);
    if let Some(route) = route.filter(|r| r.contains("mask: default")) {
        let interface = route
            .lines()
            .find_map(|l| l.trim().strip_prefix("interface:"))
            .map(str::trim);
        let found = net::primary().unwrap();
        assert_eq!(found.as_ref().map(|i| i.name.as_str()), interface);
    }
    if let Some(scutil) = need("scutil", &["--dns"]) {
        // Every server the resolver is given is in scutil's report.
        match net::dns() {
            Ok(dns) => {
                for server in &dns.servers {
                    assert!(scutil.contains(&server.to_string()), "{server}");
                }
            }
            Err(e) => assert!(matches!(e, sys_lib::Error::NotFound { .. }), "{e}"),
        }
    }
}

#[cfg(target_os = "macos")]
#[test]
fn test_live_macos_power_matches_pmset() {
    use sys_lib::power;
    let Some(batt) = need("pmset", &["-g", "batt"]) else {
        return;
    };
    assert_eq!(power::has_battery(), batt.contains("InternalBattery"));
    if batt.contains("'AC Power'") {
        assert_eq!(power::on_ac().unwrap(), Some(true));
    } else if batt.contains("'Battery Power'") {
        assert_eq!(power::on_ac().unwrap(), Some(false));
    }
    if let Some(b) = power::battery().unwrap() {
        // "-InternalBattery-0 (id=...)  87%; discharging; 3:12 remaining"
        let shown: f32 = batt
            .split_whitespace()
            .find_map(|w| w.strip_suffix("%;"))
            .unwrap()
            .parse()
            .unwrap();
        assert!(
            (b.charge.value() - shown).abs() <= 2.0,
            "{} vs {shown}",
            b.charge
        );
    }
}

#[cfg(target_os = "macos")]
#[test]
fn test_live_macos_time_and_sessions_match_the_tools() {
    let tz = host::timezone().unwrap();
    if let Some(offset) = need("date", &["+%z"]) {
        // "+0100"
        let digits: i32 = offset[1..].parse().unwrap();
        let seconds = (digits / 100) * 3600 + (digits % 100) * 60;
        let sign = if offset.starts_with('-') { -1 } else { 1 };
        assert_eq!(tz.utc_offset_seconds, sign * seconds);
    }
    if let Some(name) = need("date", &["+%Z"]) {
        assert_eq!(tz.abbreviation.as_deref(), Some(name.as_str()));
    }
    let _ = host::clock_sync().unwrap();
    if let Some(who) = need("who", &[]) {
        for session in host::sessions().unwrap() {
            assert!(who.contains(&session.user), "{}", session.user);
        }
    }
}

/// `a` and `b` agree to within 2% of the larger plus `slack` bytes: memory
/// and free space move between the two readings (PLAN.md 19.1).
#[allow(dead_code)]
fn close(a: u64, b: u64, slack: u64) -> bool {
    a.abs_diff(b) <= a.max(b) / 50 + slack
}

#[allow(dead_code)]
const MIB: u64 = 1 << 20;

#[cfg(target_os = "linux")]
#[test]
fn test_live_linux_memory_disk_and_uptime_match_the_tools() {
    use sys_lib::{disk, mem};
    if let Some(free) = need("free", &["-b"]) {
        let row = |label: &str| -> Vec<u64> {
            free.lines()
                .find(|l| l.starts_with(label))
                .map(|l| {
                    l.split_whitespace()
                        .skip(1)
                        .filter_map(|v| v.parse().ok())
                        .collect()
                })
                .unwrap_or_default()
        };
        let m = mem::snapshot().unwrap();
        let memrow = row("Mem:");
        assert_eq!(m.host_total.raw(), memrow[0], "MemTotal");
        assert!(
            close(m.host_free.raw(), memrow[5], 16 * MIB),
            "available {} vs {}",
            m.host_free,
            memrow[5]
        );
        assert_eq!(m.swap.total.raw(), row("Swap:")[0], "SwapTotal");
    }
    if let Some(df) = need("df", &["-B1", "--output=size,avail", "/"]) {
        let values: Vec<u64> = df
            .lines()
            .nth(1)
            .unwrap()
            .split_whitespace()
            .filter_map(|v| v.parse().ok())
            .collect();
        let s = disk::space("/").unwrap();
        assert_eq!(s.total.raw(), values[0], "df size");
        assert!(close(s.available.raw(), values[1], 16 * MIB), "df avail");
    }
    if let Some(online) = need("getconf", &["_NPROCESSORS_ONLN"]) {
        assert_eq!(cpu::online(), number(&online));
    }
    let proc_uptime: f64 = std::fs::read_to_string("/proc/uptime")
        .unwrap()
        .split_whitespace()
        .next()
        .unwrap()
        .parse()
        .unwrap();
    let up = host::uptime().unwrap().as_secs_f64();
    assert!(
        (up - proc_uptime).abs() < 2.0,
        "uptime {up} vs /proc/uptime {proc_uptime}"
    );
}

#[cfg(target_os = "macos")]
#[test]
fn test_live_macos_memory_disk_load_and_uptime_match_the_tools() {
    use sys_lib::{disk, mem};
    if let Some(n) = need("sysctl", &["-n", "hw.memsize"]) {
        assert_eq!(mem::host_total().unwrap().raw(), n.parse::<u64>().unwrap());
    }
    if let Some(df) = need("df", &["-k", "/"]) {
        let blocks: u64 = df
            .lines()
            .nth(1)
            .unwrap()
            .split_whitespace()
            .nth(1)
            .unwrap()
            .parse()
            .unwrap();
        let s = disk::space("/").unwrap();
        assert!(
            close(s.total.raw(), blocks * 1024, 16 * MIB),
            "{} vs {}",
            s.total,
            blocks * 1024
        );
    }
    if let Some(n) = need("sysctl", &["-n", "hw.activecpu"]) {
        assert_eq!(cpu::online(), number(&n));
    }
    if let Some(l) = need("sysctl", &["-n", "vm.loadavg"]) {
        let one: f32 = l
            .trim_matches(|c| c == '{' || c == '}' || c == ' ')
            .split_whitespace()
            .next()
            .unwrap()
            .parse()
            .unwrap();
        let load = cpu::load().unwrap().unwrap();
        assert!((load.one - one).abs() < 1.0, "{} vs {one}", load.one);
    }
    if let Some(b) = need("sysctl", &["-n", "kern.boottime"]) {
        // "{ sec = 1700000000, usec = 123456 } Tue Nov 14 ..."
        let sec: u64 = b
            .split("sec = ")
            .nth(1)
            .unwrap()
            .split(',')
            .next()
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        let boot = host::boot_time()
            .unwrap()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert!(boot.abs_diff(sec) <= 2, "{boot} vs {sec}");
    }
}

#[cfg(windows)]
#[test]
fn test_live_windows_memory_disk_and_uptime_match_cim_and_dotnet() {
    use sys_lib::{disk, mem};
    let script = "$cs = Get-CimInstance Win32_ComputerSystem; $os = Get-CimInstance Win32_OperatingSystem; \
        $d = [System.IO.DriveInfo]::new($env:SystemDrive); \
        $cs.TotalPhysicalMemory; $os.FreePhysicalMemory; $d.TotalSize; $d.AvailableFreeSpace; \
        [long]((Get-Date) - $os.LastBootUpTime).TotalMilliseconds";
    let Some(out) = need(
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script],
    ) else {
        return;
    };
    let v: Vec<u64> = out.lines().map(|l| l.trim().parse().unwrap()).collect();
    assert_eq!(v.len(), 5, "{out}");
    let m = mem::snapshot().unwrap();
    assert_eq!(m.host_total.raw(), v[0], "TotalPhysicalMemory");
    assert!(
        close(m.host_free.raw(), v[1] * 1024, 64 * MIB),
        "free {} vs {}",
        m.host_free,
        v[1] * 1024
    );
    let drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".to_owned()) + "\\";
    let s = disk::space(&drive).unwrap();
    assert_eq!(s.total.raw(), v[2], "drive size");
    assert!(close(s.available.raw(), v[3], 64 * MIB), "drive available");
    // The boot time from CIM (Windows PowerShell 5.1 has no TickCount64).
    // Fast Startup and sleep can separate the two clocks on a desktop, so
    // the comparison is strict only on CI's virtual machines.
    let up = host::uptime().unwrap().as_millis() as u64;
    if std::env::var_os("CI").is_some() {
        assert!(
            up.abs_diff(v[4]) < 5_000,
            "uptime {up} vs LastBootUpTime {}",
            v[4]
        );
    }
}

/// A PowerShell script's output lines, each a value in order, ending at a fixed
/// last line so an empty value in the middle survives the trim.
#[cfg(windows)]
fn cim_lines(script: &str, want: usize) -> Option<Vec<String>> {
    let out = need(
        "powershell",
        &["-NoProfile", "-NonInteractive", "-Command", script],
    )?;
    let lines: Vec<String> = out.lines().map(|l| l.trim().to_owned()).collect();
    assert_eq!(lines.len(), want, "{out}");
    Some(lines)
}

#[cfg(windows)]
#[test]
fn test_live_windows_identity_and_firmware_match_cim() {
    use sys_lib::{cpu::Arch, virt};
    let script = r#"$cs = Get-CimInstance Win32_ComputerSystem; $b = Get-CimInstance Win32_BIOS;
        $bb = Get-CimInstance Win32_BaseBoard; $o = Get-CimInstance Win32_OperatingSystem;
        $p = @(Get-CimInstance Win32_Processor)[0];
        $e = @(Get-CimInstance Win32_SystemEnclosure)[0];
        "$($cs.Manufacturer)"; "$($cs.Model)"; "$($b.Manufacturer)"; "$($b.SMBIOSBIOSVersion)";
        "$($bb.Manufacturer)"; "$($bb.Product)"; "$($o.ProductType)";
        (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').EditionID;
        "$($p.Architecture)"; "$($e.ChassisTypes[0])"; "$($cs.HypervisorPresent)"; "end""#;
    let Some(v) = cim_lines(script, 12) else {
        return;
    };
    // CIM reads the same SMBIOS strings, placeholders included: only a string
    // sys-lib kept is compared.
    if let Some(m) = host::model() {
        assert_eq!(m.name, v[1]);
        if let Some(vendor) = m.vendor {
            assert_eq!(vendor, v[0]);
        }
    }
    let firmware = host::firmware().expect("the firmware type is always known");
    if let Some(vendor) = firmware.vendor {
        assert_eq!(vendor, v[2]);
    }
    if let Some(version) = firmware.version {
        assert_eq!(version, v[3]);
    }
    if let Some(b) = host::board() {
        if let Some(vendor) = b.vendor {
            assert_eq!(vendor, v[4]);
        }
        if let Some(name) = b.name {
            assert_eq!(name, v[5]);
        }
    }
    assert_eq!(os::is_server_edition(), Some(v[6] != "1"));
    assert_eq!(os::edition(), Some(v[7].as_str()));
    let native = match v[8].as_str() {
        "9" => Arch::X86_64,
        "12" => Arch::Aarch64,
        "0" => Arch::X86,
        other => panic!("Win32_Processor.Architecture {other}"),
    };
    assert_eq!(cpu::native_arch(), native);

    // A host with Hyper-V, WSL 2, or VBS has a hypervisor underneath and is not
    // a VM (E-84); a machine without one cannot be a VM at all.
    let names_a_vm = ["Virtual Machine", "VMware", "VirtualBox", "QEMU", "KVM"]
        .iter()
        .any(|n| v[0].contains(n) || v[1].contains(n));
    if names_a_vm {
        assert!(virt::is_vm(), "{} {}", v[0], v[1]);
    }
    if v[10].eq_ignore_ascii_case("false") {
        assert!(!virt::is_vm());
    }
    if virt::is_vm() {
        assert_eq!(os::form_factor(), os::FormFactor::Unknown);
        assert!(!virt::detect().evidence.is_empty());
    } else if v[9] == "3" {
        assert!(os::is_desktop(), "{:?}", os::detect_form_factor());
    }
}

#[cfg(windows)]
#[test]
fn test_live_windows_topology_and_modules_match_cim() {
    use sys_lib::{cpu::CacheKind, mem};
    let script = r#"$p = @(Get-CimInstance Win32_Processor);
        $m = @(Get-CimInstance Win32_PhysicalMemory);
        $p.Count; ($p | Measure-Object NumberOfCores -Sum).Sum;
        ($p | Measure-Object L3CacheSize -Sum).Sum;
        $m.Count; [long]($m | Measure-Object Capacity -Sum).Sum; "end""#;
    let Some(v) = cim_lines(script, 6) else {
        return;
    };
    let t = cpu::topology();
    assert_eq!(t.packages.len(), number(&v[0]));
    assert_eq!(t.cores.len(), number(&v[1]));
    let logical: usize = t.cores.iter().map(|c| c.logical.len()).sum();
    assert_eq!(logical, cpu::logical());
    assert!(t.packages.iter().all(|p| !p.cores.is_empty()));
    let first = cpu::caches().first().expect("every CPU reports a cache");
    assert_eq!(first.level, 1);
    assert_ne!(cpu::cache_line(), 0);
    // Hypervisors under CI report what they like for this class.
    if std::env::var_os("CI").is_none() {
        let l3: u64 = cpu::caches()
            .iter()
            .filter(|c| c.level == 3 && c.kind == CacheKind::Unified)
            .map(|c| c.size.raw())
            .sum();
        let cim = v[2].parse::<u64>().unwrap() * 1024;
        if cim != 0 {
            assert_eq!(l3, cim, "level 3 cache");
        }
    }
    let modules = mem::modules().unwrap();
    assert_eq!(modules.len(), number(&v[3]));
    let total: u64 = modules.iter().map(|m| m.size.raw()).sum();
    assert_eq!(total, v[4].parse::<u64>().unwrap(), "installed memory");
}

#[cfg(windows)]
#[test]
fn test_live_windows_disks_match_cim() {
    use sys_lib::disk::{self, DiskKind};
    let script = r#"$d = $env:SystemDrive.TrimEnd(':');
        "$((Get-Partition -DriveLetter $d | Get-Disk | Get-PhysicalDisk).MediaType)"; "end""#;
    let Some(v) = cim_lines(script, 2) else {
        return;
    };
    let drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".to_owned());
    let root = format!("{drive}\\");
    let windows = disk::of(format!("{root}Windows")).unwrap();
    assert_eq!(windows.mount_point.to_str(), Some(root.as_str()));
    assert!(windows.device.eq_ignore_ascii_case(&drive));
    assert!(disk::list().unwrap().contains(&windows));
    match v[0].as_str() {
        "SSD" => assert_eq!(windows.kind, DiskKind::Ssd),
        "HDD" => assert_eq!(windows.kind, DiskKind::Hdd),
        _ => {}
    }
    // A junction: the disk of what it leads to, here the same volume.
    let link = std::env::temp_dir().join(format!("sys-lib-live-link-{}", std::process::id()));
    let target = std::env::temp_dir();
    let (link_text, target_text) = (link.display().to_string(), target.display().to_string());
    let made = tool("cmd", &["/c", "mklink", "/J", &link_text, &target_text]).is_some();
    if made {
        let through = disk::of(&link);
        let _ = std::fs::remove_dir(&link);
        assert_eq!(through.unwrap().device, disk::of(&target).unwrap().device);
    }
    assert!(disk::of(format!("{root}definitely-not-here")).is_err_and(|e| e.is_unavailable()));
}

#[cfg(windows)]
#[test]
fn test_live_windows_network_matches_cim() {
    use std::net::IpAddr;

    use sys_lib::net;
    let script = r#"$up = @(Get-NetIPInterface -ConnectionState Connected | ForEach-Object InterfaceIndex | Sort-Object -Unique);
        $s = @(Get-DnsClientServerAddress | Where-Object { $up -contains $_.InterfaceIndex } | ForEach-Object ServerAddresses | Sort-Object -Unique);
        $r = @(Get-NetRoute -DestinationPrefix 0.0.0.0/0 -ErrorAction SilentlyContinue | ForEach-Object ifIndex);
        "$($s -join ' ')"; "$($r -join ' ')"; "end""#;
    let Some(v) = cim_lines(script, 3) else {
        return;
    };
    let site_local = "fec0:0:0:ffff::";
    let mut cim: Vec<IpAddr> = v[0]
        .split_whitespace()
        .filter(|s| !s.starts_with(site_local))
        .map(|s| s.split('%').next().unwrap().parse().unwrap())
        .collect();
    cim.sort_unstable();
    cim.dedup();
    let mut ours = net::dns().unwrap().servers;
    ours.sort_unstable();
    assert_eq!(ours, cim, "DNS servers");

    let routes: Vec<u32> = v[1]
        .split_whitespace()
        .map(|s| s.parse().unwrap())
        .collect();
    match net::primary().unwrap() {
        Some(i) => assert!(routes.contains(&i.index), "{} not in {routes:?}", i.index),
        None => assert!(routes.is_empty(), "{routes:?}"),
    }
}

#[cfg(windows)]
#[test]
fn test_live_windows_zone_locale_power_and_sessions_match_dotnet_and_cim() {
    use sys_lib::power;
    let script = r#"$z = [TimeZoneInfo]::Local;
        $z.Id; [long]$z.GetUtcOffset([DateTime]::UtcNow).TotalSeconds; (Get-Culture).Name;
        @(Get-CimInstance Win32_Battery).Count; "end""#;
    let Some(v) = cim_lines(script, 5) else {
        return;
    };
    let tz = host::timezone().unwrap();
    assert_eq!(tz.windows.as_deref(), Some(v[0].as_str()));
    assert_eq!(
        i64::from(tz.utc_offset_seconds),
        v[1].parse::<i64>().unwrap()
    );
    assert!(tz.iana.is_some(), "{} is in the zone table", v[0]);
    if !v[2].is_empty() {
        assert_eq!(host::locale().map(|l| l.tag), Some(v[2].as_str()));
    }
    assert_eq!(power::has_battery(), number(&v[3]) > 0);
    assert_eq!(host::clock_sync().unwrap(), None);
    // `quser` exits non-zero with nobody logged in, and Home editions lack it.
    if let Some(out) = tool("quser", &[]) {
        let ours = host::sessions().unwrap();
        for line in out.lines().skip(1) {
            let user = line
                .trim_start_matches(['>', ' '])
                .split_whitespace()
                .next();
            let user = user.unwrap();
            assert!(
                ours.iter().any(|s| s.user.eq_ignore_ascii_case(user)),
                "{user} missing from {} sessions",
                ours.len()
            );
        }
    }
}

#[cfg(all(windows, feature = "device-id"))]
#[test]
fn test_live_windows_device_sources_are_read() {
    use sys_lib::device::{self, Anchor, SourceState};
    let r = device::report();
    let state = |anchor| {
        r.sources
            .iter()
            .find(|s| s.anchor == anchor)
            .map(|s| s.state)
    };
    // Windows always has a MachineGuid, and SMBIOS needs no privilege.
    assert_eq!(state(Anchor::InstallId), Some(SourceState::Present));
    assert!(r.default_basis_available);
    assert!(matches!(
        state(Anchor::PlatformUuid),
        Some(SourceState::Present | SourceState::Placeholder)
    ));
    assert!(device::id("com.hivedb.sys-lib.live").is_ok());
}

#[test]
fn test_live_samplers_measure_real_activity() {
    use std::time::Duration;
    // This process burns CPU for 100 ms: its sampler sees most of one core.
    let mut cpu = process::CpuSampler::new().unwrap();
    let start = std::time::Instant::now();
    let mut x = 1u64;
    while start.elapsed() < Duration::from_millis(100) {
        x = x.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
    }
    std::hint::black_box(x);
    let u = cpu.sample().unwrap();
    assert!(
        u.of_one_core > 30.0,
        "a busy loop used {:.1}% of a core",
        u.of_one_core
    );
    // Writing and syncing a file shows up as this process's storage writes
    // where the OS counts them per process.
    let before = process::io().ok();
    let path = std::env::temp_dir().join(format!("sys-lib-live-io-{}", std::process::id()));
    std::fs::write(&path, vec![7u8; 4 << 20]).unwrap();
    std::fs::OpenOptions::new()
        .write(true)
        .open(&path)
        .unwrap()
        .sync_all()
        .unwrap();
    let after = process::io().ok();
    let _ = std::fs::remove_file(&path);
    if let (Some(b), Some(a)) = (before, after) {
        assert!((a - b).written.raw() > 0 || !a.storage_only || cfg!(target_os = "macos"));
    }
}

#[test]
fn test_live_counts_are_consistent_everywhere() {
    assert!(cpu::logical() >= 1);
    assert!((1..=cpu::logical()).contains(&cpu::available()));
    assert!((1..=cpu::logical()).contains(&cpu::physical()));
    assert_ne!(cpu::is_64bit(), cpu::is_32bit());
    assert!(!os::name().is_empty() && !os::distro().is_empty() && !os::distro_id().is_empty());
    assert_eq!(process::id(), std::process::id());
}

#[cfg(target_os = "linux")]
#[test]
fn test_live_linux_detection_matches_the_tools() {
    use sys_lib::{cpu, disk, host, net, virt};
    if let Some(offset) = need("date", &["+%z"]) {
        // "+0100" is 3600 seconds east.
        let t = offset.trim();
        let sign = if t.starts_with('-') { -1 } else { 1 };
        let (hours, minutes): (i32, i32) = (t[1..3].parse().unwrap(), t[3..5].parse().unwrap());
        assert_eq!(
            host::timezone().unwrap().utc_offset_seconds,
            sign * (hours * 3600 + minutes * 60)
        );
    }
    if let Some(line) = need("getconf", &["LEVEL1_DCACHE_LINESIZE"])
        && let Ok(line) = line.trim().parse::<usize>()
        && line != 0
    {
        assert_eq!(cpu::cache_line(), line);
    }
    let root = disk::of("/").unwrap();
    assert_eq!(root.mount_point, std::path::Path::new("/"));
    assert!(root.space.is_some());
    assert_eq!(cpu::native_arch(), cpu::arch());
    assert!(!cpu::is_translated());
    if let Some(route) = need("ip", &["route", "show", "default"])
        && let Some(dev) = route.split_whitespace().skip_while(|w| *w != "dev").nth(1)
    {
        assert_eq!(
            net::primary().unwrap().map(|i| i.name).as_deref(),
            Some(dev)
        );
    }
    if let Ok(release) = std::fs::read_to_string("/proc/sys/kernel/osrelease") {
        assert_eq!(virt::is_wsl(), release.to_lowercase().contains("microsoft"));
    }
    assert_eq!(
        cpu::topology()
            .cores
            .iter()
            .map(|c| c.logical.len())
            .sum::<usize>(),
        cpu::logical()
    );
}