ktstr/cli/kernel_build/
kconfig.rs

1//! kconfig fragment merging, validation, and post-build probing.
2//!
3//! Holds the helpers that compose, parse, and validate the kernel
4//! configuration:
5//! - [`configure_kernel`] runs `make defconfig` (when no `.config`
6//!   exists), checks the merged fragment is present, appends and
7//!   re-runs `olddefconfig` only when needed.
8//! - [`all_fragment_lines_present`] / [`is_kconfig_semantic_line`]
9//!   gate the no-op short-circuit so a clean `.config` doesn't
10//!   churn the configure pass.
11//! - [`read_extra_kconfig`] parses the user's `--extra-kconfig PATH`
12//!   into the fragment string with actionable error wording per
13//!   I/O failure mode.
14//! - [`append_extra_kconfig_suffix`] composes the cache-key suffix
15//!   so the extras-aware build lands at a distinct cache slot.
16//! - [`warn_extra_kconfig_overrides_baked_in`] /
17//!   [`warn_dropped_extra_kconfig_lines`] surface user/baked-in
18//!   conflicts and silent olddefconfig drops respectively.
19//! - [`parse_kconfig_symbol`] / [`render_kconfig_value`] are the
20//!   shared primitives behind those warning passes.
21//! - [`validate_kernel_config`] is the post-build critical-option
22//!   pass.
23
24use std::path::Path;
25
26use anyhow::{Context, Result, bail};
27
28use super::super::kernel_cmd::EMBEDDED_KCONFIG;
29use super::make::{MAKE_POLL_INTERVAL, MAKE_TIMEOUT, run_make_captured};
30
31/// Ensure the kconfig fragment is applied to the kernel's .config.
32///
33/// Creates a default .config via `make defconfig` if none exists.
34/// Pure check used by [`configure_kernel`]: every non-empty line of
35/// `fragment` (including disable directives like
36/// `# CONFIG_X is not set`) must appear as an exact line of `config`.
37///
38/// Exact-line matching avoids the prefix-aliasing hazard of the prior
39/// `config.contains(fragment_line)` formulation, where a fragment line
40/// false-matches when it appears as a substring of an unrelated
41/// `.config` line — e.g. fragment `CONFIG_NR_CPUS=1` appearing inside
42/// `CONFIG_NR_CPUS=128`, or any numeric-tail option where the
43/// requested value is a prefix of the existing value.
44///
45/// `# CONFIG_X is not set` comments ARE kconfig semantics (the
46/// canonical way to disable an option), so they participate in the
47/// check.
48///
49/// Free-text comments (`#` lines that are NOT the
50/// `# CONFIG_X is not set` form, e.g. `# Build for testing scx`)
51/// are dropped before the probe: kbuild emits its own header into
52/// `.config` and strips user-added free-text comments, so a fragment
53/// containing decorative `#` lines would always fail this check and
54/// trigger a redundant `make olddefconfig` re-resolve on every
55/// configure pass.
56///
57/// Genuinely empty lines are also skipped.
58pub(super) fn all_fragment_lines_present(fragment: &str, config: &str) -> bool {
59    let existing: std::collections::HashSet<&str> = config.lines().map(str::trim).collect();
60    fragment
61        .lines()
62        .map(str::trim)
63        .filter(|t| is_kconfig_semantic_line(t))
64        .all(|t| existing.contains(t))
65}
66
67/// True for lines that participate in kconfig semantics — i.e.
68/// `CONFIG_X=...` assignments and the `# CONFIG_X is not set`
69/// disable-directive form. Empty lines and free-text `#` comments
70/// return false.
71///
72/// Drives [`all_fragment_lines_present`]'s filter so a fragment with
73/// decorative comments doesn't churn the configure pass on every
74/// rebuild. The disable-directive form is a kconfig sentinel kbuild
75/// emits into `.config` as the canonical way to record a disabled
76/// `tristate`/`bool` symbol; it survives `make olddefconfig` and
77/// must participate in the present-in-config check.
78pub(super) fn is_kconfig_semantic_line(trimmed: &str) -> bool {
79    if trimmed.is_empty() {
80        return false;
81    }
82    if let Some(rest) = trimmed.strip_prefix('#') {
83        // `# CONFIG_X is not set` — the disable-directive sentinel
84        // kbuild writes verbatim into .config. Tolerant of internal
85        // whitespace variation by trimming the rest.
86        let rest = rest.trim_start();
87        return rest.starts_with("CONFIG_") && rest.ends_with(" is not set");
88    }
89    // Non-comment, non-empty line: a CONFIG_X=... assignment or
90    // similar. The probe defers semantic validity to the existing
91    // hash-set match against the on-disk `.config`.
92    true
93}
94
95/// Read a `--extra-kconfig PATH` file. Returns `Ok(content)` on
96/// success or `Err(message)` with an actionable diagnostic naming
97/// `--extra-kconfig` and the user's literal input path verbatim so
98/// a typo names the exact string they passed.
99///
100/// Four distinguishing arms each produce an actionable message:
101/// - `ENOENT` (not-found) → tells the operator to verify the path
102///   spelling and that the file exists
103/// - `EISDIR` (is-a-directory) → tells the operator to pass a regular
104///   file rather than a directory
105/// - `EACCES` (permission-denied) → tells the operator to check file
106///   ownership and mode
107/// - empty file (zero-byte read success) → emits a `tracing::warn!`
108///   explaining the cache-slot consequence and pointing at the likely
109///   operator intent (a non-empty fragment), then proceeds
110///
111/// Other I/O errors fall through with the OS error rendered verbatim
112/// (`--extra-kconfig {path}: {os error}`). A non-UTF-8 file errors
113/// with a message identifying the constraint (kconfig fragments are
114/// ASCII text).
115///
116/// Symlinks resolve transparently (`std::fs::read` opens through
117/// `open(2)` which follows symlinks per kernel default).
118pub fn read_extra_kconfig(path: &Path, cli_label: &str) -> std::result::Result<String, String> {
119    let display = path.display();
120    let bytes = match std::fs::read(path) {
121        Ok(b) => b,
122        Err(e) => {
123            let msg = match e.kind() {
124                std::io::ErrorKind::NotFound => {
125                    format!(
126                        "--extra-kconfig {display}: file not found; check the \
127                         path spelling and that the file exists"
128                    )
129                }
130                std::io::ErrorKind::IsADirectory => {
131                    format!(
132                        "--extra-kconfig {display}: is a directory; pass a \
133                         regular file containing kconfig fragment lines"
134                    )
135                }
136                std::io::ErrorKind::PermissionDenied => {
137                    format!(
138                        "--extra-kconfig {display}: permission denied; check \
139                         file ownership and mode (the kconfig fragment must \
140                         be readable by the current user)"
141                    )
142                }
143                _ => format!("--extra-kconfig {display}: {e}"),
144            };
145            return Err(msg);
146        }
147    };
148
149    // Empty file: warn but proceed. The build still lands at a
150    // distinct cache slot via the `-xkc{hash_of_empty}` segment, but
151    // no user symbols merge — the operator likely meant to populate
152    // the file with `CONFIG_X=...` lines.
153    if bytes.is_empty() {
154        let path_str = display.to_string();
155        tracing::warn!(
156            cli_label = cli_label,
157            path = %path_str,
158            "--extra-kconfig file is empty; the build will land at a \
159             distinct cache slot but no user symbols will merge into the \
160             configuration. Did you mean to populate {path_str} with \
161             CONFIG_X=... lines?",
162        );
163    }
164
165    String::from_utf8(bytes).map_err(|_| {
166        format!(
167            "--extra-kconfig {display}: file is not valid UTF-8; kconfig \
168             fragments must be ASCII text"
169        )
170    })
171}
172
173/// Append the `-xkc{extra_hash}` segment to a cache key built around
174/// the bare baked-in suffix (`...-kc{baked_hash}`), bringing it to the
175/// two-segment shape produced by [`crate::cache_key_suffix_with_extra`].
176///
177/// `local_source` and `git_clone` populate `acquired.cache_key` against
178/// the bare [`crate::cache_key_suffix`] which carries only the baked-in
179/// hash. With `--extra-kconfig` set, the cache lookup and the
180/// post-build store must target the extras-aware slot — this helper
181/// performs the plain string append so both binaries share one merge
182/// path. Plain append (vs rewriting the suffix) preserves the upstream
183/// key prefix exactly and is robust to any future shape change in the
184/// head segments. No-op when `extra` is `None`.
185pub fn append_extra_kconfig_suffix(cache_key: &mut String, extra: Option<&str>) {
186    if let Some(content) = extra {
187        cache_key.push_str("-xkc");
188        cache_key.push_str(&crate::extra_kconfig_hash(content));
189    }
190}
191
192/// Pre-configure pass that warns when a user `--extra-kconfig` line
193/// overrides a baked-in symbol from `EMBEDDED_KCONFIG`. The build
194/// proceeds with the user value winning (per kbuild's last-wins
195/// rule and the design intent of `--extra-kconfig`); this helper
196/// just surfaces the override so the operator sees that their
197/// fragment is shadowing a baked-in setting.
198///
199/// Output shape:
200/// `--extra-kconfig overrides baked-in CONFIG_FOO (was =y, now =n)`
201/// where the "was"/"now" values are extracted from the matching
202/// lines on each side. `# CONFIG_X is not set` (kbuild's disable
203/// directive) is normalized to "is not set" in the rendered
204/// before/after for readability.
205///
206/// Free-text `#`-comments and blank lines in the user fragment are
207/// skipped — only `CONFIG_X=...` assignments and `# CONFIG_X is
208/// not set` directives count as overrides.
209pub(super) fn warn_extra_kconfig_overrides_baked_in(extra: &str, cli_label: &str) {
210    // Build a per-symbol map of the baked-in declarations once.
211    // `EMBEDDED_KCONFIG` is small (~370 lines per ktstr.kconfig)
212    // so a single pass is cheap.
213    let mut baked: std::collections::HashMap<&str, &str> = std::collections::HashMap::new();
214    for raw in EMBEDDED_KCONFIG.lines() {
215        let line = raw.trim();
216        if let Some(sym) = parse_kconfig_symbol(line) {
217            baked.insert(sym, line);
218        }
219    }
220
221    for raw in extra.lines() {
222        let line = raw.trim();
223        let Some(user_sym) = parse_kconfig_symbol(line) else {
224            continue;
225        };
226        let Some(baked_line) = baked.get(user_sym) else {
227            continue;
228        };
229        if *baked_line == line {
230            continue;
231        }
232        tracing::warn!(
233            cli_label = cli_label,
234            symbol = user_sym,
235            was = *baked_line,
236            now = line,
237            "--extra-kconfig overrides baked-in {user_sym} (was {}, now {})",
238            render_kconfig_value(baked_line, user_sym),
239            render_kconfig_value(line, user_sym),
240        );
241    }
242}
243
244/// Extract the symbol name from a kbuild `.config`-shaped line.
245///
246/// Returns `Some("CONFIG_FOO")` for `CONFIG_FOO=...` or
247/// `# CONFIG_FOO is not set`, `None` for anything else (free-text
248/// comments, blank lines, malformed input).
249pub(super) fn parse_kconfig_symbol(line: &str) -> Option<&str> {
250    if let Some(rest) = line.strip_prefix("# ")
251        && let Some(sym) = rest.strip_suffix(" is not set")
252        && sym.starts_with("CONFIG_")
253    {
254        return Some(sym);
255    }
256    if line.starts_with("CONFIG_")
257        && let Some((sym, _)) = line.split_once('=')
258    {
259        return Some(sym);
260    }
261    None
262}
263
264/// Render the value half of a `.config` line for the override
265/// warning's `(was =y, now =n)` formatting. For an assignment
266/// line `CONFIG_FOO=y`, returns `=y`. For a disable directive
267/// `# CONFIG_FOO is not set`, returns `is not set`. Falls back to
268/// the full line when the shape is unrecognized so the operator
269/// still gets information.
270pub(super) fn render_kconfig_value<'a>(line: &'a str, sym: &str) -> &'a str {
271    if let Some(value) = line.strip_prefix(sym)
272        && value.starts_with('=')
273    {
274        return value;
275    }
276    if line == format!("# {sym} is not set") {
277        return "is not set";
278    }
279    line
280}
281
282/// Post-`olddefconfig` validation pass for `--extra-kconfig` lines.
283///
284/// Scan the user's `extra` fragment line-by-line and verify each
285/// non-empty, non-comment line either appears verbatim in the final
286/// `.config` or matches the is-not-set sentinel for a
287/// missing-from-output symbol (which kbuild renders as
288/// `# CONFIG_X is not set` or simply omits). When a user line was
289/// silently dropped by olddefconfig (typically because of an unmet
290/// dependency), emit a `tracing::warn!` naming the requested setting
291/// and the actual `.config` state — operator gets the diagnostic
292/// without the build failing.
293///
294/// Best-effort: a missing or unreadable `.config` collapses to
295/// silent return, since the surrounding pipeline failure would be
296/// the actionable signal in those cases.
297///
298/// Lines starting with `#` that are NOT the kbuild
299/// `# CONFIG_X is not set` form are treated as free-text comments
300/// and skipped — they exist in user fragments but have no
301/// `.config` counterpart.
302pub(super) fn warn_dropped_extra_kconfig_lines(kernel_dir: &Path, extra: &str, cli_label: &str) {
303    let config_path = kernel_dir.join(".config");
304    let Ok(final_config) = std::fs::read_to_string(&config_path) else {
305        return;
306    };
307    let final_lines: std::collections::HashSet<&str> =
308        final_config.lines().map(str::trim).collect();
309
310    for raw_line in extra.lines() {
311        let line = raw_line.trim();
312        if line.is_empty() {
313            continue;
314        }
315        // Skip free-text comments — `# foo bar baz`. The kbuild
316        // disable form `# CONFIG_X is not set` is a special-case
317        // comment that participates in `.config` and IS checked.
318        let is_disable_directive = line.starts_with("# CONFIG_") && line.ends_with(" is not set");
319        let is_assignment = line.starts_with("CONFIG_") && line.contains('=');
320        if !is_disable_directive && !is_assignment {
321            continue;
322        }
323        if final_lines.contains(line) {
324            continue;
325        }
326        // Line missing — either dropped by olddefconfig or rewritten
327        // (e.g. `=y` → `is not set` because dep didn't resolve).
328        // Look up the symbol's actual final value to enrich the
329        // warning. Symbol name is everything up to `=` (assignment)
330        // or between `# ` and ` is not set` (disable directive).
331        let sym_name = if is_assignment {
332            line.split('=').next().unwrap_or(line)
333        } else {
334            line.trim_start_matches("# ")
335                .trim_end_matches(" is not set")
336        };
337        let final_state = final_config
338            .lines()
339            .find(|l| {
340                let t = l.trim();
341                t.starts_with(&format!("{sym_name}=")) || t == format!("# {sym_name} is not set")
342            })
343            .map(str::trim)
344            .unwrap_or(
345                "(absent — symbol not present in .config; likely \
346                        disabled or unrecognized by kconfig)",
347            );
348        tracing::warn!(
349            cli_label = cli_label,
350            requested = line,
351            final_state = final_state,
352            "--extra-kconfig line did not survive `make olddefconfig` (likely an \
353             unmet dependency or unrecognized symbol)"
354        );
355    }
356}
357
358/// Checks each non-empty line of the fragment against the current
359/// `.config` via `all_fragment_lines_present`. If every fragment
360/// line already appears in `.config`, the file is not touched
361/// (preserving mtime for make's dependency tracking). If any are
362/// missing, appends the full fragment and runs `make olddefconfig`
363/// to resolve new options with defaults — without this, the
364/// subsequent `make` launches interactive `conf` prompts that hang
365/// when stdout/stderr are piped.
366///
367/// The `defconfig` / `olddefconfig` invocations run through
368/// `run_make_captured` rather than [`super::make::run_make`]: this
369/// step runs under a live "Configuring kernel..." spinner, so their
370/// output is captured (and replayed only on failure) instead of
371/// raw-inherited, which would clobber the spinner. `progress` is
372/// `Some` under the spinner (failure replay lands above the bars) and
373/// `None` in tests.
374pub(crate) fn configure_kernel(
375    kernel_dir: &Path,
376    fragment: &str,
377    progress: Option<&crate::cli::FetchProgress>,
378) -> Result<()> {
379    let config_path = kernel_dir.join(".config");
380    if !config_path.exists() {
381        run_make_captured(
382            kernel_dir,
383            &["defconfig"],
384            progress,
385            MAKE_TIMEOUT,
386            MAKE_POLL_INTERVAL,
387        )?;
388    }
389
390    let config_content = std::fs::read_to_string(&config_path)?;
391    if all_fragment_lines_present(fragment, &config_content) {
392        return Ok(());
393    }
394
395    let mut config = std::fs::OpenOptions::new()
396        .append(true)
397        .open(&config_path)?;
398    std::io::Write::write_all(&mut config, fragment.as_bytes())?;
399
400    run_make_captured(
401        kernel_dir,
402        &["olddefconfig"],
403        progress,
404        MAKE_TIMEOUT,
405        MAKE_POLL_INTERVAL,
406    )?;
407
408    Ok(())
409}
410
411/// Critical `.config` options checked by [`validate_kernel_config`].
412///
413/// Each entry pairs a `CONFIG_X` name with a diagnostic hint —
414/// human-readable context on the dependency that typically causes the
415/// option to be silently dropped during `make`. The list is curated:
416/// every entry here is an option whose absence at the post-build
417/// check has historically surfaced as a specific tool-install or
418/// arch-default-override. The companion test
419/// `critical_options_are_in_embedded_kconfig` proves every name is
420/// present in [`EMBEDDED_KCONFIG`] as `=y`, so a kconfig edit that
421/// removes a critical entry fails the test immediately instead of
422/// surfacing later as a build that passes validation but behaves
423/// differently.
424const VALIDATE_CONFIG_CRITICAL: &[(&str, &str)] = &[
425    (
426        "CONFIG_SCHED_CLASS_EXT",
427        "depends on CONFIG_DEBUG_INFO_BTF — ensure pahole >= 1.16 is installed (dwarves package)",
428    ),
429    (
430        "CONFIG_DEBUG_INFO_BTF",
431        "requires pahole >= 1.16 (dwarves package)",
432    ),
433    ("CONFIG_BPF_SYSCALL", "required for BPF program loading"),
434    (
435        "CONFIG_FTRACE",
436        "gate for all tracing infrastructure — arm64 defconfig disables it, \
437         silently dropping KPROBE_EVENTS and BPF_EVENTS",
438    ),
439    (
440        "CONFIG_KPROBE_EVENTS",
441        "required for ktstr probe pipeline (depends on FTRACE + KPROBES)",
442    ),
443    (
444        "CONFIG_BPF_EVENTS",
445        "required for BPF kprobe/tracepoint attachment (depends on KPROBE_EVENTS + PERF_EVENTS)",
446    ),
447    (
448        "CONFIG_VIRTIO_BLK",
449        "required for ktstr DiskConfig — backs /dev/vd* in the guest. Depends on VIRTIO + BLOCK; \
450         a user --extra-kconfig that strips BLOCK would silently disable this and disk-IO WorkTypes \
451         would fail with a confusing 'no /dev/vda' inside the guest instead of a clear build error",
452    ),
453    (
454        "CONFIG_ACPI",
455        "the linchpin of the x86 PCI transport — the guest parses the MCFG (ECAM base), the \
456         _SB.PCI0 DSDT _PRT (PCI INTx -> GSI routing), and the FADT PM register blocks only when \
457         ACPI is enabled. x86_64 defconfig sets it, but an --extra-kconfig that strips it would \
458         drop PCI_MMCONFIG too (default-y only on PCI + ACPI) and PCI INTx would fall back to \
459         legacy MP-table routing with no NIC entry — the exact silent failure the FADT PM blocks \
460         + _PRT exist to fix. Validated here (not only via PCI_MMCONFIG) because it is the most \
461         catastrophic to lose",
462    ),
463    (
464        "CONFIG_PCI",
465        "required for the virtio-PCI transport — the host bridge at 00:00.0 and any PCI device \
466         (NICs) enumerate only with PCI compiled in. x86_64 defconfig sets it, but an \
467         --extra-kconfig that strips it would silently leave the guest with no /sys/bus/pci and \
468         every PCI device invisible instead of a clear build error",
469    ),
470    (
471        "CONFIG_VIRTIO_PCI",
472        "the guest virtio-PCI DRIVER that binds the virtio-net NIC (a PCI function). Without it \
473         the guest enumerates the PCI device but no driver attaches, so eth* never appears and \
474         every NIC WorkType/e2e fails with a confusing 'no eth0' inside the guest instead of a \
475         clear build error. Distinct from CONFIG_PCI (the bus) and CONFIG_VIRTIO_NET (the \
476         transport-agnostic net driver)",
477    ),
478];
479
480/// Critical `.config` options that exist only in `arch/x86` Kconfig, so they are
481/// required only when cargo-ktstr targets x86_64 (which builds an x86_64 kernel).
482///
483/// `CONFIG_PCI_MMCONFIG` (x86 MMCONFIG-based ECAM, `arch/x86/Kconfig`) has no
484/// arm64 counterpart — arm64 ECAM is `PCI_HOST_GENERIC` — so on an arm64 build
485/// `make` drops the unknown symbol and validating it would be a guaranteed false
486/// failure. `ktstr.kconfig` still requests it as `=y` (a no-op on arm64).
487#[cfg(target_arch = "x86_64")]
488const VALIDATE_CONFIG_CRITICAL_X86: &[(&str, &str)] = &[(
489    "CONFIG_PCI_MMCONFIG",
490    "backs ECAM (extended config space, reg >= 256) which the MCFG table and _SB.PCI0 DSDT \
491     window describe and the PCI enumeration e2e exercises (a host-bridge-class device is \
492     sized to 4096-byte config and read at reg 0x100 via ECAM). default-y on x86_64 when \
493     PCI + ACPI are set, but an --extra-kconfig that strips it would silently drop ECAM — \
494     base config still works over CAM, so the loss is invisible until an extended-config \
495     access (the e2e, or a future MSI-X device) fails",
496)];
497
498/// The critical `.config` options to validate for the arch that cargo-ktstr targets:
499/// the arch-neutral [`VALIDATE_CONFIG_CRITICAL`] plus, on x86_64, the x86-only
500/// [`VALIDATE_CONFIG_CRITICAL_X86`]. Single source of truth for both the
501/// post-build check and its tests, so the two never drift.
502///
503/// `pub(crate)` so the distro-kernel config gate
504/// ([`crate::distro::acquire`]) reuses the same option/hint list rather
505/// than duplicating it — a prebuilt distro kernel that lacks one of
506/// these ktstr-feature options warns with the identical hint the build
507/// path would have hard-failed with.
508pub(crate) fn critical_config_options() -> Vec<(&'static str, &'static str)> {
509    #[cfg_attr(not(target_arch = "x86_64"), allow(unused_mut))]
510    let mut opts = VALIDATE_CONFIG_CRITICAL.to_vec();
511    #[cfg(target_arch = "x86_64")]
512    opts.extend_from_slice(VALIDATE_CONFIG_CRITICAL_X86);
513    opts
514}
515
516/// Validate the output .config for critical options that the kconfig
517/// fragment requested but the kernel build system may have silently
518/// disabled (e.g. CONFIG_DEBUG_INFO_BTF requires pahole).
519///
520/// Call after `make` succeeds. Returns `Err` with a diagnostic
521/// message listing missing options and likely causes.
522pub fn validate_kernel_config(kernel_dir: &std::path::Path) -> Result<()> {
523    let config_path = kernel_dir.join(".config");
524    let config = std::fs::read_to_string(&config_path)
525        .with_context(|| format!("read {}", config_path.display()))?;
526
527    // Build a HashSet of trimmed `.config` lines once, then probe
528    // each critical option in O(1). The previous formulation
529    // walked `config.lines()` once per critical option (O(N×M)
530    // with M≈11 critical options (10 arch-neutral + 1 x86-only)
531    // and N≈5000 .config lines), which turned every kernel-build
532    // pipeline into a ~55K-line scan.
533    // Trimming each line matches `all_fragment_lines_present`'s
534    // configure-time behavior so the same `.config` parses
535    // identically across both checks — without trim, a
536    // configure-time write that produced trailing whitespace (or
537    // a `.config` edited by hand on a Windows host with `\r\n`
538    // line endings) would silently flag every critical option as
539    // missing here while passing the configure-time check.
540    let existing: std::collections::HashSet<&str> = config.lines().map(str::trim).collect();
541
542    let mut missing = Vec::new();
543    let critical = critical_config_options();
544    for &(option, hint) in &critical {
545        let enabled = format!("{option}=y");
546        if !existing.contains(enabled.as_str()) {
547            missing.push((option, hint));
548        }
549    }
550
551    if !missing.is_empty() {
552        let mut msg =
553            String::from("kernel build completed but critical config options are missing:\n");
554        for (option, hint) in &missing {
555            msg.push_str(&format!("  {option} not set — {hint}\n"));
556        }
557        msg.push_str(
558            "\nThe kernel build system silently disables options whose dependencies \
559             are not met. Install missing tools and rebuild with --force.",
560        );
561        bail!("{msg}");
562    }
563    Ok(())
564}
565
566#[cfg(test)]
567mod tests {
568    use super::*;
569
570    // -- validate_kernel_config --
571
572    /// Every entry in `VALIDATE_CONFIG_CRITICAL` must appear as `=y`
573    /// in the embedded kconfig fragment. If a critical option is
574    /// dropped from the fragment, builds skip it but validation
575    /// keeps flagging it as missing — the user sees a build failure
576    /// no tool install fixes. This test catches the drift at
577    /// compile-test time.
578    #[test]
579    fn critical_options_are_in_embedded_kconfig() {
580        let fragment = crate::EMBEDDED_KCONFIG;
581        for &(option, _) in &critical_config_options() {
582            let enabled = format!("{option}=y");
583            assert!(
584                fragment.lines().any(|l| l.trim() == enabled),
585                "VALIDATE_CONFIG_CRITICAL lists {option:?} but ktstr.kconfig does not \
586                 enable it; either add `{option}=y` to the fragment or drop the entry \
587                 from VALIDATE_CONFIG_CRITICAL",
588            );
589        }
590    }
591
592    #[test]
593    fn validate_kernel_config_all_present() {
594        let dir = tempfile::TempDir::new().unwrap();
595        // Every critical option present => validation passes. Generated from
596        // VALIDATE_CONFIG_CRITICAL (not a hand-picked subset) so the test stays
597        // complete as the critical list grows.
598        let content: String = critical_config_options()
599            .iter()
600            .map(|(option, _)| format!("{option}=y\n"))
601            .collect();
602        std::fs::write(dir.path().join(".config"), content).unwrap();
603        assert!(validate_kernel_config(dir.path()).is_ok());
604    }
605
606    #[test]
607    fn validate_kernel_config_missing_btf() {
608        let dir = tempfile::TempDir::new().unwrap();
609        std::fs::write(
610            dir.path().join(".config"),
611            "CONFIG_SCHED_CLASS_EXT=y\n\
612             CONFIG_BPF_SYSCALL=y\n\
613             CONFIG_FTRACE=y\n\
614             CONFIG_KPROBE_EVENTS=y\n\
615             CONFIG_BPF_EVENTS=y\n",
616        )
617        .unwrap();
618        let err = validate_kernel_config(dir.path()).unwrap_err();
619        let msg = format!("{err}");
620        assert!(msg.contains("CONFIG_DEBUG_INFO_BTF"), "got: {msg}");
621    }
622
623    #[test]
624    fn validate_kernel_config_missing_multiple() {
625        let dir = tempfile::TempDir::new().unwrap();
626        std::fs::write(dir.path().join(".config"), "CONFIG_BPF_SYSCALL=y\n").unwrap();
627        let err = validate_kernel_config(dir.path()).unwrap_err();
628        let msg = format!("{err}");
629        assert!(msg.contains("CONFIG_SCHED_CLASS_EXT"), "got: {msg}");
630        assert!(msg.contains("CONFIG_DEBUG_INFO_BTF"), "got: {msg}");
631    }
632
633    #[test]
634    fn validate_kernel_config_no_config_file() {
635        let dir = tempfile::TempDir::new().unwrap();
636        assert!(validate_kernel_config(dir.path()).is_err());
637    }
638
639    /// Pin the per-line `str::trim` semantics in
640    /// [`validate_kernel_config`]. CRLF line endings (`\r\n` from a
641    /// Windows-edited file) and trailing-space lines must STILL
642    /// validate when the option-after-trim equals the expected
643    /// `CONFIG_X=y` form. A regression that dropped `.map(str::trim)`
644    /// would surface every option as missing.
645    #[test]
646    fn validate_kernel_config_trim_handles_crlf_and_trailing_whitespace() {
647        let dir = tempfile::TempDir::new().unwrap();
648        // Write EVERY critical option as `=y`, alternating dirty line endings
649        // (`\r\n`) and trailing spaces so each required line needs trimming to
650        // be recognized. Generated from VALIDATE_CONFIG_CRITICAL (not a
651        // hand-picked subset) so the test stays complete — and keeps testing
652        // trim on the whole set — as the critical list grows.
653        let mut content = String::new();
654        let critical = critical_config_options();
655        for (i, (option, _)) in critical.iter().enumerate() {
656            if i % 2 == 0 {
657                content.push_str(&format!("{option}=y\r\n")); // CRLF
658            } else {
659                content.push_str(&format!("{option}=y \n")); // trailing space
660            }
661        }
662        std::fs::write(dir.path().join(".config"), content).unwrap();
663        let result = validate_kernel_config(dir.path());
664        assert!(
665            result.is_ok(),
666            "validate_kernel_config must trim per-line whitespace \
667             before the HashSet probe; got: {result:?}",
668        );
669    }
670
671    // -- parse_kconfig_symbol + render_kconfig_value --
672
673    #[test]
674    fn parse_kconfig_symbol_assignment() {
675        assert_eq!(parse_kconfig_symbol("CONFIG_FOO=y"), Some("CONFIG_FOO"));
676        assert_eq!(parse_kconfig_symbol("CONFIG_FOO=m"), Some("CONFIG_FOO"));
677        assert_eq!(parse_kconfig_symbol("CONFIG_FOO=n"), Some("CONFIG_FOO"));
678        assert_eq!(
679            parse_kconfig_symbol("CONFIG_BAR=\"value\""),
680            Some("CONFIG_BAR")
681        );
682    }
683
684    #[test]
685    fn parse_kconfig_symbol_disable_directive() {
686        assert_eq!(
687            parse_kconfig_symbol("# CONFIG_FOO is not set"),
688            Some("CONFIG_FOO")
689        );
690    }
691
692    #[test]
693    fn parse_kconfig_symbol_rejects_free_text_comment() {
694        assert!(parse_kconfig_symbol("# user note about foo").is_none());
695        assert!(parse_kconfig_symbol("#").is_none());
696        assert!(parse_kconfig_symbol("# this is a doc line").is_none());
697    }
698
699    #[test]
700    fn parse_kconfig_symbol_rejects_blank_and_non_config() {
701        assert!(parse_kconfig_symbol("").is_none());
702        assert!(parse_kconfig_symbol("not a kconfig line").is_none());
703        assert!(parse_kconfig_symbol("FOO=y").is_none());
704    }
705
706    #[test]
707    fn render_kconfig_value_assignment_returns_value_with_equals() {
708        assert_eq!(render_kconfig_value("CONFIG_FOO=y", "CONFIG_FOO"), "=y");
709        assert_eq!(render_kconfig_value("CONFIG_FOO=n", "CONFIG_FOO"), "=n");
710        assert_eq!(
711            render_kconfig_value("CONFIG_BAR=\"value\"", "CONFIG_BAR"),
712            "=\"value\""
713        );
714    }
715
716    #[test]
717    fn render_kconfig_value_disable_returns_is_not_set() {
718        assert_eq!(
719            render_kconfig_value("# CONFIG_FOO is not set", "CONFIG_FOO"),
720            "is not set"
721        );
722    }
723
724    #[test]
725    fn render_kconfig_value_falls_back_to_full_line_on_unknown_shape() {
726        let s = "CONFIG_FOO without equals";
727        assert_eq!(render_kconfig_value(s, "CONFIG_FOO"), s);
728    }
729
730    // -- warn_extra_kconfig_overrides_baked_in --
731    //
732    // The function's only observable behavior is the `tracing::warn!`
733    // it emits when a user line overrides a baked-in symbol. Each
734    // test installs a capturing subscriber via `traced_test` and
735    // asserts on the rendered warning (or its absence) — a no-panic
736    // assertion would not catch a dropped emit, a mis-rendered
737    // was/now value, or a spurious warning. Mirrors
738    // `vmm::rust_init::tests::send_sys_rdy_retry_exits_when_budget_exhausted`.
739
740    /// CONFIG_BPF is baked in as `=y` (ktstr.kconfig); a
741    /// `# CONFIG_BPF is not set` user line is an actual override and
742    /// must fire the WARN naming the symbol and rendering the
743    /// before/after values (`=y` → `is not set`).
744    #[test]
745    #[tracing_test::traced_test]
746    fn warn_extra_kconfig_overrides_emits_on_actual_override() {
747        assert!(
748            EMBEDDED_KCONFIG.lines().any(|l| l.trim() == "CONFIG_BPF=y"),
749            "fixture invariant: CONFIG_BPF must be baked in as =y",
750        );
751        let user = "# CONFIG_BPF is not set\n";
752        warn_extra_kconfig_overrides_baked_in(user, "test");
753        assert!(
754            logs_contain("overrides baked-in CONFIG_BPF"),
755            "override of a baked-in symbol must emit the WARN naming it",
756        );
757        // Rendered before/after tokens: baked `=y`, user `is not set`.
758        assert!(
759            logs_contain("(was =y, now is not set)"),
760            "WARN must render the baked before-value and the user after-value",
761        );
762        // Structured fields rendered into the line.
763        for field in [
764            "symbol=\"CONFIG_BPF\"",
765            "was=\"CONFIG_BPF=y\"",
766            "now=\"# CONFIG_BPF is not set\"",
767            "cli_label=\"test\"",
768        ] {
769            assert!(
770                logs_contain(field),
771                "WARN must include structured field `{field}`",
772            );
773        }
774    }
775
776    #[test]
777    #[tracing_test::traced_test]
778    fn warn_extra_kconfig_overrides_silent_on_empty_fragment() {
779        warn_extra_kconfig_overrides_baked_in("", "test");
780        assert!(
781            !logs_contain("overrides baked-in"),
782            "an empty fragment overrides nothing — no WARN",
783        );
784    }
785
786    #[test]
787    #[tracing_test::traced_test]
788    fn warn_extra_kconfig_overrides_silent_on_novel_symbol() {
789        let novel = "CONFIG_KTSTR_TEST_NOVEL_SYMBOL_OVERRIDE_TEST=y\n";
790        assert!(
791            !EMBEDDED_KCONFIG.contains("CONFIG_KTSTR_TEST_NOVEL_SYMBOL_OVERRIDE_TEST"),
792            "test fixture must use a symbol absent from EMBEDDED_KCONFIG"
793        );
794        warn_extra_kconfig_overrides_baked_in(novel, "test");
795        assert!(
796            !logs_contain("overrides baked-in"),
797            "a symbol not present in EMBEDDED_KCONFIG overrides nothing — no WARN",
798        );
799    }
800
801    /// `CONFIG_BPF=y` matches the baked-in line byte-for-byte, so the
802    /// `*baked_line == line` guard suppresses the WARN. A regression
803    /// that warned on an identical value would surface here.
804    #[test]
805    #[tracing_test::traced_test]
806    fn warn_extra_kconfig_overrides_silent_on_matching_assignment() {
807        assert!(
808            EMBEDDED_KCONFIG.lines().any(|l| l.trim() == "CONFIG_BPF=y"),
809            "fixture invariant: CONFIG_BPF must be baked in as =y",
810        );
811        let user = "CONFIG_BPF=y\n";
812        warn_extra_kconfig_overrides_baked_in(user, "test");
813        assert!(
814            !logs_contain("overrides baked-in"),
815            "a user line identical to the baked-in line is not an override — no WARN",
816        );
817    }
818
819    #[test]
820    #[tracing_test::traced_test]
821    fn warn_extra_kconfig_overrides_silent_on_free_text_comments() {
822        let user = "# this is a comment about something\n# another comment\n";
823        warn_extra_kconfig_overrides_baked_in(user, "test");
824        assert!(
825            !logs_contain("overrides baked-in"),
826            "free-text `#` comments are not kconfig assignments — no WARN",
827        );
828    }
829
830    // -- read_extra_kconfig --
831
832    #[test]
833    fn read_extra_kconfig_returns_content_for_valid_file() {
834        let dir = tempfile::TempDir::new().unwrap();
835        let path = dir.path().join("frag.kconfig");
836        let content = "CONFIG_FOO=y\nCONFIG_BAR=m\n";
837        std::fs::write(&path, content).unwrap();
838        let got = read_extra_kconfig(&path, "test").unwrap();
839        assert_eq!(got, content, "content must round-trip byte-for-byte");
840    }
841
842    #[test]
843    fn read_extra_kconfig_not_found_arm_names_path_and_intent() {
844        let dir = tempfile::TempDir::new().unwrap();
845        let missing = dir.path().join("does-not-exist.kconfig");
846        let display = missing.display().to_string();
847        let err = read_extra_kconfig(&missing, "cargo ktstr").expect_err("missing file must Err");
848        assert!(
849            err.contains(&display),
850            "ENOENT message must name the literal path: {err}"
851        );
852        assert!(
853            err.contains("--extra-kconfig"),
854            "ENOENT message must name the flag: {err}"
855        );
856        assert!(
857            err.contains("file not found"),
858            "ENOENT arm must surface a `file not found` token: {err}"
859        );
860    }
861
862    #[test]
863    fn read_extra_kconfig_directory_arm_distinguishes_from_not_found() {
864        let dir = tempfile::TempDir::new().unwrap();
865        let display = dir.path().display().to_string();
866        let err =
867            read_extra_kconfig(dir.path(), "cargo ktstr").expect_err("directory path must Err");
868        assert!(
869            err.contains(&display),
870            "EISDIR message must name the path: {err}"
871        );
872        assert!(
873            err.contains("is a directory"),
874            "EISDIR arm must surface its specific token: {err}"
875        );
876    }
877
878    #[test]
879    fn read_extra_kconfig_invalid_utf8_arm_names_constraint() {
880        let dir = tempfile::TempDir::new().unwrap();
881        let path = dir.path().join("binary.bin");
882        std::fs::write(&path, [0xFFu8, 0xFE, 0x00, 0x42]).unwrap();
883        let err = read_extra_kconfig(&path, "cargo ktstr").expect_err("non-UTF-8 file must Err");
884        assert!(
885            err.contains("not valid UTF-8"),
886            "UTF-8 arm must surface the constraint name: {err}"
887        );
888        assert!(
889            err.contains("ASCII text"),
890            "UTF-8 arm must mention the kconfig content constraint: {err}"
891        );
892    }
893
894    #[test]
895    fn read_extra_kconfig_empty_file_returns_empty_string() {
896        let dir = tempfile::TempDir::new().unwrap();
897        let path = dir.path().join("empty.kconfig");
898        std::fs::write(&path, "").unwrap();
899        let got = read_extra_kconfig(&path, "cargo ktstr").unwrap();
900        assert_eq!(
901            got, "",
902            "empty file must round-trip as empty String, not Err"
903        );
904    }
905
906    #[test]
907    #[cfg(unix)]
908    fn read_extra_kconfig_follows_symlink_chain() {
909        use std::os::unix::fs::symlink;
910        let dir = tempfile::TempDir::new().unwrap();
911        let target = dir.path().join("real.kconfig");
912        let link = dir.path().join("link.kconfig");
913        std::fs::write(&target, "CONFIG_BPF=y\n").unwrap();
914        symlink(&target, &link).unwrap();
915        let got = read_extra_kconfig(&link, "test").unwrap();
916        assert_eq!(
917            got, "CONFIG_BPF=y\n",
918            "symlink must resolve to target content"
919        );
920    }
921
922    // -- warn_dropped_extra_kconfig_lines --
923    //
924    // The function exists to emit a `tracing::warn!` when a requested
925    // `--extra-kconfig` line did not survive `make olddefconfig`. Each
926    // test installs a capturing subscriber via `traced_test` and
927    // asserts the WARN fires (with the enriched `final_state`) for the
928    // dropped/rewritten cases, and stays silent for the present /
929    // missing-config / free-text cases — a no-panic assertion would
930    // catch none of those regressions.
931
932    /// No `.config` on disk: the `read_to_string` Err arm returns
933    /// silently (best-effort), so no WARN even though the requested
934    /// line is "missing".
935    #[test]
936    #[tracing_test::traced_test]
937    fn warn_dropped_extra_kconfig_lines_silent_when_config_missing() {
938        let dir = tempfile::TempDir::new().unwrap();
939        let extra = "CONFIG_FOO=y\n";
940        warn_dropped_extra_kconfig_lines(dir.path(), extra, "test");
941        assert!(
942            !logs_contain("did not survive"),
943            "a missing .config collapses to a silent return — no WARN",
944        );
945    }
946
947    #[test]
948    #[tracing_test::traced_test]
949    fn warn_dropped_extra_kconfig_lines_silent_when_all_present() {
950        let dir = tempfile::TempDir::new().unwrap();
951        std::fs::write(dir.path().join(".config"), "CONFIG_FOO=y\nCONFIG_BAR=m\n").unwrap();
952        let extra = "CONFIG_FOO=y\nCONFIG_BAR=m\n";
953        warn_dropped_extra_kconfig_lines(dir.path(), extra, "test");
954        assert!(
955            !logs_contain("did not survive"),
956            "every requested line present verbatim in .config — no WARN",
957        );
958    }
959
960    /// A requested assignment whose symbol is entirely absent from the
961    /// final `.config` (dropped by olddefconfig) must fire the WARN
962    /// naming the requested line and the absent-symbol `final_state`
963    /// sentinel.
964    #[test]
965    #[tracing_test::traced_test]
966    fn warn_dropped_extra_kconfig_lines_emits_on_dropped_line() {
967        let dir = tempfile::TempDir::new().unwrap();
968        std::fs::write(dir.path().join(".config"), "CONFIG_BPF=y\n").unwrap();
969        let extra = "CONFIG_KTSTR_DROPPED_TEST_NOVEL=y\n";
970        warn_dropped_extra_kconfig_lines(dir.path(), extra, "test");
971        assert!(
972            logs_contain("did not survive"),
973            "a dropped requested line must emit the WARN",
974        );
975        assert!(
976            logs_contain("requested=\"CONFIG_KTSTR_DROPPED_TEST_NOVEL=y\""),
977            "WARN must carry the requested line",
978        );
979        // Absent symbol: `final_state` falls to the sentinel string.
980        assert!(
981            logs_contain("symbol not present in .config"),
982            "WARN's final_state must surface the absent-symbol sentinel",
983        );
984    }
985
986    /// A requested `=y` that olddefconfig rewrote to `is not set`
987    /// (unmet dependency) is "missing" from `.config` verbatim, so the
988    /// WARN fires with the rewritten `# CONFIG_X is not set` line as
989    /// the enriched `final_state`.
990    #[test]
991    #[tracing_test::traced_test]
992    fn warn_dropped_extra_kconfig_lines_emits_on_rewritten_line() {
993        let dir = tempfile::TempDir::new().unwrap();
994        std::fs::write(
995            dir.path().join(".config"),
996            "# CONFIG_KTSTR_REWRITE_TEST is not set\n",
997        )
998        .unwrap();
999        let extra = "CONFIG_KTSTR_REWRITE_TEST=y\n";
1000        warn_dropped_extra_kconfig_lines(dir.path(), extra, "test");
1001        assert!(
1002            logs_contain("did not survive"),
1003            "a rewritten requested line must emit the WARN",
1004        );
1005        assert!(
1006            logs_contain("requested=\"CONFIG_KTSTR_REWRITE_TEST=y\""),
1007            "WARN must carry the requested =y line",
1008        );
1009        // `final_state` enrichment: the actual rewritten .config line.
1010        assert!(
1011            logs_contain("final_state=\"# CONFIG_KTSTR_REWRITE_TEST is not set\""),
1012            "WARN must enrich final_state with the rewritten .config value",
1013        );
1014    }
1015
1016    /// A free-text `#` header is not a kconfig assignment nor a disable
1017    /// directive, so it is skipped; the lone real assignment is present
1018    /// — no WARN.
1019    #[test]
1020    #[tracing_test::traced_test]
1021    fn warn_dropped_extra_kconfig_lines_silent_on_free_text_comments() {
1022        let dir = tempfile::TempDir::new().unwrap();
1023        std::fs::write(dir.path().join(".config"), "CONFIG_BPF=y\n").unwrap();
1024        let extra = "# decorative header\nCONFIG_BPF=y\n";
1025        warn_dropped_extra_kconfig_lines(dir.path(), extra, "test");
1026        assert!(
1027            !logs_contain("did not survive"),
1028            "free-text comments are skipped and the assignment is present — no WARN",
1029        );
1030    }
1031
1032    // -- configure_kernel --
1033
1034    #[test]
1035    fn configure_kernel_appends_missing() {
1036        let dir = tempfile::TempDir::new().unwrap();
1037        std::fs::write(dir.path().join(".config"), "CONFIG_BPF=y\n").unwrap();
1038        std::fs::write(dir.path().join("Makefile"), "olddefconfig:\n\t@true\n").unwrap();
1039        let fragment = "CONFIG_EXTRA=y\n";
1040        configure_kernel(dir.path(), fragment, None).unwrap();
1041        let config = std::fs::read_to_string(dir.path().join(".config")).unwrap();
1042        assert!(config.contains("CONFIG_EXTRA=y"));
1043        assert!(config.contains("CONFIG_BPF=y"));
1044    }
1045
1046    #[test]
1047    fn configure_kernel_skips_when_present() {
1048        let dir = tempfile::TempDir::new().unwrap();
1049        let initial = "CONFIG_BPF=y\nCONFIG_EXTRA=y\n";
1050        std::fs::write(dir.path().join(".config"), initial).unwrap();
1051        let fragment = "CONFIG_EXTRA=y\n";
1052        configure_kernel(dir.path(), fragment, None).unwrap();
1053        let config = std::fs::read_to_string(dir.path().join(".config")).unwrap();
1054        assert_eq!(config, initial);
1055    }
1056
1057    /// Fragment asks `CONFIG_NR_CPUS=1`, .config has
1058    /// `CONFIG_NR_CPUS=128`. A plain `contains(fragment_line)` would
1059    /// false-match the substring "CONFIG_NR_CPUS=1" inside
1060    /// "CONFIG_NR_CPUS=128" and skip the append. Exact-line matching
1061    /// via the HashSet helper distinguishes the two and appends.
1062    #[test]
1063    fn configure_kernel_rejects_numeric_prefix_false_match() {
1064        let dir = tempfile::TempDir::new().unwrap();
1065        let initial = "CONFIG_NR_CPUS=128\n";
1066        std::fs::write(dir.path().join(".config"), initial).unwrap();
1067        std::fs::write(dir.path().join("Makefile"), "olddefconfig:\n\t@true\n").unwrap();
1068        let fragment = "CONFIG_NR_CPUS=1\n";
1069        configure_kernel(dir.path(), fragment, None).unwrap();
1070        let config = std::fs::read_to_string(dir.path().join(".config")).unwrap();
1071        assert!(
1072            config.lines().any(|l| l.trim() == "CONFIG_NR_CPUS=1"),
1073            "CONFIG_NR_CPUS=1 must be appended as its own line: {config:?}"
1074        );
1075        assert!(
1076            config.lines().any(|l| l.trim() == "CONFIG_NR_CPUS=128"),
1077            "original CONFIG_NR_CPUS=128 must be preserved: {config:?}"
1078        );
1079    }
1080
1081    /// The `!config_path.exists()` branch: with no pre-existing
1082    /// `.config`, configure_kernel runs `make defconfig` first (via
1083    /// run_make_captured), then appends the fragment and runs
1084    /// olddefconfig. The other configure_kernel tests all pre-write a
1085    /// `.config`, so the defconfig branch was otherwise uncovered. Fake
1086    /// Makefile targets stand in for the kernel's: `defconfig` writes a
1087    /// base `.config`, `olddefconfig` is a no-op.
1088    #[test]
1089    fn configure_kernel_runs_defconfig_when_config_absent() {
1090        let dir = tempfile::TempDir::new().unwrap();
1091        std::fs::write(
1092            dir.path().join("Makefile"),
1093            "defconfig:\n\t@printf 'CONFIG_BASE=y\\n' > .config\nolddefconfig:\n\t@true\n",
1094        )
1095        .unwrap();
1096        let fragment = "CONFIG_EXTRA=y\n";
1097        configure_kernel(dir.path(), fragment, None).unwrap();
1098        let config = std::fs::read_to_string(dir.path().join(".config")).unwrap();
1099        assert!(
1100            config.contains("CONFIG_BASE=y"),
1101            "defconfig target must have created the base .config: {config:?}"
1102        );
1103        assert!(
1104            config.contains("CONFIG_EXTRA=y"),
1105            "fragment must be appended after defconfig: {config:?}"
1106        );
1107    }
1108
1109    // -- all_fragment_lines_present pure helper --
1110
1111    #[test]
1112    fn all_fragment_lines_present_exact_match() {
1113        let config = "CONFIG_FOO=y\nCONFIG_BAR=m\n";
1114        assert!(all_fragment_lines_present("CONFIG_FOO=y\n", config));
1115        assert!(all_fragment_lines_present("CONFIG_BAR=m\n", config));
1116        assert!(all_fragment_lines_present(
1117            "CONFIG_FOO=y\nCONFIG_BAR=m\n",
1118            config
1119        ));
1120    }
1121
1122    #[test]
1123    fn all_fragment_lines_present_numeric_prefix_not_present() {
1124        let config = "CONFIG_NR_CPUS=128\n";
1125        assert!(!all_fragment_lines_present("CONFIG_NR_CPUS=1\n", config));
1126        assert!(!all_fragment_lines_present("CONFIG_NR_CPUS=12\n", config));
1127    }
1128
1129    #[test]
1130    fn all_fragment_lines_present_disable_directive_participates() {
1131        let config = "CONFIG_BPF=y\n";
1132        assert!(!all_fragment_lines_present(
1133            "# CONFIG_BPF is not set\n",
1134            config
1135        ));
1136    }
1137
1138    #[test]
1139    fn all_fragment_lines_present_empty_lines_skipped() {
1140        let config = "CONFIG_FOO=y\n";
1141        assert!(all_fragment_lines_present("\n\nCONFIG_FOO=y\n\n", config));
1142    }
1143
1144    #[test]
1145    fn all_fragment_lines_present_free_text_comment_stripped() {
1146        let config = "CONFIG_FOO=y\n";
1147        let fragment = "# Build for testing scx schedulers\nCONFIG_FOO=y\n";
1148        assert!(
1149            all_fragment_lines_present(fragment, config),
1150            "free-text comment must not block the present-in-config check"
1151        );
1152    }
1153
1154    #[test]
1155    fn all_fragment_lines_present_disable_directive_still_participates() {
1156        let config = "CONFIG_FOO=y\n# CONFIG_BAR is not set\n";
1157        let fragment_present = "# CONFIG_BAR is not set\n";
1158        assert!(
1159            all_fragment_lines_present(fragment_present, config),
1160            "disable directive present in config must satisfy probe"
1161        );
1162        let config_missing = "CONFIG_FOO=y\n";
1163        assert!(
1164            !all_fragment_lines_present(fragment_present, config_missing),
1165            "disable directive missing from config must fail probe"
1166        );
1167    }
1168
1169    #[test]
1170    fn all_fragment_lines_present_section_header_comment_stripped() {
1171        let config = "CONFIG_FOO=y\nCONFIG_BAR=m\n";
1172        let fragment = "\
1173# == BPF support ==\n\
1174CONFIG_FOO=y\n\
1175# == Tracing ==\n\
1176CONFIG_BAR=m\n";
1177        assert!(all_fragment_lines_present(fragment, config));
1178    }
1179
1180    #[test]
1181    fn all_fragment_lines_present_changed_baked_in_with_sched_ext_present() {
1182        // Regression for the configure-skip bug: the prior `has_sched_ext`
1183        // proxy reported "configured" whenever CONFIG_SCHED_CLASS_EXT=y
1184        // persisted in a stale `.config`, so an edited baked-in symbol
1185        // (CONFIG_NR_CPUS 64->512) was silently never re-applied and the
1186        // built kernel mismatched its cache key. `all_fragment_lines_present`
1187        // must read the changed value as not-present even when sched_ext is
1188        // present, so the build.rs gate reconfigures.
1189        let config = "CONFIG_SCHED_CLASS_EXT=y\nCONFIG_NR_CPUS=64\n";
1190        let fragment = "CONFIG_SCHED_CLASS_EXT=y\nCONFIG_NR_CPUS=512\n";
1191        assert!(
1192            !all_fragment_lines_present(fragment, config),
1193            "changed CONFIG_NR_CPUS (64->512) must read as not-present even with sched_ext=y"
1194        );
1195    }
1196
1197    // -- is_kconfig_semantic_line predicate --
1198
1199    #[test]
1200    fn is_kconfig_semantic_line_classifies_assignment_disable_and_comment() {
1201        assert!(is_kconfig_semantic_line("CONFIG_FOO=y"));
1202        assert!(is_kconfig_semantic_line("CONFIG_NR_CPUS=128"));
1203        assert!(is_kconfig_semantic_line("# CONFIG_BPF is not set"));
1204        assert!(is_kconfig_semantic_line("#  CONFIG_BPF is not set"));
1205        assert!(!is_kconfig_semantic_line("# Build for testing"));
1206        assert!(!is_kconfig_semantic_line("# == Section header =="));
1207        assert!(!is_kconfig_semantic_line(""));
1208        assert!(!is_kconfig_semantic_line("# CONFIG_FOO is enabled"));
1209        assert!(!is_kconfig_semantic_line("# CONFIG_FOO"));
1210    }
1211}