ktstr/test_support/
mod.rs

1//! Runtime support for `#[ktstr_test]` integration tests.
2//!
3//! Provides the registration type, distributed slice, VM launcher,
4//! and result evaluation. Includes guest-side profraw flush for
5//! coverage-instrumented builds.
6//!
7//! The entry point for test authors is the [`macro@crate::ktstr_test`]
8//! attribute macro; see the user-facing Writing Tests guide shipped
9//! with the crate's mdbook for end-to-end examples and the full
10//! attribute grammar.
11//!
12//! # Consumer API
13//!
14//! Test authors interact primarily with the `#[ktstr_test]` proc
15//! macro; programmatic test generation can instead populate
16//! [`KtstrTestEntry`] values into the [`KTSTR_TESTS`]
17//! `linkme` distributed slice. The remaining items in this module
18//! are runtime glue invoked by the macro-generated code and the
19//! `ktstr` / `cargo-ktstr` binaries.
20//!
21//! # Module layout
22//!
23//! Implementation is split across 19 production submodules
24//! re-exported at `test_support::*` for a flat public API: `args`
25//! (CLI argument extraction), `dispatch` (ktstr / cargo-ktstr CLI
26//! entry points), `entry` (scheduler + test-entry types),
27//! `entry_validate` (`KtstrTestEntry::validate` + phase helpers split
28//! out of `entry.rs`), `eval`
29//! (host-side VM result evaluation), `host_class` (shared
30//! host-insufficiency error classification), `metrics` (payload stdout →
31//! `Metric` list), `output`
32//! (guest-output and console parsing), `payload` (`Payload` /
33//! `MetricCheck` / `Metric` / `Polarity`), `probe` (auto-repro and
34//! BPF probe pipeline), `probe_metrics` (host-side BPF map
35//! introspection), `profraw` (coverage flush), `runtime` (`pub mod`
36//! — neutral home for verbose/shm-size/config-file-parts shared by
37//! eval and probe so they don't circularly depend on each other),
38//! `shell_descriptor` (wire-format struct shared between the test
39//! binary's `--ktstr-shell-test=<NAME>` producer and cargo-ktstr's
40//! shell-mode consumer), `wprof` (`#[cfg(feature = "wprof")]` —
41//! Perfetto-trace wire constants + `.wprof.pb` shape assertions),
42//! `sidecar` (per-run JSON records), `staged`
43//! (`pub(crate) mod` — staged-payload writer), `timefmt` (ISO-8601
44//! + run-id helpers), and `topo` (topology override parsing).
45//!
46//! A `#[cfg(test)] pub(crate) mod test_helpers` exists for cross-file
47//! test wiring; it is not part of the production surface.
48
49#[cfg(test)]
50use crate::assert::AssertResult;
51#[cfg(test)]
52use crate::scenario::Ctx;
53#[cfg(test)]
54use anyhow::Result;
55
56mod admission_stamp;
57mod args;
58#[doc(hidden)]
59pub use admission_stamp::{
60    AdmissionCellDescriptor, AdmissionCellKind, AdmissionMode, AdmissionTestKeyV3,
61    AdmissionTestStampV3, AdmissionTopologyDescriptor, KTSTR_ADMISSION_TEST_KEYS_V3,
62    KTSTR_ADMISSION_TESTS_V3, read_admission_cell_stamp,
63};
64// Re-exported for the workload-side CgroupChurn worker, which resolves the
65// same workload cgroup root the host-side setup uses but lives outside the
66// private `args` module's subtree.
67pub(crate) use args::resolve_cgroup_root;
68mod boot_retry;
69// Shared by the guest (rust_init formats the AP-gap panic around the
70// marker) and the host cell layer (verifier + eval retry the whole boot
71// when a run's crash_message carries it).
72#[cfg(target_arch = "x86_64")]
73pub(crate) use boot_retry::guest_kernel_rejected_wide_apic;
74pub(crate) use boot_retry::{AP_BRINGUP_GAP_MARKER, run_vm_with_ap_gap_retry};
75mod dispatch;
76mod entry;
77mod entry_validate;
78mod eval;
79mod host_class;
80mod metrics;
81mod output;
82#[doc(hidden)]
83pub use output::strip_ansi_csi;
84// Reachable crate-wide (vmm::VmResult::guest_assert_result parses the guest
85// AssertResult from its own drained guest_messages via this helper, mirroring
86// the eval-layer use). The fn itself is pub(crate); this just lifts it out of
87// the private `output` module so the vmm layer can call it by a stable path.
88pub(crate) use output::parse_assert_result_from_drain;
89mod payload;
90mod probe;
91// Reachable crate-wide so the freeze coordinator can detect the guest's
92// probe-payload end delimiter in the drained bulk-port stdout stream and
93// hold teardown until Phase 6b has shipped (see freeze_coord's wprof-ship
94// kill gating). The const itself is pub(crate); this lifts it out of the
95// private `probe` module onto a stable `test_support::` path.
96pub(crate) use probe::PROBE_OUTPUT_END;
97mod probe_metrics;
98mod profraw;
99pub(crate) use eval::FrameworkInfrastructureFailure;
100pub use eval::{
101    capture_starvation_witness, periodic_starvation_gate, post_vm_skip, stall_ejection_skip,
102    starved_below_minimum_skip,
103};
104pub use profraw::current_binary_is_coverage_instrumented;
105pub mod runtime;
106mod scheduler_manifest_stamp;
107#[doc(hidden)]
108pub use scheduler_manifest_stamp::{
109    KTSTR_SCHEDULER_MANIFEST_DECLARATIONS_V1, KTSTR_SCHEDULER_MANIFEST_TESTS_V1,
110    SchedulerManifestDeclarationStampV1, SchedulerManifestStampSliceV1,
111    SchedulerManifestStampStrV1, SchedulerManifestStampSysctlV1, SchedulerManifestTestStampV1,
112    SchedulerManifestUseStampV1, read_scheduler_manifest_stamp,
113};
114
115/// Read scheduler discovery metadata and validate the admission wire-format
116/// envelope through one ELF mapping.
117///
118/// Cargo invokes this once per warmed binary. This path checks versions,
119/// section/header shape, registry counts, and compact-key integrity without
120/// decoding every topology payload. The target runner subsequently performs
121/// strict exact-name lookup and fully decodes the selected cell before it
122/// acquires resources or executes the test binary.
123#[doc(hidden)]
124pub fn read_scheduler_manifest_and_validate_admission_stamp(
125    path: &std::path::Path,
126) -> std::result::Result<Option<SchedulerManifestProbe>, String> {
127    let file = std::fs::File::open(path).map_err(|error| {
128        format!(
129            "open warmed test binary {} for ktstr metadata: {error}",
130            path.display(),
131        )
132    })?;
133    // SAFETY: the map is read-only, the file stays alive through construction,
134    // and the returned mapping owns its VMA.
135    let data = unsafe { memmap2::MmapOptions::new().map(&file) }.map_err(|error| {
136        format!(
137            "map warmed test binary {} for ktstr metadata: {error}",
138            path.display(),
139        )
140    })?;
141    scheduler_manifest_stamp::advise_sparse_elf(&data);
142    let reader = scheduler_manifest_stamp::ElfStampReader::new(path, &data)?;
143    let manifest = scheduler_manifest_stamp::read_scheduler_manifest_stamp_reader(&reader)?;
144    admission_stamp::validate_admission_stamp_envelope_reader(&reader)?;
145    Ok(manifest)
146}
147mod shell_descriptor;
148pub use shell_descriptor::{SchedulerKind, ShellTestDescriptor};
149#[cfg(feature = "wprof")]
150pub mod wprof;
151#[cfg(feature = "wprof")]
152pub use wprof::{PERFETTO_TRACE_PACKETS_TAG, WPROF_PB_MIN_BYTES, assert_wprof_pb_shape};
153#[cfg(test)]
154pub(crate) mod btf_blob;
155mod sidecar;
156pub(crate) mod staged;
157#[cfg(test)]
158pub(crate) mod test_helpers;
159mod timefmt;
160mod topo;
161
162/// Shared callback signature for the
163/// [`KtstrTestEntry::post_vm`](entry::KtstrTestEntry::post_vm) and
164/// [`KtstrTestEntry::post_vm_unconditional`](entry::KtstrTestEntry::post_vm_unconditional)
165/// host-side hooks. Both fields wrap this same shape in `Option<_>`;
166/// the alias collapses the open-coded `fn(&crate::vmm::VmResult)
167/// -> anyhow::Result<()>` repetition at the field declarations and
168/// at the matching `with_post_vm{,_unconditional}` builder
169/// parameters. Future post-VM hooks (e.g. an `expect_auto_repro`
170/// artifact-existence checker) plug into the same shape without
171/// triplicating the signature.
172pub type PostVmCallback = fn(&crate::vmm::VmResult) -> anyhow::Result<()>;
173
174// extract_probe_stack_arg and extract_work_type_arg are reached in
175// production via `super::args::` (probe.rs); the re-export here
176// preserves the flat-namespace invariant so `test_support::X` resolves
177// uniformly across all CLI arg extractors.
178#[cfg(feature = "export")]
179pub(crate) use args::extract_export_output_arg;
180#[allow(unused_imports)]
181pub(crate) use args::{
182    CellParentCgroupArg, VERIFIER_WORKLOAD_FLAG, cell_parent_path_is_valid,
183    extract_export_check_test_arg, extract_export_test_arg, extract_probe_stack_arg,
184    extract_shell_test_arg, extract_test_fn_arg, extract_topo_arg, extract_work_type_arg,
185    is_verifier_workload, parse_cell_parent_cgroup, parse_line_framed_args,
186};
187#[allow(unused_imports)]
188pub(crate) use runtime::{append_base_sched_args, content_hash, scratch_dir, sys_rdy_budget_ms};
189#[cfg(test)]
190pub(crate) use sidecar::enriched_parse_error_message_for_test;
191pub use sidecar::{
192    PerfDeltaAssertionRecord, SidecarResult, ThroughputDenomination, collect_pool,
193    detect_kernel_commit, detect_project_commit, format_run_artifact_footer,
194    kernel_commit_for_resolved, newest_run_dir, repo_is_dirty, runs_root, sidecar_dir,
195    source_dir_for,
196};
197pub(crate) use sidecar::{
198    SidecarIoError, SidecarParseError, apply_archive_source_override, collect_sidecars,
199    collect_sidecars_with_errors, format_callback_profile, format_kvm_stats, format_verifier_stats,
200    is_run_directory, is_sidecar_filename, warn_skipped_sidecars,
201};
202
203pub use dispatch::{
204    DEFAULT_HOST_CGROUP_PARENT, EXIT_FAIL, EXIT_INCONCLUSIVE, EXIT_PASS, analyze_sidecars,
205    is_cpu_budget_unsatisfiable, is_kernel_unavailable, is_perf_mode_unavailable,
206    is_resource_contention, is_topology_insufficient, is_topology_unrepresentable, ktstr_main,
207    ktstr_test_early_dispatch, resolve_host_cgroup_parent, run_ktstr_test, sanitize_kernel_label,
208};
209pub use entry::{
210    BinaryKindJson, BpfMapAgg, BpfMapWrite, CgroupPath, KTSTR_SCHEDULERS, KTSTR_TESTS,
211    KtstrTestEntry, MemSideCache, NumaDistance, NumaNode, PerfDeltaAssertion,
212    SCHEDULER_MANIFEST_PROBE_ARG, Scheduler, SchedulerArtifactRequirement, SchedulerJson,
213    SchedulerListEntry, SchedulerManifestProbe, SchedulerSpec, SchedulerTestJson, Sysctl,
214    SysctlJson, Topology, TopologyConstraints, TopologyConstraintsJson, TopologyJson, WatchBpfMap,
215    default_post_vm_periodic_fired, find_scheduler, find_test, runtime_manifest_dir,
216};
217pub use eval::{KernelUnavailable, ResolveSource, resolve_scheduler, resolve_test_kernel};
218pub(crate) use eval::{record_skip_sidecar, run_ktstr_test_inner};
219pub(crate) use host_class::host_skip_class;
220pub use host_class::{HostClass, classify_host_error};
221
222/// True when an error is a ktstr framework/CAS/COW infrastructure failure
223/// which must never be reinterpreted as host insufficiency or inverted by an
224/// `expect_err` test.
225///
226/// This hidden public predicate is consumed by proc-macro-generated libtest
227/// wrappers in downstream crates, where the private marker type itself cannot
228/// be named.
229#[doc(hidden)]
230pub fn is_framework_infrastructure_failure(error: &anyhow::Error) -> bool {
231    error
232        .downcast_ref::<eval::FrameworkInfrastructureFailure>()
233        .is_some()
234}
235pub use metrics::{
236    MAX_WALK_DEPTH, WALK_TRUNCATION_SENTINEL_NAME, extract_metrics, is_truncation_sentinel_name,
237    walk_json_leaves,
238};
239pub(crate) use output::extract_panic_message;
240pub use payload::{
241    Metric, MetricCheck, MetricHint, MetricStream, OutputFormat, Payload, PayloadKind,
242    PayloadMetrics, Polarity,
243};
244pub(crate) use probe::maybe_dispatch_vm_test;
245pub(crate) use probe::{
246    PROBE_DRAIN_GRACE, ProbePhaseAState, finalize_probe_after_unwind,
247    maybe_dispatch_vm_test_with_args, maybe_dispatch_vm_test_with_phase_a,
248    propagate_rust_env_from_cmdline, start_probe_phase_a,
249};
250pub use probe_metrics::{
251    MAX_SCAN_INDEX, ThreadLookup, count_indexed_metrics, find_metric, find_metric_u64,
252    flat_metrics_dump, has_metric, lookup_thread, snapshot_count, snapshot_worker_allocated,
253    thread_count,
254};
255pub use profraw::target_dir as profraw_target_dir;
256pub(crate) use profraw::{find_symbol_vaddrs, persist_guest_profraw, try_flush_profraw};
257pub(crate) use timefmt::now_iso8601;
258pub(crate) use topo::{TopoOverride, parse_topo_string};
259
260/// Host capacity triple `(cpus, llcs, max_cpus_per_llc)` used to
261/// filter gauntlet topology presets against what the host can actually
262/// schedule. Both `dispatch::list_tests_*` (gauntlet variant filter)
263/// and `dispatch::list_verifier_cells_all` (verifier sweep filter)
264/// share this single source of truth so the two filters never drift.
265/// Reads `available_parallelism()` for CPU count + `HostTopology::from_sysfs()`
266/// for LLC layout; falls back to single-LLC + single-cpu-per-llc when
267/// sysfs is unavailable.
268pub fn host_capacity() -> (u32, u32, u32) {
269    let host_cpus = std::thread::available_parallelism()
270        .map(|n| n.get() as u32)
271        .unwrap_or(1);
272    let host_topo = crate::vmm::host_topology::HostTopology::from_sysfs().ok();
273    let host_llcs = host_topo
274        .as_ref()
275        .map(|t| t.llc_groups.len() as u32)
276        .unwrap_or(1);
277    let host_max_cpus_per_llc = host_topo
278        .as_ref()
279        .map(|t| t.max_cores_per_llc() as u32)
280        .unwrap_or(host_cpus);
281    (host_cpus, host_llcs, host_max_cpus_per_llc)
282}
283
284// ---------------------------------------------------------------------------
285// Test infrastructure requirements
286// ---------------------------------------------------------------------------
287//
288// `require_*` helpers turn missing test infrastructure into a panic with
289// an actionable message instead of a silent skip. Use them when a test
290// is meaningless without the resource -- a missing kernel, vmlinux,
291// scheduler binary, or kernel-symbol resolution means the harness is
292// misconfigured, not that the test should pass quietly. CI silently
293// passing 100 "tests" that all early-returned because no kernel was
294// findable is the failure mode these helpers exist to prevent.
295//
296// For genuine skips (raw BTF at /sys/kernel/btf/vmlinux, host without
297// the architectural dependency the test exercises), call the crate's
298// `skip!("reason: {detail}")` macro (see `src/test_macros.rs`). It
299// emits the canonical `ktstr: SKIP: ...` line and returns from the
300// test.
301
302/// Whether the current test process was launched by a cargo-ktstr
303/// orchestration path (`cargo ktstr test`, `cargo ktstr verifier`)
304/// vs. a raw `cargo nextest run` / `cargo test`.
305///
306/// Reads [`crate::KTSTR_ORCHESTRATED_ENV`]; only checks presence,
307/// not value (cargo-ktstr always sets it to `"1"`, but the marker
308/// semantics are presence-only). Returns `false` when the env var
309/// is unset or unreadable.
310///
311/// Tests that boot real KVM VMs use this to skip when running
312/// under raw nextest, where the 7000+-test concurrency starves
313/// per-VM resource budgets and produces a misleading "kill set by
314/// AP" failure that looks like a real bug. cargo-ktstr's
315/// orchestrator constrains the VM-test concurrency so the budgets
316/// hold; skipping under raw nextest surfaces the operator-error
317/// (wrong runner) without masking real failures during proper
318/// orchestrated runs.
319///
320/// `pub(crate)` — only callers are integration-test helpers under
321/// `src/vmm/mod.rs`'s `#[cfg(test)]` mod. The env-var name itself
322/// is `pub` via [`crate::KTSTR_ORCHESTRATED_ENV`] for
323/// documentation purposes.
324#[cfg(test)]
325#[allow(dead_code)] // called from x86_64-only tests in vmm/mod.rs
326pub(crate) fn cargo_ktstr_orchestrated() -> bool {
327    std::env::var(crate::KTSTR_ORCHESTRATED_ENV).is_ok()
328}
329
330/// Skip-message body for vmm-boot tests that bail when the test
331/// process wasn't launched by cargo-ktstr orchestration. The
332/// canonical extended rationale lives inline at the
333/// `boot_kernel_with_monitor` site; sibling sites reference back
334/// to it via this shared const so a future message tweak lands in
335/// one place instead of four. The 4 sibling sites previously
336/// carried byte-for-byte-identical copies of this string — per
337/// the no-mega-no-dupes policy the 3+-site threshold mandates a
338/// shared const.
339#[cfg(test)]
340#[allow(dead_code)] // referenced from x86_64-only vmm/mod.rs tests
341pub(crate) const SKIP_NOT_ORCHESTRATED_MSG: &str = "raw nextest fan-out starves KVM resource budgets — see \
342     boot_kernel_with_monitor for the shared rationale. Run via \
343     `cargo ktstr test --kernel ../linux`.";
344
345#[cfg(test)]
346mod cargo_ktstr_orchestrated_tests {
347    //! Pin the env-var-presence detection contract. A regression
348    //! that renamed [`crate::KTSTR_ORCHESTRATED_ENV`] silently
349    //! would make every vmm-test skip even under cargo-ktstr
350    //! orchestration (where the env IS set), turning the
351    //! VM-boot test suite into an always-green no-op. Pin the
352    //! two-arm contract (set → true, unset → false) so the rename
353    //! surfaces here.
354    use super::cargo_ktstr_orchestrated;
355    use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
356    #[test]
357    fn cargo_ktstr_orchestrated_true_when_env_set() {
358        let _lock = lock_env();
359        let _guard = EnvVarGuard::set(crate::KTSTR_ORCHESTRATED_ENV, "1");
360        assert!(
361            cargo_ktstr_orchestrated(),
362            "KTSTR_ORCHESTRATED set → orchestrated check must return true"
363        );
364    }
365    #[test]
366    fn cargo_ktstr_orchestrated_false_when_env_unset() {
367        let _lock = lock_env();
368        let _guard = EnvVarGuard::remove(crate::KTSTR_ORCHESTRATED_ENV);
369        assert!(
370            !cargo_ktstr_orchestrated(),
371            "KTSTR_ORCHESTRATED absent → orchestrated check must return false \
372             (otherwise raw nextest invocations would run vmm tests and \
373             starve KVM resource budgets)"
374        );
375    }
376}
377
378/// Resolve a kernel image path or panic with an actionable message.
379///
380/// Wraps [`crate::find_kernel`]: an `Err` (KTSTR_KERNEL points at a
381/// path with no kernel image, cache lookup failed) and a successful
382/// `Ok(None)` (no kernel discoverable) both panic. Tests that boot a
383/// VM cannot proceed without a kernel; silently skipping turns CI
384/// breakage into a green run.
385#[cfg(test)]
386#[allow(dead_code)] // called from x86_64-only tests in vmm/mod.rs
387pub(crate) fn require_kernel() -> std::path::PathBuf {
388    match crate::find_kernel() {
389        Ok(Some(p)) => p,
390        Ok(None) => panic!(
391            "ktstr_test: test requires a kernel but none was found. {}",
392            crate::KTSTR_KERNEL_HINT
393        ),
394        Err(e) => panic!("ktstr_test: kernel resolution failed: {e:#}"),
395    }
396}
397
398/// Resolve a vmlinux path next to a kernel image or panic.
399///
400/// `kernel_path` is the value returned by [`require_kernel`]. The
401/// vmlinux is required for symbol address lookup, BTF, and probe
402/// source resolution -- a kernel image without vmlinux means the
403/// cache entry is corrupt or the build was incomplete, which is an
404/// infrastructure failure rather than a legitimate skip.
405#[cfg(test)]
406#[allow(dead_code)] // called from x86_64-only tests in vmm/mod.rs
407pub(crate) fn require_vmlinux(kernel_path: &std::path::Path) -> std::path::PathBuf {
408    crate::vmm::find_vmlinux(kernel_path).unwrap_or_else(|| {
409        panic!(
410            "ktstr_test: no vmlinux found alongside {}. The cache entry or \
411             kernel build is incomplete. Rebuild with `cargo ktstr kernel \
412             build --force`; the specified kernel must include `vmlinux` \
413             alongside the boot image. {}",
414            kernel_path.display(),
415            crate::KTSTR_KERNEL_HINT,
416        )
417    })
418}
419
420/// Build a workspace package and return its binary path, or panic.
421///
422/// Wraps [`crate::build_and_find_binary`]. A failed build or missing
423/// artifact for a required scheduler binary (e.g. `scx-ktstr`) is an
424/// infrastructure failure -- the workspace is broken, not the test.
425#[cfg(test)]
426pub(crate) fn require_binary(package: &str) -> std::path::PathBuf {
427    crate::build_and_find_binary(package, env!("CARGO_MANIFEST_DIR")).unwrap_or_else(|e| {
428        panic!(
429            "ktstr_test: build of `{package}` failed: {e:#}. \
430             Run `cargo build -p {package}` to reproduce and diagnose."
431        )
432    })
433}
434
435/// Resolve [`crate::monitor::symbols::KernelSymbols`] from a vmlinux
436/// or panic. The symbol table is required for any host-side memory
437/// introspection; an unparseable vmlinux is an infrastructure failure.
438#[cfg(test)]
439#[allow(dead_code)] // called from x86_64-only tests in vmm/mod.rs
440pub(crate) fn require_kernel_symbols(
441    vmlinux_path: &std::path::Path,
442) -> crate::monitor::symbols::KernelSymbols {
443    crate::monitor::symbols::KernelSymbols::from_vmlinux(vmlinux_path).unwrap_or_else(|e| {
444        panic!(
445            "ktstr_test: kernel symbol resolution from {} failed: {e:#}",
446            vmlinux_path.display(),
447        )
448    })
449}
450
451/// Resolve [`crate::monitor::btf_offsets::KernelOffsets`] from a vmlinux
452/// or panic. BTF resolution is required for any host-side kernel
453/// struct introspection; a vmlinux whose BTF fails to parse is an
454/// infrastructure failure, not a test-skip condition.
455#[cfg(test)]
456pub(crate) fn require_kernel_offsets(
457    vmlinux_path: &std::path::Path,
458) -> crate::monitor::btf_offsets::KernelOffsets {
459    crate::monitor::btf_offsets::KernelOffsets::from_vmlinux(vmlinux_path).unwrap_or_else(|e| {
460        panic!(
461            "ktstr_test: kernel BTF resolution from {} failed: {e:#}. \
462             The kernel must be built with CONFIG_DEBUG_INFO_BTF=y; \
463             rebuild with `cargo ktstr kernel build --force` if the \
464             cache entry was produced without BTF.",
465            vmlinux_path.display(),
466        )
467    })
468}
469
470/// Resolve [`crate::monitor::btf_offsets::BpfMapOffsets`] from a vmlinux
471/// or panic. A vmlinux whose BTF fails to yield BPF map offsets is an
472/// infrastructure failure, not a test-skip condition.
473#[cfg(test)]
474pub(crate) fn require_bpf_map_offsets(
475    vmlinux_path: &std::path::Path,
476) -> crate::monitor::btf_offsets::BpfMapOffsets {
477    crate::monitor::btf_offsets::BpfMapOffsets::from_vmlinux(vmlinux_path).unwrap_or_else(|e| {
478        panic!(
479            "ktstr_test: BpfMapOffsets resolution from {} failed: {e:#}. \
480             The kernel must be built with CONFIG_DEBUG_INFO_BTF=y; \
481             rebuild with `cargo ktstr kernel build --force` if the \
482             cache entry was produced without BTF.",
483            vmlinux_path.display(),
484        )
485    })
486}
487
488/// Resolve [`crate::monitor::btf_offsets::BpfProgOffsets`] from a vmlinux
489/// or panic. A vmlinux whose BTF fails to yield BPF program offsets is
490/// an infrastructure failure, not a test-skip condition.
491#[cfg(test)]
492pub(crate) fn require_bpf_prog_offsets(
493    vmlinux_path: &std::path::Path,
494) -> crate::monitor::btf_offsets::BpfProgOffsets {
495    crate::monitor::btf_offsets::BpfProgOffsets::from_vmlinux(vmlinux_path).unwrap_or_else(|e| {
496        panic!(
497            "ktstr_test: BpfProgOffsets resolution from {} failed: {e:#}. \
498             The kernel must be built with CONFIG_DEBUG_INFO_BTF=y; \
499             rebuild with `cargo ktstr kernel build --force` if the \
500             cache entry was produced without BTF.",
501            vmlinux_path.display(),
502        )
503    })
504}
505
506#[cfg(test)]
507mod tests {
508    use super::*;
509    use crate::ktstr_test;
510
511    // Register a test entry in the distributed slice for unit testing find_test.
512    fn __ktstr_inner_unit_test_dummy(_ctx: &Ctx) -> Result<AssertResult> {
513        Ok(AssertResult::pass())
514    }
515
516    #[crate::ktstr_test_entry]
517    static __KTSTR_ENTRY_UNIT_TEST_DUMMY: KtstrTestEntry = KtstrTestEntry {
518        name: "__unit_test_dummy__",
519        func: __ktstr_inner_unit_test_dummy,
520        ..KtstrTestEntry::DEFAULT
521    };
522
523    #[test]
524    fn find_test_registered_entry() {
525        let entry = find_test("__unit_test_dummy__");
526        assert!(entry.is_some(), "registered entry should be found");
527        let entry = entry.unwrap();
528        assert_eq!(entry.name, "__unit_test_dummy__");
529        assert_eq!(entry.topology.llcs, 1);
530        assert_eq!(entry.topology.cores_per_llc, 2);
531    }
532
533    #[test]
534    fn find_test_nonexistent() {
535        assert!(find_test("__nonexistent_test_xyz__").is_none());
536    }
537
538    #[test]
539    fn find_test_from_distributed_slice() {
540        // KTSTR_TESTS should contain at least the __unit_test_dummy__ entry.
541        assert!(!KTSTR_TESTS.is_empty());
542    }
543
544    // Macro-codegen coverage for the cpu_budget attr: drive the real
545    // #[ktstr_test] expansion (the parse arm + the Some(n)/None field-emit
546    // arms) and assert the emitted KtstrTestEntry carries the right
547    // cpu_budget. host_only keeps the probe from booting a VM; no_perf_mode
548    // satisfies the macro's cpu_budget-requires-no_perf_mode gate. find_test
549    // reads the registered entry from KTSTR_TESTS without invoking the body.
550    // This RUNS in CI (a src/ #[cfg(test)] unit test), unlike the
551    // ktstr-macros crate's own suite which cargo-ktstr does not discover.
552    #[ktstr_test(cpu_budget = 7, host_only, no_perf_mode)]
553    fn cpu_budget_codegen_probe(_ctx: &Ctx) -> Result<AssertResult> {
554        Ok(AssertResult::pass())
555    }
556
557    #[ktstr_test(host_only)]
558    fn cpu_budget_codegen_probe_none(_ctx: &Ctx) -> Result<AssertResult> {
559        Ok(AssertResult::pass())
560    }
561
562    #[test]
563    fn cpu_budget_attr_emits_some() {
564        let e = find_test("cpu_budget_codegen_probe")
565            .expect("the cpu_budget probe entry must be registered");
566        assert_eq!(
567            e.cpu_budget,
568            Some(7),
569            "#[ktstr_test(cpu_budget = 7)] must emit cpu_budget: Some(7)"
570        );
571    }
572
573    #[test]
574    fn omitted_cpu_budget_defaults_none() {
575        let e = find_test("cpu_budget_codegen_probe_none")
576            .expect("the no-cpu_budget probe entry must be registered");
577        assert_eq!(
578            e.cpu_budget, None,
579            "omitting cpu_budget must leave the DEFAULT None (no field emitted)"
580        );
581    }
582}