1use 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
31pub(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
67pub(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 let rest = rest.trim_start();
87 return rest.starts_with("CONFIG_") && rest.ends_with(" is not set");
88 }
89 true
93}
94
95pub 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 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
173pub 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
192pub(super) fn warn_extra_kconfig_overrides_baked_in(extra: &str, cli_label: &str) {
210 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
244pub(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
264pub(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
282pub(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 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 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
358pub(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
411const 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#[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
498pub(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
516pub 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 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 #[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 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 #[test]
646 fn validate_kernel_config_trim_handles_crlf_and_trailing_whitespace() {
647 let dir = tempfile::TempDir::new().unwrap();
648 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")); } else {
659 content.push_str(&format!("{option}=y \n")); }
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 #[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 #[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 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 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 #[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 #[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 #[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 #[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 assert!(
981 logs_contain("symbol not present in .config"),
982 "WARN's final_state must surface the absent-symbol sentinel",
983 );
984 }
985
986 #[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 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 #[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 #[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 #[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 #[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 #[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 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 #[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}