From 0767c24f53a2f5743f65e27092e814e7ee3b1e47 Mon Sep 17 00:00:00 2001 From: fionera Date: Tue, 11 Aug 2026 21:04:47 +0000 Subject: [PATCH 01/46] kconfig: emit map_directory action plans --- internal/cmd/kconfig_parse/main.go | 13 +- internal/kconfig/BUILD.bazel | 2 + internal/kconfig/compact_action_plan.go | 305 +++++++++++++++++++ internal/kconfig/compact_action_plan_test.go | 290 ++++++++++++++++++ 4 files changed, 607 insertions(+), 3 deletions(-) create mode 100644 internal/kconfig/compact_action_plan.go create mode 100644 internal/kconfig/compact_action_plan_test.go diff --git a/internal/cmd/kconfig_parse/main.go b/internal/cmd/kconfig_parse/main.go index 17e23ce1..7107eaba 100644 --- a/internal/cmd/kconfig_parse/main.go +++ b/internal/cmd/kconfig_parse/main.go @@ -287,6 +287,7 @@ func run() (exitCode int) { kbuildTreeMinCount = flag.Int("kbuild_tree_min_count", 0, "Minimum number of Kbuild-like files that must be parsed during -kbuild_tree_root validation") compactMetadataOut = flag.String("compact_metadata_out", "", "Path to write compact fragment-keyed Linux metadata JSON") compactBuildfileOut = flag.String("compact_buildfile_out", "", "Path to write a combined compact object/image BUILD file") + compactActionPlanOut = flag.String("compact_action_plan_out", "", "Directory to write a map_directory compact compile action plan") compactBaseConfig = flag.String("compact_base_config", "", "Base config name for delta image BUILD emission") compileEnvironmentABI = flag.String("compile_environment_abi", "", "Toolchain/action ABI bound into compile environment content IDs") rustProfileOut = flag.String("rust_profile_out", "", "Path to write the source-derived Rust profile JSON") @@ -535,7 +536,7 @@ func run() (exitCode int) { } resolvedConfigRequested := *resolveConfig != "" || *resolvedConfigOut != "" || *resolvedAutoConfOut != "" || *resolvedCmdOut != "" || *resolvedAutoconfOut != "" || *resolvedRustcCfgOut != "" || *resolvedReleaseOut != "" - if tree == nil && (*compactMetadataOut != "" || *compactBuildfileOut != "" || resolvedConfigRequested || *out != "") { + if tree == nil && (*compactMetadataOut != "" || *compactBuildfileOut != "" || *compactActionPlanOut != "" || resolvedConfigRequested || *out != "") { fmt.Fprintf(os.Stderr, "-root is required for Kconfig outputs\n") return 2 } @@ -554,7 +555,7 @@ func run() (exitCode int) { } } - if *compactMetadataOut != "" || *compactBuildfileOut != "" { + if *compactMetadataOut != "" || *compactBuildfileOut != "" || *compactActionPlanOut != "" { headerLabels, err := compactGeneratedHeaderLabels( compactConfigInputs, generatedHeadersByConfig, @@ -593,6 +594,12 @@ func run() (exitCode int) { return 1 } } + if *compactActionPlanOut != "" { + if err := metadata.WriteCompactActionPlan(workspacePath(*compactActionPlanOut)); err != nil { + fmt.Fprintf(os.Stderr, "failed to write compact action plan: %v\n", err) + return 1 + } + } if *compactBuildfileOut != "" { exports := []string(compactExports) if len(exports) == 0 { @@ -631,7 +638,7 @@ func run() (exitCode int) { // Only emit the JSON dump when explicitly requested, or when no output was // requested at all (preserves the prior default of dumping to stdout). - if *out == "" && (*kbuildOut != "" || *kbuildTreeOut != "" || *compactMetadataOut != "" || *compactBuildfileOut != "" || *rustProfileOut != "" || resolvedConfigRequested) { + if *out == "" && (*kbuildOut != "" || *kbuildTreeOut != "" || *compactMetadataOut != "" || *compactBuildfileOut != "" || *compactActionPlanOut != "" || *rustProfileOut != "" || resolvedConfigRequested) { return 0 } diff --git a/internal/kconfig/BUILD.bazel b/internal/kconfig/BUILD.bazel index 51efbfbb..b6f07a69 100644 --- a/internal/kconfig/BUILD.bazel +++ b/internal/kconfig/BUILD.bazel @@ -5,6 +5,7 @@ go_library( srcs = [ "buildmerge.go", "compact.go", + "compact_action_plan.go", "compact_content.go", "config.go", "config_footprint.go", @@ -37,6 +38,7 @@ go_library( go_test( name = "kconfig_test", srcs = [ + "compact_action_plan_test.go", "compact_test.go", "config_footprint_test.go", "config_test.go", diff --git a/internal/kconfig/compact_action_plan.go b/internal/kconfig/compact_action_plan.go new file mode 100644 index 00000000..474d7204 --- /dev/null +++ b/internal/kconfig/compact_action_plan.go @@ -0,0 +1,305 @@ +package kconfig + +import ( + "encoding/hex" + "encoding/json" + "fmt" + "os" + "path" + "path/filepath" + "sort" + "strings" +) + +const compactActionPlanMetadataSchema = "compact-v8-adaptive-content-graph" + +type compactActionPlanEntry struct { + path string + data []byte +} + +// WriteCompactActionPlan writes a versioned action-plan tree for one measured, +// adaptive compact configuration. The directory layout intentionally carries +// every value needed by a map_directory callback: callbacks can inspect a tree +// artifact's child paths, but cannot read child contents during expansion. +// Compile marker contents retain the validated recipe for ordinary actions and +// future expansion stages while the callback selects work from marker paths. +func (m *CompactMetadata) WriteCompactActionPlan(outputDir string) error { + entries, err := m.compactActionPlanEntries() + if err != nil { + return err + } + if strings.TrimSpace(outputDir) == "" { + return fmt.Errorf("compact action plan output directory must not be empty") + } + outputDir = filepath.Clean(outputDir) + precreated := false + if info, err := os.Lstat(outputDir); err == nil { + if !info.IsDir() { + return fmt.Errorf("compact action plan output %q exists and is not a directory", outputDir) + } + children, err := os.ReadDir(outputDir) + if err != nil { + return fmt.Errorf("inspect compact action plan output directory %q: %w", outputDir, err) + } + if len(children) != 0 { + return fmt.Errorf("compact action plan output directory %q is not empty", outputDir) + } + precreated = true + } else if !os.IsNotExist(err) { + return fmt.Errorf("inspect compact action plan output directory %q: %w", outputDir, err) + } + + parent := filepath.Dir(outputDir) + if err := os.MkdirAll(parent, 0o755); err != nil { + return fmt.Errorf("create compact action plan parent %q: %w", parent, err) + } + temporary, err := os.MkdirTemp(parent, "."+filepath.Base(outputDir)+".tmp-") + if err != nil { + return fmt.Errorf("create temporary compact action plan: %w", err) + } + published := false + defer func() { + if !published { + _ = os.RemoveAll(temporary) + } + }() + + for _, entry := range entries { + filename := filepath.Join(temporary, filepath.FromSlash(entry.path)) + if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil { + return fmt.Errorf("create compact action plan directory for %q: %w", entry.path, err) + } + if err := os.WriteFile(filename, entry.data, 0o644); err != nil { + return fmt.Errorf("write compact action plan entry %q: %w", entry.path, err) + } + } + // Bazel precreates an empty directory for a declared TreeArtifact. Replace + // that exact empty directory only after the complete plan has been staged. + if precreated { + if err := os.Remove(outputDir); err != nil { + return fmt.Errorf("replace empty compact action plan output directory %q: %w", outputDir, err) + } + } + if err := os.Rename(temporary, outputDir); err != nil { + return fmt.Errorf("publish compact action plan %q: %w", outputDir, err) + } + published = true + return nil +} + +func (m *CompactMetadata) compactActionPlanEntries() ([]compactActionPlanEntry, error) { + if m == nil { + return nil, fmt.Errorf("compact action plan requires metadata") + } + if m.Schema != compactActionPlanMetadataSchema || m.Target == nil { + return nil, fmt.Errorf("compact action plan requires measured adaptive compact metadata") + } + profile, err := LinuxTargetProfileByName(m.Target.Profile) + if err != nil { + return nil, fmt.Errorf("compact action plan target: %w", err) + } + if err := profile.ValidateTargetIdentity(m.Target.LinuxArch, m.Target.TargetTriple); err != nil { + return nil, fmt.Errorf("compact action plan target: %w", err) + } + if m.Target.Profile != profile.Name || + m.Target.LinuxArch != profile.Arch || + m.Target.Srcarch != profile.Srcarch || + m.Target.UTSMachine != profile.UTSMachine || + m.Target.TargetTriple != profile.TargetTriple { + return nil, fmt.Errorf("compact action plan has incomplete or inconsistent target identity %#v", m.Target) + } + if err := validateCompactActionPlanProbeIdentity(m.Target.ProbeIdentity); err != nil { + return nil, err + } + if len(m.Configs) != 1 { + return nil, fmt.Errorf("compact action plan requires exactly one config, got %d", len(m.Configs)) + } + + variants := make(map[string]CompactObjectVariant, len(m.ObjectVariants)) + for _, variant := range m.ObjectVariants { + if _, exists := variants[variant.Target]; exists { + return nil, fmt.Errorf("compact action plan has duplicate object target %q", variant.Target) + } + variants[variant.Target] = variant + } + config := m.Configs[0] + selectedTargets := append([]string(nil), config.ObjectTargets...) + selectedTargets = append(selectedTargets, config.ModuleObjectTargets...) + sort.Strings(selectedTargets) + + selected := make([]CompactObjectVariant, 0, len(selectedTargets)) + seenTargets := make(map[string]bool, len(selectedTargets)) + for _, target := range selectedTargets { + if seenTargets[target] { + continue + } + seenTargets[target] = true + variant, ok := variants[target] + if !ok { + return nil, fmt.Errorf("compact config %q selects missing object target %q", config.Name, target) + } + if err := validateCompactActionPlanVariant(variant); err != nil { + return nil, err + } + selected = append(selected, variant) + } + sort.Slice(selected, func(i, j int) bool { + if selected[i].Object != selected[j].Object { + return selected[i].Object < selected[j].Object + } + return selected[i].ContentID < selected[j].ContentID + }) + + usedSourceIndices := map[int]bool{} + primarySourceIndices := make(map[string]int, len(selected)) + for _, variant := range selected { + if variant.SourceInputGroup <= 0 || variant.SourceInputGroup > len(m.SourceInputGroups) { + return nil, fmt.Errorf( + "object %q references source input group %d, out of range 1..%d", + variant.Object, + variant.SourceInputGroup, + len(m.SourceInputGroups), + ) + } + indices, err := decodeCompactSourceInputGroup( + m.SourceInputGroups[variant.SourceInputGroup-1], + len(m.SourceFiles), + ) + if err != nil { + return nil, fmt.Errorf("object %q source inputs: %w", variant.Object, err) + } + primary := 0 + for _, index := range indices { + input := m.SourceFiles[index-1] + if err := validateCompactActionPlanRelativePath("source", input.Path); err != nil { + return nil, err + } + if input.Path == variant.Source { + primary = index + } + usedSourceIndices[index] = true + } + if primary == 0 { + return nil, fmt.Errorf("object %q source input group omits primary source %q", variant.Object, variant.Source) + } + primarySourceIndices[variant.Target] = primary + } + + // The compact graph generator already canonicalizes and hashes these fields. + // Revalidate it before publishing recipes so hand-constructed or corrupted + // metadata cannot become executable action descriptions. + if err := m.validateContentIDs(); err != nil { + return nil, fmt.Errorf("validate compact action plan metadata: %w", err) + } + + entries := []compactActionPlanEntry{{ + path: path.Join("v1", "probe", m.Target.ProbeIdentity), + }} + indices := make([]int, 0, len(usedSourceIndices)) + for index := range usedSourceIndices { + indices = append(indices, index) + } + sort.Ints(indices) + for _, index := range indices { + if index > 99999999 { + return nil, fmt.Errorf("compact action plan source index %d exceeds eight digits", index) + } + entries = append(entries, compactActionPlanEntry{ + path: path.Join("v1", "source", fmt.Sprintf("%08d", index), m.SourceFiles[index-1].Path), + }) + } + for _, variant := range selected { + data, err := json.MarshalIndent(variant, "", " ") + if err != nil { + return nil, fmt.Errorf("encode compact action plan recipe for %q: %w", variant.Object, err) + } + data = append(data, '\n') + entries = append(entries, compactActionPlanEntry{ + path: path.Join( + "v1", + "compile", + variant.ContentID, + fmt.Sprintf("%08d", primarySourceIndices[variant.Target]), + variant.Object+".json", + ), + data: data, + }) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].path < entries[j].path }) + return entries, nil +} + +func validateCompactActionPlanVariant(variant CompactObjectVariant) error { + if err := validateCompactActionPlanDigest("object content ID", variant.ContentID); err != nil { + return fmt.Errorf("object %q: %w", variant.Object, err) + } + if err := validateCompactActionPlanRelativePath("object", variant.Object); err != nil { + return err + } + if len(variant.Members) != 0 { + return fmt.Errorf("object %q has an unsupported composite recipe", variant.Object) + } + if len(variant.Deps) != 0 { + return fmt.Errorf("object %q has unsupported generated-object dependencies", variant.Object) + } + if compactGroupedSpecialObjects[variant.Object] || + strings.HasSuffix(variant.Object, ".asn1.o") || + strings.HasSuffix(variant.Object, ".pi.o") || + strings.HasSuffix(variant.Object, ".stub.o") { + return fmt.Errorf("object %q has an unsupported generated recipe", variant.Object) + } + if !strings.HasSuffix(variant.Object, ".o") { + return fmt.Errorf("object %q is not a leaf object", variant.Object) + } + if variant.Mode != "y" || variant.ModuleRoot { + return fmt.Errorf("object %q has unsupported non-built-in mode %q", variant.Object, variant.Mode) + } + if err := validateCompactActionPlanRelativePath("source", variant.Source); err != nil { + return err + } + if compactSourceLanguage(variant.Source) != "c" { + return fmt.Errorf("object %q has unsupported non-C source %q", variant.Object, variant.Source) + } + if variant.Symversions || variant.ObjtoolForce || len(variant.ObjtoolArgs) != 0 { + return fmt.Errorf("object %q has unsupported generated or post-compile processing", variant.Object) + } + if reason := variant.sourceBuildError(); reason != "" { + return fmt.Errorf("object %q cannot be compiled from source: %s", variant.Object, reason) + } + return nil +} + +func validateCompactActionPlanProbeIdentity(identity string) error { + digest, ok := strings.CutPrefix(identity, "sha256-") + if !ok { + return fmt.Errorf("compact action plan requires a measured sha256 probe identity, got %q", identity) + } + if err := validateCompactActionPlanDigest("probe identity", digest); err != nil { + return err + } + return nil +} + +func validateCompactActionPlanDigest(kind, value string) error { + if len(value) != 64 || strings.ToLower(value) != value { + return fmt.Errorf("%s %q is not a canonical SHA-256 digest", kind, value) + } + if _, err := hex.DecodeString(value); err != nil { + return fmt.Errorf("%s %q is not a canonical SHA-256 digest: %w", kind, value, err) + } + return nil +} + +func validateCompactActionPlanRelativePath(kind, value string) error { + if value == "" || strings.Contains(value, `\`) || strings.ContainsRune(value, 0) || + strings.HasPrefix(value, "/") || path.Clean(value) != value { + return fmt.Errorf("compact action plan %s path %q is not a canonical relative path", kind, value) + } + for _, component := range strings.Split(value, "/") { + if component == "" || component == "." || component == ".." { + return fmt.Errorf("compact action plan %s path %q is not a canonical relative path", kind, value) + } + } + return nil +} diff --git a/internal/kconfig/compact_action_plan_test.go b/internal/kconfig/compact_action_plan_test.go new file mode 100644 index 00000000..5fac7827 --- /dev/null +++ b/internal/kconfig/compact_action_plan_test.go @@ -0,0 +1,290 @@ +package kconfig + +import ( + "encoding/json" + "fmt" + "io/fs" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "testing" +) + +const compactActionPlanTestProbeIdentity = "sha256-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + +func TestWriteCompactActionPlanEmitsDeterministicSelectedRecipes(t *testing.T) { + metadata := compactActionPlanMetadataForTest(t) + first := filepath.Join(t.TempDir(), "plan") + second := filepath.Join(t.TempDir(), "plan") + if err := os.Mkdir(second, 0o755); err != nil { + t.Fatalf("precreate TreeArtifact directory: %v", err) + } + if err := metadata.WriteCompactActionPlan(first); err != nil { + t.Fatalf("WriteCompactActionPlan(first) failed: %v", err) + } + if err := metadata.WriteCompactActionPlan(second); err != nil { + t.Fatalf("WriteCompactActionPlan(second) failed: %v", err) + } + + firstFiles := compactActionPlanFilesForTest(t, first) + secondFiles := compactActionPlanFilesForTest(t, second) + if !reflect.DeepEqual(firstFiles, secondFiles) { + t.Fatalf("compact action plan is not deterministic:\nfirst: %#v\nsecond: %#v", firstFiles, secondFiles) + } + probePath := "v1/probe/" + compactActionPlanTestProbeIdentity + if data, ok := firstFiles[probePath]; !ok || len(data) != 0 { + t.Fatalf("probe marker %q = %q, present=%v; want empty marker", probePath, data, ok) + } + + selected := compactActionPlanSelectedVariantsForTest(t, metadata) + compileFiles := map[string][]byte{} + sourceMarkers := 0 + for name, data := range firstFiles { + switch { + case strings.HasPrefix(name, "v1/compile/"): + compileFiles[name] = data + case strings.HasPrefix(name, "v1/source/"): + sourceMarkers++ + if len(data) != 0 { + t.Fatalf("source marker %q is not empty: %q", name, data) + } + } + } + if len(compileFiles) != len(selected) { + t.Fatalf("compile marker count = %d, want %d", len(compileFiles), len(selected)) + } + if sourceMarkers == 0 { + t.Fatal("compact action plan emitted no source markers") + } + for _, variant := range selected { + primary, err := metadata.sourceFileIndex(variant.Source) + if err != nil { + t.Fatal(err) + } + name := fmt.Sprintf( + "v1/compile/%s/%08d/%s.json", + variant.ContentID, + primary, + variant.Object, + ) + got, ok := compileFiles[name] + if !ok { + t.Fatalf("missing compile marker %q; got %v", name, sortedCompactActionPlanFileNames(compileFiles)) + } + want, err := json.MarshalIndent(variant, "", " ") + if err != nil { + t.Fatal(err) + } + want = append(want, '\n') + if string(got) != string(want) { + t.Fatalf("compile marker %q =\n%s\nwant:\n%s", name, got, want) + } + } +} + +func TestWriteCompactActionPlanRejectsNonemptyOutput(t *testing.T) { + output := filepath.Join(t.TempDir(), "plan") + if err := os.Mkdir(output, 0o755); err != nil { + t.Fatal(err) + } + sentinel := filepath.Join(output, "user-data") + if err := os.WriteFile(sentinel, []byte("preserve me"), 0o644); err != nil { + t.Fatal(err) + } + err := compactActionPlanMetadataForTest(t).WriteCompactActionPlan(output) + if err == nil || !strings.Contains(err.Error(), "is not empty") { + t.Fatalf("WriteCompactActionPlan() error = %v, want nonempty output error", err) + } + data, readErr := os.ReadFile(sentinel) + if readErr != nil || string(data) != "preserve me" { + t.Fatalf("nonempty output was modified: data=%q, error=%v", data, readErr) + } +} + +func TestWriteCompactActionPlanRejectsUnsupportedMetadata(t *testing.T) { + tests := []struct { + name string + mutate func(*CompactMetadata, *CompactObjectVariant) + want string + }{ + { + name: "non-adaptive metadata", + mutate: func(metadata *CompactMetadata, _ *CompactObjectVariant) { + metadata.Schema = "" + }, + want: "measured adaptive compact metadata", + }, + { + name: "unmeasured probe identity", + mutate: func(metadata *CompactMetadata, _ *CompactObjectVariant) { + metadata.Target.ProbeIdentity = "fixed-clang" + }, + want: "measured sha256 probe identity", + }, + { + name: "multiple configs", + mutate: func(metadata *CompactMetadata, _ *CompactObjectVariant) { + metadata.Configs = append(metadata.Configs, metadata.Configs[0]) + }, + want: "exactly one config", + }, + { + name: "composite recipe", + mutate: func(_ *CompactMetadata, variant *CompactObjectVariant) { + variant.Members = []string{"member"} + }, + want: "unsupported composite recipe", + }, + { + name: "generated dependency", + mutate: func(_ *CompactMetadata, variant *CompactObjectVariant) { + variant.Deps = []string{"generated"} + }, + want: "unsupported generated-object dependencies", + }, + { + name: "assembly source", + mutate: func(_ *CompactMetadata, variant *CompactObjectVariant) { + variant.Source = strings.TrimSuffix(variant.Source, ".c") + ".S" + }, + want: "unsupported non-C source", + }, + { + name: "module recipe", + mutate: func(_ *CompactMetadata, variant *CompactObjectVariant) { + variant.Mode = "m" + variant.ModuleRoot = true + }, + want: "unsupported non-built-in mode", + }, + { + name: "object path traversal", + mutate: func(_ *CompactMetadata, variant *CompactObjectVariant) { + variant.Object = "../escape.o" + }, + want: "not a canonical relative path", + }, + { + name: "missing primary source", + mutate: func(_ *CompactMetadata, variant *CompactObjectVariant) { + variant.Source = "missing.c" + }, + want: "omits primary source", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + metadata := compactActionPlanMetadataForTest(t) + variant := compactActionPlanFirstSelectedVariantForTest(t, metadata) + test.mutate(metadata, variant) + output := filepath.Join(t.TempDir(), "plan") + err := metadata.WriteCompactActionPlan(output) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("WriteCompactActionPlan() error = %v, want substring %q", err, test.want) + } + if _, statErr := os.Stat(output); !os.IsNotExist(statErr) { + t.Fatalf("invalid plan published output %q: %v", output, statErr) + } + }) + } +} + +func compactActionPlanMetadataForTest(t *testing.T) *CompactMetadata { + t.Helper() + metadata, err := compactMetadataBatchForTest( + t, + mustParseCompactFixture(t), + mustParseKbuildFixture(t), + []NamedConfig{{Name: "selected", Flags: map[string]string{"CONFIG_NET": "y"}}}, + ) + if err != nil { + t.Fatalf("compactMetadataBatchForTest() failed: %v", err) + } + metadata.Schema = compactActionPlanMetadataSchema + metadata.Target = &CompactTarget{ + Profile: "x86_64", + LinuxArch: "x86", + Srcarch: "x86", + UTSMachine: "x86_64", + TargetTriple: "x86_64-linux-gnu", + ProbeIdentity: compactActionPlanTestProbeIdentity, + } + return metadata +} + +func compactActionPlanFirstSelectedVariantForTest(t *testing.T, metadata *CompactMetadata) *CompactObjectVariant { + t.Helper() + if len(metadata.Configs) != 1 || len(metadata.Configs[0].ObjectTargets) == 0 { + t.Fatalf("test metadata has no selected object: %#v", metadata.Configs) + } + target := metadata.Configs[0].ObjectTargets[0] + for i := range metadata.ObjectVariants { + if metadata.ObjectVariants[i].Target == target { + return &metadata.ObjectVariants[i] + } + } + t.Fatalf("selected target %q has no variant", target) + return nil +} + +func compactActionPlanSelectedVariantsForTest(t *testing.T, metadata *CompactMetadata) []CompactObjectVariant { + t.Helper() + byTarget := map[string]CompactObjectVariant{} + for _, variant := range metadata.ObjectVariants { + byTarget[variant.Target] = variant + } + targets := append([]string(nil), metadata.Configs[0].ObjectTargets...) + targets = append(targets, metadata.Configs[0].ModuleObjectTargets...) + selected := make([]CompactObjectVariant, 0, len(targets)) + seen := map[string]bool{} + for _, target := range targets { + if seen[target] { + continue + } + seen[target] = true + variant, ok := byTarget[target] + if !ok { + t.Fatalf("selected target %q has no variant", target) + } + selected = append(selected, variant) + } + return selected +} + +func compactActionPlanFilesForTest(t *testing.T, root string) map[string][]byte { + t.Helper() + out := map[string][]byte{} + if err := filepath.WalkDir(root, func(filename string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() { + return nil + } + relative, err := filepath.Rel(root, filename) + if err != nil { + return err + } + data, err := os.ReadFile(filename) + if err != nil { + return err + } + out[filepath.ToSlash(relative)] = data + return nil + }); err != nil { + t.Fatalf("walk compact action plan: %v", err) + } + return out +} + +func sortedCompactActionPlanFileNames(files map[string][]byte) []string { + out := make([]string, 0, len(files)) + for name := range files { + out = append(out, name) + } + sort.Strings(out) + return out +} From 9ab0199e23c518197d59280a8055a46efe3cebb3 Mon Sep 17 00:00:00 2001 From: fionera Date: Tue, 11 Aug 2026 21:04:55 +0000 Subject: [PATCH 02/46] tests: exercise action-time Kconfig expansion --- .github/workflows/ci.yml | 5 +- internal/map_directory_kconfig.bzl | 305 ++++++++++++++++++ tests/map_directory/BUILD.bazel | 39 +++ tests/map_directory/Kbuild | 4 + tests/map_directory/Kconfig | 20 ++ tests/map_directory/base.config | 2 + .../include/linux/compiler-version.h | 1 + .../include/linux/compiler_types.h | 1 + tests/map_directory/include/linux/kconfig.h | 1 + tests/map_directory/supported.c | 4 + tests/map_directory/unsupported.c | 1 + tests/map_directory/validator.go | 149 +++++++++ 12 files changed, 531 insertions(+), 1 deletion(-) create mode 100644 internal/map_directory_kconfig.bzl create mode 100644 tests/map_directory/BUILD.bazel create mode 100644 tests/map_directory/Kbuild create mode 100644 tests/map_directory/Kconfig create mode 100644 tests/map_directory/base.config create mode 100644 tests/map_directory/include/linux/compiler-version.h create mode 100644 tests/map_directory/include/linux/compiler_types.h create mode 100644 tests/map_directory/include/linux/kconfig.h create mode 100644 tests/map_directory/supported.c create mode 100644 tests/map_directory/unsupported.c create mode 100644 tests/map_directory/validator.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d654806..5ae5b7f0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,7 +52,10 @@ jobs: targets=(//...) path_mapping_args=() if [[ -n "${BAZEL_PATH_MAPPING}" ]]; then - targets+=(//internal/tests:path_mapping_test) + targets+=( + //internal/tests:path_mapping_test + //tests/map_directory:compiler_capabilities_e2e_test + ) path_mapping_args+=("${BAZEL_PATH_MAPPING}") fi bazel --host_jvm_args=-Xmx6g \ diff --git a/internal/map_directory_kconfig.bzl b/internal/map_directory_kconfig.bzl new file mode 100644 index 00000000..3cf49146 --- /dev/null +++ b/internal/map_directory_kconfig.bzl @@ -0,0 +1,305 @@ +"""Bazel 9 feasibility spike for execution-time Kconfig graph expansion.""" + +load("@rules_cc//cc:action_names.bzl", "C_COMPILE_ACTION_NAME") +load( + "@rules_cc//cc:find_cc_toolchain.bzl", + "CC_TOOLCHAIN_TYPE", + "find_cpp_toolchain", + "use_cc_toolchain", +) +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") + +visibility("//tests/map_directory") + +_HEX_DIGITS = "0123456789abcdef" +_PLAN_VERSION = "v1" +_SOURCE_INPUT_PREFIX = "source:" + +def _is_decimal(value): + if not value: + return False + for index in range(len(value)): + if value[index] not in "0123456789": + return False + return True + +def _is_sha256(value): + if len(value) != 64: + return False + for index in range(len(value)): + if value[index] not in _HEX_DIGITS: + return False + return True + +def _validate_relative_path(path, what): + if not path or path.startswith("/") or path.endswith("/") or "//" in path: + fail("%s has invalid relative path %r" % (what, path)) + for component in path.split("/"): + if component in ["", ".", ".."]: + fail("%s has invalid relative path %r" % (what, path)) + +def _map_compiler_selected_objects( + template_ctx, + input_directories, + output_directories, + additional_inputs, + tools, + additional_params): + """Expands the action plan after its producing action has completed.""" + plan = input_directories["plan"] + output_directory = output_directories["objects"] + + children = {} + for child in plan.children: + children[child.tree_relative_path] = child + + source_markers = {} + probe_marker = None + compile_paths = [] + for path in sorted(children.keys()): + parts = path.split("/") + if len(parts) == 3 and parts[0] == _PLAN_VERSION and parts[1] == "probe": + identity = parts[2] + if not identity.startswith("sha256-") or not _is_sha256(identity[len("sha256-"):]): + fail("map_directory plan has invalid measured probe identity %r" % identity) + if probe_marker != None: + fail("map_directory plan contains more than one measured probe marker") + probe_marker = children[path] + elif len(parts) >= 4 and parts[0] == _PLAN_VERSION and parts[1] == "source": + index = parts[2] + canonical_path = "/".join(parts[3:]) + if len(index) != 8 or not _is_decimal(index) or index == "00000000": + fail("map_directory plan has invalid source index %r" % index) + _validate_relative_path(canonical_path, "map_directory source marker") + if index in source_markers: + fail("map_directory plan repeats source index %s" % index) + source_key = _SOURCE_INPUT_PREFIX + canonical_path + if source_key not in additional_inputs: + fail("map_directory plan selected undeclared source %r" % canonical_path) + source_markers[index] = struct( + file = additional_inputs[source_key], + marker = children[path], + ) + elif len(parts) >= 5 and parts[0] == _PLAN_VERSION and parts[1] == "compile": + compile_paths.append(path) + else: + fail("map_directory plan contains unknown marker %r" % path) + + if probe_marker == None: + fail("map_directory plan is missing its measured probe marker") + if not compile_paths: + fail("map_directory plan selected no compile actions") + + declared_outputs = {} + for path in compile_paths: + marker = children[path] + parts = path.split("/") + content_id = parts[2] + source_index = parts[3] + object_json = "/".join(parts[4:]) + if not _is_sha256(content_id): + fail("map_directory plan has invalid compile content ID %r" % content_id) + if len(source_index) != 8 or source_index not in source_markers: + fail("map_directory plan compile marker references unknown source index %r" % source_index) + if not object_json.endswith(".o.json"): + fail("map_directory plan compile marker does not name an object recipe: %r" % path) + object_path = object_json[:-len(".json")] + _validate_relative_path(object_path, "map_directory compile marker") + output_path = content_id + "/" + object_path + if output_path in declared_outputs: + fail("map_directory plan repeats output %r" % output_path) + declared_outputs[output_path] = True + + source = source_markers[source_index] + output = template_ctx.declare_file(output_path, directory = output_directory) + args = template_ctx.args() + args.add("--target=" + additional_params["target_triple"]) + args.add(additional_params["compile_flag"]) + args.add("-Werror") + args.add("-c") + args.add(source.file) + args.add("-o") + args.add(output) + template_ctx.run( + executable = tools["cc"], + inputs = [ + marker, + probe_marker, + source.file, + source.marker, + ], + tools = [tools["cc_files"]], + outputs = [output], + arguments = [args], + progress_message = "Compiling a compiler-selected Kconfig object", + ) + +def _tool_file_for_path(cc_toolchain, tool_path, name): + matches = [ + file + for file in cc_toolchain.all_files.to_list() + if file.path == tool_path + ] + if len(matches) != 1: + fail( + "selected C/C++ toolchain must provide exactly one File for %s path %r; found: %s" % ( + name, + tool_path, + ", ".join(sorted([file.path for file in matches])) or "none", + ), + ) + return matches[0] + +def _tool_file_for_basename(cc_toolchain, basename): + basenames = [basename, basename + ".exe"] + matches = [ + file + for file in cc_toolchain.all_files.to_list() + if file.basename in basenames + ] + if len(matches) != 1: + fail( + "selected C/C++ toolchain must provide exactly one %s; found: %s" % ( + basename, + ", ".join(sorted([file.path for file in matches])) or "none", + ), + ) + return matches[0] + +def _canonical_sources(ctx): + prefix = ctx.label.package + "/" if ctx.label.package else "" + sources = {} + for file in ctx.files.srcs: + path = file.short_path + if not path.startswith(prefix): + fail("map_directory spike source %s is outside package %s" % (file, ctx.label.package)) + canonical_path = path[len(prefix):] + _validate_relative_path(canonical_path, "map_directory candidate source") + if canonical_path in sources: + fail("map_directory spike repeats candidate source %r" % canonical_path) + sources[canonical_path] = file + return sources + +def _linux_map_directory_kconfig_spike_impl(ctx): + cc_toolchain = find_cpp_toolchain(ctx) + feature_configuration = cc_common.configure_features( + ctx = ctx, + cc_toolchain = cc_toolchain, + requested_features = ctx.features, + unsupported_features = ctx.disabled_features, + ) + compiler_path = cc_common.get_tool_for_action( + feature_configuration = feature_configuration, + action_name = C_COMPILE_ACTION_NAME, + ) + compiler = _tool_file_for_path(cc_toolchain, compiler_path, "C compiler") + linker = _tool_file_for_basename(cc_toolchain, "ld.lld") + sources = _canonical_sources(ctx) + + plan = ctx.actions.declare_directory(ctx.label.name + ".plan") + objects = ctx.actions.declare_directory(ctx.label.name + ".objects") + validated = ctx.actions.declare_file(ctx.label.name + ".validated") + + plan_args = ctx.actions.args() + plan_args.add("-root") + plan_args.add(ctx.file.kconfig) + plan_args.add("-kbuild") + plan_args.add(ctx.file.kbuild) + plan_args.add("-config") + plan_args.add(ctx.file.config, format = ctx.attr.config_name + "=%s") + plan_args.add("-generated_headers_for_config") + plan_args.add(ctx.attr.config_name + "=//tests/map_directory:unused_generated_headers") + plan_args.add("-compile_environment_abi") + plan_args.add("map-directory-spike/" + ctx.attr.target_profile) + plan_args.add("-target_profile") + plan_args.add(ctx.attr.target_profile) + plan_args.add("-linux_arch") + plan_args.add(ctx.attr.linux_arch) + plan_args.add("-target_triple") + plan_args.add(ctx.attr.target_triple) + plan_args.add("-probe_cc") + plan_args.add(compiler) + plan_args.add("-probe_ld") + plan_args.add(linker) + plan_args.add("-compact_action_plan_out") + plan_args.add_all([plan], expand_directories = False) + + ctx.actions.run( + executable = ctx.attr._kconfig_parse[DefaultInfo].files_to_run, + inputs = [ctx.file.kconfig, ctx.file.kbuild, ctx.file.config] + ctx.files.srcs, + tools = cc_toolchain.all_files, + outputs = [plan], + arguments = [plan_args], + mnemonic = "MapDirectoryKconfigPlan", + progress_message = "Probing the selected compiler and generating a Kconfig action plan for %{label}", + execution_requirements = {"supports-path-mapping": "1"}, + toolchain = CC_TOOLCHAIN_TYPE, + ) + + additional_inputs = {} + for canonical_path, file in sources.items(): + additional_inputs[_SOURCE_INPUT_PREFIX + canonical_path] = file + ctx.actions.map_directory( + implementation = _map_compiler_selected_objects, + input_directories = {"plan": plan}, + output_directories = {"objects": objects}, + additional_inputs = additional_inputs, + tools = { + "cc": compiler, + "cc_files": cc_toolchain.all_files, + }, + additional_params = { + "compile_flag": "-fno-omit-frame-pointer", + "target_triple": ctx.attr.target_triple, + }, + execution_requirements = {"supports-path-mapping": "1"}, + mnemonic = "MapDirectoryKconfigCompile", + toolchain = CC_TOOLCHAIN_TYPE, + ) + + validation_args = ctx.actions.args() + validation_args.add("-plan") + validation_args.add_all([plan], expand_directories = False) + validation_args.add("-objects") + validation_args.add_all([objects], expand_directories = False) + validation_args.add("-out") + validation_args.add(validated) + ctx.actions.run( + executable = ctx.executable.validator, + inputs = [plan, objects], + outputs = [validated], + arguments = [validation_args], + mnemonic = "MapDirectoryKconfigValidate", + progress_message = "Validating mapped compiler output for %{label}", + execution_requirements = {"supports-path-mapping": "1"}, + ) + + return [ + DefaultInfo(files = depset([validated])), + OutputGroupInfo( + objects = depset([objects]), + plan = depset([plan]), + ), + ] + +linux_map_directory_kconfig_spike = rule( + implementation = _linux_map_directory_kconfig_spike_impl, + attrs = { + "config": attr.label(allow_single_file = True, mandatory = True), + "config_name": attr.string(default = "spike"), + "kbuild": attr.label(allow_single_file = True, mandatory = True), + "kconfig": attr.label(allow_single_file = True, mandatory = True), + "linux_arch": attr.string(default = "x86"), + "srcs": attr.label_list(allow_files = [".c", ".h"], mandatory = True), + "target_profile": attr.string(default = "x86_64"), + "target_triple": attr.string(default = "x86_64-linux-gnu"), + "validator": attr.label(cfg = "exec", executable = True, mandatory = True), + "_kconfig_parse": attr.label( + cfg = "exec", + default = Label("//internal/cmd/kconfig_parse:kconfig_parse"), + executable = True, + ), + }, + fragments = ["cpp"], + toolchains = use_cc_toolchain(), +) diff --git a/tests/map_directory/BUILD.bazel b/tests/map_directory/BUILD.bazel new file mode 100644 index 00000000..08dddded --- /dev/null +++ b/tests/map_directory/BUILD.bazel @@ -0,0 +1,39 @@ +load("@bazel_skylib//rules:build_test.bzl", "build_test") +load("@rules_go//go:def.bzl", "go_binary") +load("//internal:map_directory_kconfig.bzl", "linux_map_directory_kconfig_spike") + +package(default_visibility = ["//visibility:private"]) + +go_binary( + name = "validator", + srcs = ["validator.go"], + pure = "on", +) + +linux_map_directory_kconfig_spike( + name = "compiler_capabilities", + srcs = [ + "include/linux/compiler-version.h", + "include/linux/compiler_types.h", + "include/linux/kconfig.h", + "supported.c", + "unsupported.c", + ], + config = "base.config", + kbuild = "Kbuild", + kconfig = "Kconfig", + tags = [ + "manual", + "requires-bazel-9", + ], + validator = ":validator", +) + +build_test( + name = "compiler_capabilities_e2e_test", + tags = [ + "manual", + "requires-bazel-9", + ], + targets = [":compiler_capabilities"], +) diff --git a/tests/map_directory/Kbuild b/tests/map_directory/Kbuild new file mode 100644 index 00000000..e1e8581f --- /dev/null +++ b/tests/map_directory/Kbuild @@ -0,0 +1,4 @@ +obj-$(CONFIG_MAP_DIRECTORY_CC_SUPPORTED) += supported.o +obj-$(CONFIG_MAP_DIRECTORY_CC_UNSUPPORTED) += unsupported.o + +CFLAGS_supported.o += -fno-omit-frame-pointer diff --git a/tests/map_directory/Kconfig b/tests/map_directory/Kconfig new file mode 100644 index 00000000..349dfbcb --- /dev/null +++ b/tests/map_directory/Kconfig @@ -0,0 +1,20 @@ +mainmenu "map_directory compiler capability fixture" + +if-success = $(shell,{ $(1); } >/dev/null 2>&1 && echo "$(2)" || echo "$(3)") +success = $(if-success,$(1),y,n) +cc-option = $(success,$(CC) -Werror $(CLANG_FLAGS) $(1) -c -x c /dev/null -o /dev/null) + +config 64BIT + def_bool y + +config X86 + def_bool 64BIT + +config X86_64 + def_bool X86 && 64BIT + +config MAP_DIRECTORY_CC_SUPPORTED + def_bool $(cc-option,-fno-omit-frame-pointer) + +config MAP_DIRECTORY_CC_UNSUPPORTED + def_bool $(cc-option,-fno-linux-bzl-map-directory-spike) diff --git a/tests/map_directory/base.config b/tests/map_directory/base.config new file mode 100644 index 00000000..57ea5ac7 --- /dev/null +++ b/tests/map_directory/base.config @@ -0,0 +1,2 @@ +# The target profile supplies immutable x86_64 ABI values. Compiler capability +# symbols are intentionally left for Kconfig's real cc-option probes. diff --git a/tests/map_directory/include/linux/compiler-version.h b/tests/map_directory/include/linux/compiler-version.h new file mode 100644 index 00000000..b0f1de1f --- /dev/null +++ b/tests/map_directory/include/linux/compiler-version.h @@ -0,0 +1 @@ +/* Forced kernel compiler-version preinclude for the compact source scanner. */ diff --git a/tests/map_directory/include/linux/compiler_types.h b/tests/map_directory/include/linux/compiler_types.h new file mode 100644 index 00000000..30ca56c0 --- /dev/null +++ b/tests/map_directory/include/linux/compiler_types.h @@ -0,0 +1 @@ +/* Forced kernel compiler types preinclude for the compact source scanner. */ diff --git a/tests/map_directory/include/linux/kconfig.h b/tests/map_directory/include/linux/kconfig.h new file mode 100644 index 00000000..e3090264 --- /dev/null +++ b/tests/map_directory/include/linux/kconfig.h @@ -0,0 +1 @@ +/* Forced kernel Kconfig preinclude for the compact source scanner. */ diff --git a/tests/map_directory/supported.c b/tests/map_directory/supported.c new file mode 100644 index 00000000..9a2e5e70 --- /dev/null +++ b/tests/map_directory/supported.c @@ -0,0 +1,4 @@ +int map_directory_selected(void) +{ + return 42; +} diff --git a/tests/map_directory/unsupported.c b/tests/map_directory/unsupported.c new file mode 100644 index 00000000..85067b3d --- /dev/null +++ b/tests/map_directory/unsupported.c @@ -0,0 +1 @@ +#error "the unsupported compiler capability must not select this source" diff --git a/tests/map_directory/validator.go b/tests/map_directory/validator.go new file mode 100644 index 00000000..36cf1c7c --- /dev/null +++ b/tests/map_directory/validator.go @@ -0,0 +1,149 @@ +package main + +import ( + "debug/elf" + "flag" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" +) + +var probeMarkerPattern = regexp.MustCompile(`^v1/probe/sha256-[0-9a-f]{64}$`) + +func treeFiles(root string) ([]string, error) { + var files []string + err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() { + return nil + } + relative, err := filepath.Rel(root, path) + if err != nil { + return err + } + files = append(files, filepath.ToSlash(relative)) + return nil + }) + if err != nil { + return nil, err + } + sort.Strings(files) + return files, nil +} + +func validatePlan(root string) error { + files, err := treeFiles(root) + if err != nil { + return fmt.Errorf("walk action plan: %w", err) + } + var probes, sources, compiles []string + for _, path := range files { + switch { + case strings.HasPrefix(path, "v1/probe/"): + probes = append(probes, path) + case strings.HasPrefix(path, "v1/source/"): + sources = append(sources, path) + case strings.HasPrefix(path, "v1/compile/"): + compiles = append(compiles, path) + default: + return fmt.Errorf("unexpected action-plan marker %q", path) + } + } + if len(probes) != 1 || !probeMarkerPattern.MatchString(probes[0]) { + return fmt.Errorf("measured compiler probe markers = %q, want one sha256 marker", probes) + } + wantSources := []string{ + "include/linux/compiler-version.h", + "include/linux/compiler_types.h", + "include/linux/kconfig.h", + "supported.c", + } + if len(sources) != len(wantSources) { + return fmt.Errorf("selected source markers = %q, want %q", sources, wantSources) + } + for _, want := range wantSources { + found := false + for _, source := range sources { + if strings.HasSuffix(source, "/"+want) { + found = true + break + } + } + if !found { + return fmt.Errorf("selected source markers = %q, missing %q", sources, want) + } + } + if len(compiles) != 1 || !strings.HasSuffix(compiles[0], "/supported.o.json") { + return fmt.Errorf("compile markers = %q, want only supported.o.json", compiles) + } + for _, path := range files { + if strings.Contains(path, "unsupported") { + return fmt.Errorf("unsupported compiler branch appeared in action plan as %q", path) + } + } + return nil +} + +func validateObject(root string) error { + files, err := treeFiles(root) + if err != nil { + return fmt.Errorf("walk mapped objects: %w", err) + } + if len(files) != 1 || !strings.HasSuffix(files[0], "/supported.o") { + return fmt.Errorf("mapped objects = %q, want exactly supported.o", files) + } + objectPath := filepath.Join(root, filepath.FromSlash(files[0])) + object, err := elf.Open(objectPath) + if err != nil { + return fmt.Errorf("open mapped object %q: %w", files[0], err) + } + defer object.Close() + if object.Type != elf.ET_REL { + return fmt.Errorf("mapped object type = %s, want ET_REL", object.Type) + } + if object.Machine != elf.EM_X86_64 { + return fmt.Errorf("mapped object machine = %s, want EM_X86_64", object.Machine) + } + symbols, err := object.Symbols() + if err != nil { + return fmt.Errorf("read mapped object symbols: %w", err) + } + for _, symbol := range symbols { + if symbol.Name == "map_directory_selected" { + return nil + } + } + return fmt.Errorf("mapped object does not define map_directory_selected") +} + +func run() error { + plan := flag.String("plan", "", "action-plan tree") + objects := flag.String("objects", "", "mapped object tree") + out := flag.String("out", "", "validation stamp") + flag.Parse() + if *plan == "" || *objects == "" || *out == "" { + return fmt.Errorf("-plan, -objects, and -out are required") + } + if err := validatePlan(*plan); err != nil { + return err + } + if err := validateObject(*objects); err != nil { + return err + } + if err := os.WriteFile(*out, []byte("map_directory compiler capability spike passed\n"), 0o644); err != nil { + return fmt.Errorf("write validation stamp: %w", err) + } + return nil +} + +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} From 67d5da893be9aac7868a1c61ab0e1df8cfc9ad79 Mon Sep 17 00:00:00 2001 From: fionera Date: Wed, 12 Aug 2026 04:29:39 +0000 Subject: [PATCH 03/46] kconfig: measure selected C/C++ toolchain capabilities --- .github/workflows/ci.yml | 3 + MODULE.bazel | 26 + MODULE.bazel.lock | 47 +- internal/cmd/kconfig_parse/main.go | 70 +- internal/cmd/kconfig_parse/main_test.go | 75 ++ internal/cmd/mapdirectoryrecipe/BUILD.bazel | 22 + internal/cmd/mapdirectoryrecipe/main.go | 144 +++ internal/cmd/mapdirectoryrecipe/main_test.go | 83 ++ internal/kconfig/BUILD.bazel | 5 +- internal/kconfig/compact_action_plan.go | 3 + internal/kconfig/compact_action_plan_test.go | 7 + internal/kconfig/probe.go | 400 +++++-- internal/kconfig/tool_probe.go | 965 ++++++++++++++-- internal/kconfig/tool_probe_test.go | 1058 +++++++++++++++++- internal/map_directory_kconfig.bzl | 566 +++++++++- tests/map_directory/BUILD.bazel | 136 ++- tests/map_directory/Kbuild | 6 +- tests/map_directory/Kconfig | 64 ++ tests/map_directory/clang_selected.c | 8 + tests/map_directory/gcc_selected.c | 12 + tests/map_directory/required_local_header.h | 6 + tests/map_directory/supported.c | 8 +- tests/map_directory/upstream_validator.go | 150 +++ tests/map_directory/validator.go | 246 +++- 24 files changed, 3801 insertions(+), 309 deletions(-) create mode 100644 internal/cmd/mapdirectoryrecipe/BUILD.bazel create mode 100644 internal/cmd/mapdirectoryrecipe/main.go create mode 100644 internal/cmd/mapdirectoryrecipe/main_test.go create mode 100644 tests/map_directory/clang_selected.c create mode 100644 tests/map_directory/gcc_selected.c create mode 100644 tests/map_directory/required_local_header.h create mode 100644 tests/map_directory/upstream_validator.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5ae5b7f0..177f9076 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,6 +55,9 @@ jobs: targets+=( //internal/tests:path_mapping_test //tests/map_directory:compiler_capabilities_e2e_test + //tests/map_directory:distinct_compiler_plan_identities_e2e_test + //tests/map_directory:gcc_compiler_capabilities_e2e_test + //tests/map_directory:upstream_gcc_kconfig_e2e_test ) path_mapping_args+=("${BAZEL_PATH_MAPPING}") fi diff --git a/MODULE.bazel b/MODULE.bazel index 7d70a301..57d092ff 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -6,6 +6,7 @@ bazel_dep(name = "bazel_lib", version = "3.2.2") bazel_dep(name = "bazel_skylib", version = "1.9.0") bazel_dep(name = "buildifier_prebuilt", version = "8.2.1.1", dev_dependency = True) +bazel_dep(name = "gcc_toolchain", version = "0.12.0", dev_dependency = True) bazel_dep(name = "llvm", version = "0.8.14") bazel_dep(name = "elfutils", version = "0.195") @@ -47,10 +48,35 @@ use_repo(bindgen_toolchains, "rules_rust_bindgen") tar_toolchains = use_extension("@tar.bzl//tar:extensions.bzl", "toolchains", dev_dependency = True) use_repo(tar_toolchains, "bsd_tar_toolchains") +map_directory_gcc_toolchains = use_extension( + "@gcc_toolchain//toolchain:module_extensions.bzl", + "gcc_toolchains", + dev_dependency = True, +) +map_directory_gcc_toolchains.toolchain( + name = "map_directory_gcc_x86_64", + enable_fortran = False, + gcc_version = "15.2.0", + target_arch = "x86_64", +) +use_repo(map_directory_gcc_toolchains, "map_directory_gcc_x86_64") + +map_directory_linux_source_repository = use_repo_rule( + "//:linux.bzl", + "linux_source_repository", +) + +map_directory_linux_source_repository( + name = "map_directory_linux_6_18_39", + dev_dependency = True, + version = "6.18.39", +) + register_toolchains( "@default_rust_toolchains//:all", "@rules_rust_bindgen//:all", "@bsd_tar_toolchains//:all", + "//tests/map_directory:gcc_cc_toolchain", "@llvm//toolchain:all", dev_dependency = True, ) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index bf635a4a..590104a6 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -50,7 +50,8 @@ "https://bcr.bazel.build/modules/bazel_features/1.9.1/MODULE.bazel": "8f679097876a9b609ad1f60249c49d68bfab783dd9be012faf9d82547b14815a", "https://bcr.bazel.build/modules/bazel_lib/3.0.0/MODULE.bazel": "22b70b80ac89ad3f3772526cd9feee2fa412c2b01933fea7ed13238a448d370d", "https://bcr.bazel.build/modules/bazel_lib/3.2.2/MODULE.bazel": "e2c890c8a515d6bca9c66d47718aa9e44b458fde64ec7204b8030bf2d349058c", - "https://bcr.bazel.build/modules/bazel_lib/3.2.2/source.json": "9e84e115c20e14652c5c21401ae85ff4daa8702e265b5c0b3bf89353f17aa212", + "https://bcr.bazel.build/modules/bazel_lib/3.3.1/MODULE.bazel": "732a0d516cf6400d9b3136e4356258aef1bf91de8d5240f87f0112f098920c1d", + "https://bcr.bazel.build/modules/bazel_lib/3.3.1/source.json": "8e5175d7b4125a39b8941d01e38039934d058e03804f46a2b8fd7ae6316b1ce2", "https://bcr.bazel.build/modules/bazel_skylib/1.0.3/MODULE.bazel": "bcb0fd896384802d1ad283b4e4eb4d718eebd8cb820b0a2c3a347fb971afd9d8", "https://bcr.bazel.build/modules/bazel_skylib/1.1.1/MODULE.bazel": "1add3e7d93ff2e6998f9e118022c84d163917d912f5afafb3058e3d2f1545b5e", "https://bcr.bazel.build/modules/bazel_skylib/1.2.0/MODULE.bazel": "44fe84260e454ed94ad326352a698422dbe372b21a1ac9f3eab76eb531223686", @@ -83,6 +84,8 @@ "https://bcr.bazel.build/modules/gazelle/0.36.0/MODULE.bazel": "e375d5d6e9a6ca59b0cb38b0540bc9a05b6aa926d322f2de268ad267a2ee74c0", "https://bcr.bazel.build/modules/gazelle/0.51.3/MODULE.bazel": "618a729142f66de1e2cb776d026413763be5b80d5e3d29ffb9d3d90c5defde90", "https://bcr.bazel.build/modules/gazelle/0.51.3/source.json": "fbe5312a01fb4a2a58caff4a0d40dcf384b6f0bda75e85546663360da1d7538a", + "https://bcr.bazel.build/modules/gcc_toolchain/0.12.0/MODULE.bazel": "0f575f5136b738c6a47ed5198b365bf274fedf9283ea3377189d4ab62a118959", + "https://bcr.bazel.build/modules/gcc_toolchain/0.12.0/source.json": "40f4663ce767e406c57c6de91dd0ffb8a87c12337a8fdc684c664f88e03821a2", "https://bcr.bazel.build/modules/google_benchmark/1.8.2/MODULE.bazel": "a70cf1bba851000ba93b58ae2f6d76490a9feb74192e57ab8e8ff13c34ec50cb", "https://bcr.bazel.build/modules/googletest/1.11.0/MODULE.bazel": "3a83f095183f66345ca86aa13c58b59f9f94a2f81999c093d4eeaa2d262d12f4", "https://bcr.bazel.build/modules/googletest/1.14.0.bcr.1/MODULE.bazel": "22c31a561553727960057361aa33bf20fb2e98584bc4fec007906e27053f80c6", @@ -272,6 +275,48 @@ }, "selectedYankedVersions": {}, "moduleExtensions": { + "@@gcc_toolchain+//:internal.bzl%non_bazel_dependencies": { + "general": { + "bzlTransitiveDigest": "q7o2f2hyvgWoZzlcLHt6NQcltO37YFhGTefWaSqCJiM=", + "usagesDigest": "13mSQ09nHZ81WiU4i3SNGXBI5svRCTTyl8M9oydMMbI=", + "recordedInputs": [ + "REPO_MAPPING:gcc_toolchain+,bazel_tools bazel_tools", + "REPO_MAPPING:gcc_toolchain+,lapack gcc_toolchain++non_bazel_dependencies+lapack" + ], + "generatedRepoSpecs": { + "openssl": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", + "attributes": { + "build_file_content": "filegroup(\n name = \"srcs\",\n srcs = glob(\n include = [\"**\"],\n exclude = [\"**/* *\"],\n ),\n visibility = [\"//visibility:public\"],\n)\n", + "sha256": "40dceb51a4f6a5275bde0e6bf20ef4b91bfc32ed57c0552e2e8e15463372b17a", + "strip_prefix": "openssl-1.1.1n", + "url": "https://www.openssl.org/source/openssl-1.1.1n.tar.gz" + } + }, + "lapack": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", + "attributes": { + "build_file_content": "filegroup(\n name = \"srcs\",\n srcs = glob(\n include = [\"**\"],\n exclude = [\"**/* *\"],\n ),\n visibility = [\"//visibility:public\"],\n)\n", + "patch_cmds": [ + "cat > make.inc < %q", recipe.Source, recipe.Object) + } + + var args []string + foundSource := false + foundOutput := false + foundRecipe := false + for _, argument := range opts.actionArgs { + if argument == compileRecipeSentinel { + if foundRecipe { + return errors.New("compile action repeats its recipe-flags marker") + } + foundRecipe = true + args = append(args, recipe.Flags...) + continue + } + if strings.Contains(argument, compileSourceSentinel) { + foundSource = true + argument = strings.ReplaceAll(argument, compileSourceSentinel, opts.source) + } + if strings.Contains(argument, compileOutputSentinel) { + foundOutput = true + argument = strings.ReplaceAll(argument, compileOutputSentinel, opts.output) + } + args = append(args, argument) + } + if !foundSource || !foundOutput || !foundRecipe { + return fmt.Errorf("compile action markers: source=%t output=%t recipe=%t; want all true", foundSource, foundOutput, foundRecipe) + } + command := exec.Command(opts.compiler, args...) + command.Env = os.Environ() + command.Stdout = os.Stdout + command.Stderr = os.Stderr + if err := command.Run(); err != nil { + return fmt.Errorf("compile recipe: %w", err) + } + return nil +} + +func main() { + var actionArgs repeatedFlag + opts := recipeOptions{} + flag.StringVar(&opts.recipe, "recipe", "", "compact action-plan recipe JSON") + flag.StringVar(&opts.compiler, "compiler", "", "selected C compiler") + flag.StringVar(&opts.source, "source", "", "declared primary source input") + flag.StringVar(&opts.output, "output", "", "declared object output") + flag.StringVar(&opts.expectedSource, "expected_source", "", "canonical source path encoded by the plan") + flag.StringVar(&opts.expectedObject, "expected_object", "", "object path encoded by the plan") + flag.StringVar(&opts.expectedID, "expected_content_id", "", "content ID encoded by the plan") + flag.Var(&actionArgs, "action_arg", "selected CcToolchain compile action argument (repeatable)") + flag.Parse() + opts.actionArgs = actionArgs + if flag.NArg() != 0 { + fmt.Fprintln(os.Stderr, "mapdirectoryrecipe: positional arguments are not supported") + os.Exit(2) + } + if err := runRecipe(opts); err != nil { + fmt.Fprintf(os.Stderr, "mapdirectoryrecipe: %v\n", err) + os.Exit(1) + } +} diff --git a/internal/cmd/mapdirectoryrecipe/main_test.go b/internal/cmd/mapdirectoryrecipe/main_test.go new file mode 100644 index 00000000..00219e1e --- /dev/null +++ b/internal/cmd/mapdirectoryrecipe/main_test.go @@ -0,0 +1,83 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/hermeticbuild/linux.bzl/internal/kconfig" +) + +func TestRunRecipeReplaysFlags(t *testing.T) { + temp := t.TempDir() + recipePath := filepath.Join(temp, "recipe.json") + recipe := kconfig.CompactObjectVariant{ + ContentID: strings.Repeat("a", 64), + Object: "selected.o", + Source: "selected.c", + Mode: "y", + Flags: []string{"-DRECIPE_REPLAYED=1"}, + } + data, err := json.Marshal(recipe) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(recipePath, data, 0o644); err != nil { + t.Fatal(err) + } + compiler := filepath.Join(temp, "compiler") + log := filepath.Join(temp, "argv") + script := "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$RECIPE_TEST_LOG\"\n" + if err := os.WriteFile(compiler, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("RECIPE_TEST_LOG", log) + err = runRecipe(recipeOptions{ + recipe: recipePath, compiler: compiler, + source: filepath.Join(temp, "selected.c"), output: filepath.Join(temp, "selected.o"), + expectedSource: "selected.c", expectedObject: "selected.o", expectedID: recipe.ContentID, + actionArgs: []string{ + "--target=x86_64-linux-gnu", + compileRecipeSentinel, + "-c", + compileSourceSentinel, + "-o", + compileOutputSentinel, + }, + }) + if err != nil { + t.Fatalf("runRecipe() failed: %v", err) + } + got, err := os.ReadFile(log) + if err != nil { + t.Fatal(err) + } + want := "--target=x86_64-linux-gnu\n-DRECIPE_REPLAYED=1\n-c\n" + filepath.Join(temp, "selected.c") + "\n-o\n" + filepath.Join(temp, "selected.o") + "\n" + if string(got) != want { + t.Fatalf("compiler argv = %q, want %q", got, want) + } +} + +func TestRunRecipeRejectsPlanMismatch(t *testing.T) { + temp := t.TempDir() + recipePath := filepath.Join(temp, "recipe.json") + recipe := kconfig.CompactObjectVariant{ + ContentID: strings.Repeat("a", 64), Object: "selected.o", Source: "selected.c", Mode: "y", + } + data, err := json.Marshal(recipe) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(recipePath, data, 0o644); err != nil { + t.Fatal(err) + } + err = runRecipe(recipeOptions{ + recipe: recipePath, compiler: "/unused", source: "/unused", output: "/unused", + expectedSource: "other.c", expectedObject: recipe.Object, expectedID: recipe.ContentID, + }) + if err == nil || !strings.Contains(err.Error(), "recipe source") { + t.Fatalf("runRecipe() error = %v, want source mismatch", err) + } +} diff --git a/internal/kconfig/BUILD.bazel b/internal/kconfig/BUILD.bazel index b6f07a69..f984d4fc 100644 --- a/internal/kconfig/BUILD.bazel +++ b/internal/kconfig/BUILD.bazel @@ -28,7 +28,10 @@ go_library( "util.go", ], importpath = "github.com/hermeticbuild/linux.bzl/internal/kconfig", - visibility = ["//internal:__subpackages__"], + visibility = [ + "//internal:__subpackages__", + "//tests/map_directory:__pkg__", + ], deps = [ "//internal/kconfig/buildgen", "@com_github_bazelbuild_buildtools//build", diff --git a/internal/kconfig/compact_action_plan.go b/internal/kconfig/compact_action_plan.go index 474d7204..d0913c92 100644 --- a/internal/kconfig/compact_action_plan.go +++ b/internal/kconfig/compact_action_plan.go @@ -243,6 +243,9 @@ func validateCompactActionPlanVariant(variant CompactObjectVariant) error { if len(variant.Deps) != 0 { return fmt.Errorf("object %q has unsupported generated-object dependencies", variant.Object) } + if len(variant.RemoveFlags) != 0 { + return fmt.Errorf("object %q has unsupported Kbuild remove flags", variant.Object) + } if compactGroupedSpecialObjects[variant.Object] || strings.HasSuffix(variant.Object, ".asn1.o") || strings.HasSuffix(variant.Object, ".pi.o") || diff --git a/internal/kconfig/compact_action_plan_test.go b/internal/kconfig/compact_action_plan_test.go index 5fac7827..1829df38 100644 --- a/internal/kconfig/compact_action_plan_test.go +++ b/internal/kconfig/compact_action_plan_test.go @@ -144,6 +144,13 @@ func TestWriteCompactActionPlanRejectsUnsupportedMetadata(t *testing.T) { }, want: "unsupported generated-object dependencies", }, + { + name: "remove flags", + mutate: func(_ *CompactMetadata, variant *CompactObjectVariant) { + variant.RemoveFlags = []string{"-Werror"} + }, + want: "unsupported Kbuild remove flags", + }, { name: "assembly source", mutate: func(_ *CompactMetadata, variant *CompactObjectVariant) { diff --git a/internal/kconfig/probe.go b/internal/kconfig/probe.go index 006082b4..1df90f17 100644 --- a/internal/kconfig/probe.go +++ b/internal/kconfig/probe.go @@ -51,7 +51,7 @@ func LinuxProbeShell( }).run, nil } -// LinuxProbeShellWithTools uses actual integrity-pinned LLVM tools for +// LinuxProbeShellWithTools uses actual integrity-pinned compiler tools for // capability and version probes while retaining the small set of pure shell // expressions needed by Kconfig.include. Probe commands are parsed and mapped // to direct argv execution; no command shell is used. @@ -81,6 +81,52 @@ type linuxProbeShell struct { toolProbe *LinuxToolProbe } +func (s *linuxProbeShell) compilerToolName() string { + if s.toolProbe != nil { + return s.toolProbe.compilerToolName() + } + return "clang" +} + +func (s *linuxProbeShell) clangFlags() string { + if s.toolProbe != nil { + return s.toolProbe.ClangFlags() + } + return "-fintegrated-as" +} + +func (s *linuxProbeShell) isCompilerToken(field string) bool { + field = strings.Trim(field, `"'`) + if field == "$CC" || field == "$(CC)" { + return true + } + if s.toolProbe != nil { + return probeToolValueMatches(field, s.toolProbe.compilerPath) + } + return linuxProbeToolName(field) == s.compilerToolName() +} + +func (s *linuxProbeShell) linkerToolName() string { + if s.toolProbe != nil { + return s.toolProbe.linkerToolName() + } + return "ld.lld" +} + +func (s *linuxProbeShell) isAssemblerVersionScript(command string) bool { + args, ok := linuxProbeScriptArgs(command, "as-version.sh") + if !ok || len(args) == 0 || !s.isCompilerToken(args[0]) { + return false + } + if s.toolProbe == nil { + return len(args) == 2 && args[1] == "-fintegrated-as" + } + if s.toolProbe.compilerFamily == "clang" { + return len(args) == 2 && args[1] == s.toolProbe.ClangFlags() + } + return len(args) == 1 +} + func (s *linuxProbeShell) run(ctx context.Context, command string) (string, error) { if err := ctx.Err(); err != nil { return "", err @@ -96,26 +142,29 @@ func (s *linuxProbeShell) run(ctx context.Context, command string) (string, erro } return match[3], nil } - return s.output(command) + return s.output(ctx, command) } -func (s *linuxProbeShell) output(command string) (string, error) { +func (s *linuxProbeShell) output(ctx context.Context, command string) (string, error) { switch { - case isKnownLinuxProbeScript(command, "cc-version.sh", "clang"): + case s.isCompilerVersionScript(command): if s.toolProbe != nil { - return fmt.Sprintf("Clang %d", s.toolProbe.clangCode), nil + return fmt.Sprintf("%s %d", s.toolProbe.compilerName, s.toolProbe.compilerCode), nil } return fmt.Sprintf("%s %d", linuxProbeCCName, linuxProbeCCVersion), nil - case isLinuxProbeToolVersionCommand(command, "clang"): + case s.isCompilerVersionCommand(command): if s.toolProbe != nil { - return s.toolProbe.clangVersion, nil + return s.toolProbe.compilerVersion, nil } return linuxProbeCCVersionText, nil - case isKnownLinuxProbeScript(command, "as-version.sh", "clang", "-fintegrated-as"): + case s.isAssemblerVersionScript(command): + if s.toolProbe != nil { + return fmt.Sprintf("%s %d", s.toolProbe.assemblerName, s.toolProbe.assemblerCode), nil + } return fmt.Sprintf("%s %d", linuxProbeASName, linuxProbeASVersion), nil - case isKnownLinuxProbeScript(command, "ld-version.sh", "ld.lld"): + case s.isLinkerVersionScript(command): if s.toolProbe != nil { - return fmt.Sprintf("LLD %d", s.toolProbe.lldCode), nil + return fmt.Sprintf("%s %d", s.toolProbe.linkerName, s.toolProbe.linkerCode), nil } return fmt.Sprintf("%s %d", linuxProbeLDName, linuxProbeLDVersion), nil case isKnownLinuxProbeScript(command, "pahole-version.sh", "pahole"): @@ -126,7 +175,10 @@ func (s *linuxProbeShell) output(command string) (string, error) { return strconv.Itoa(s.rustcLLVMVersion), nil case isKnownBindgenVersionCommand(command): return linuxProbeBindgenVersion, nil - case isClangPrintPluginCommand(command): + case s.isCompilerPrintPluginCommand(command): + if s.toolProbe != nil { + return s.toolProbe.compilerPrintFileName(ctx, "plugin") + } return "plugin", nil case strings.HasPrefix(command, "set -- "): return shellSetEcho(command) @@ -137,33 +189,85 @@ func (s *linuxProbeShell) output(command string) (string, error) { } } +func (s *linuxProbeShell) isCompilerVersionScript(command string) bool { + args, ok := linuxProbeScriptArgs(command, "cc-version.sh") + return ok && len(args) == 1 && s.isCompilerToken(args[0]) +} + +func (s *linuxProbeShell) isCompilerVersionCommand(command string) bool { + fields := strings.Fields(command) + return len(fields) == 2 && s.isCompilerToken(fields[0]) && fields[1] == "--version" +} + +func (s *linuxProbeShell) isLinkerVersionScript(command string) bool { + args, ok := linuxProbeScriptArgs(command, "ld-version.sh") + if !ok || len(args) != 1 { + return false + } + if s.toolProbe != nil { + return probeToolValueMatches(args[0], s.toolProbe.linkerPath) + } + return linuxProbeToolName(args[0]) == s.linkerToolName() +} + func (s *linuxProbeShell) commandSucceeds(ctx context.Context, command string) (bool, error) { command = strings.TrimSpace(command) switch { case strings.HasPrefix(command, "command -v "): return s.commandExists(command) case strings.HasPrefix(command, "test "): - return shellTest(strings.TrimSpace(strings.TrimPrefix(command, "test "))) + return s.shellTest(ctx, strings.TrimSpace(strings.TrimPrefix(command, "test "))) case isKnownRustAvailableProbe(command): return true, nil - case isKnownCCCanLinkProbe(command): - return false, nil - case isKnownStackProtectorProbe(command): - return true, nil - case isKnownRELRProbe(command): - return true, nil - case strings.Contains(command, " --help | head -n 1 | grep -qi llvm"): - if strings.Contains(command, "llvm-nm") || strings.Contains(command, "llvm-ar") { - return true, nil - } - return false, s.unsupportedCommand(command) - case strings.Contains(command, "llvm-objcopy --version | head -n1 | grep -qv llvm"): - return false, nil case strings.Contains(command, " --crate-type=rlib "): return true, nil case command == `python3 -c "import lxml"`: return false, nil } + if args, recognized, err := s.ccCanLinkProbeArgs(command); recognized || err != nil { + if err != nil || s.toolProbe == nil { + return false, err + } + return s.toolProbe.CanLink(ctx, args) + } + if bits, args, recognized, err := s.stackProtectorProbeArgs(command); recognized || err != nil { + if err != nil { + return false, err + } + if s.toolProbe == nil { + return true, nil + } + return s.toolProbe.SupportsX86StackProtector(ctx, bits, args) + } + if _, _, recognized, err := s.relrProbeTools(command); recognized || err != nil { + if err != nil { + return false, err + } + if s.toolProbe == nil { + return true, nil + } + return s.toolProbe.SupportsRELR(ctx) + } + if tool, option, needle, negate, recognized, err := s.auxiliaryToolGrepProbe(command); recognized || err != nil { + if err != nil { + return false, err + } + if s.toolProbe == nil { + isLLVM := tool == "ar" || tool == "nm" + if negate { + return !isLLVM, nil + } + return isLLVM, nil + } + contains, err := s.toolProbe.auxiliaryToolFirstLineContains(ctx, tool, option, needle) + if err != nil { + return false, err + } + if negate { + return !contains, nil + } + return contains, nil + } if supported, recognized, err := s.knownPowerPCCompilerScriptProbe(ctx, command); recognized || err != nil { return supported, err } @@ -182,12 +286,80 @@ func (s *linuxProbeShell) commandSucceeds(ctx context.Context, command string) ( return false, s.unsupportedCommand(command) } +func (s *linuxProbeShell) auxiliaryToolGrepProbe(command string) (string, string, string, bool, bool, error) { + fields := strings.Fields(command) + if len(fields) < 7 { + return "", "", "", false, false, nil + } + selected := map[string]string{} + if s.toolProbe != nil { + selected = map[string]string{ + "ar": s.toolProbe.archiverPath, + "nm": s.toolProbe.nmPath, + "objcopy": s.toolProbe.objcopyPath, + } + } else { + selected = map[string]string{"ar": "llvm-ar", "nm": "llvm-nm", "objcopy": "llvm-objcopy"} + } + tool := "" + for name, path := range selected { + if probeToolValueMatches(fields[0], path) { + tool = name + break + } + } + if tool == "" || (fields[1] != "--help" && fields[1] != "--version") || fields[2] != "|" || (fields[3] != "head" || (fields[4] != "-n" && fields[4] != "-n1")) { + return "", "", "", false, false, nil + } + grep := 5 + if fields[4] == "-n" { + if len(fields) < 8 || fields[5] != "1" || fields[6] != "|" { + return "", "", "", false, true, s.unsupportedCommand(command) + } + grep = 7 + } else if fields[5] != "|" { + return "", "", "", false, true, s.unsupportedCommand(command) + } else { + grep = 6 + } + if len(fields) != grep+3 || fields[grep] != "grep" || !strings.EqualFold(strings.Trim(fields[grep+2], `"'`), "llvm") { + return "", "", "", false, true, s.unsupportedCommand(command) + } + switch fields[grep+1] { + case "-qi": + return tool, fields[1], "llvm", false, true, nil + case "-qv": + return tool, fields[1], "llvm", true, true, nil + default: + return "", "", "", false, true, s.unsupportedCommand(command) + } +} + func (s *linuxProbeShell) commandExists(command string) (bool, error) { fields := strings.Fields(command) if len(fields) != 3 || fields[0] != "command" || fields[1] != "-v" { return false, s.unsupportedCommand(command) } - switch linuxProbeToolName(fields[2]) { + if s.toolProbe != nil { + for _, selected := range []string{ + s.toolProbe.compilerPath, + s.toolProbe.linkerPath, + s.toolProbe.archiverPath, + s.toolProbe.nmPath, + s.toolProbe.objcopyPath, + } { + if probeToolValueMatches(fields[2], selected) { + return true, nil + } + } + } else { + tool := linuxProbeToolName(fields[2]) + if tool == s.compilerToolName() || tool == s.linkerToolName() { + return true, nil + } + } + tool := linuxProbeToolName(fields[2]) + switch tool { case "clang", "ld.lld", "llvm-ar", "llvm-nm", "llvm-objcopy", "bindgen", "pahole": return true, nil case "rustc": @@ -249,7 +421,7 @@ func (s *linuxProbeShell) knownPowerPCCompilerScriptProbe(ctx context.Context, c continue } if s.architecture != "ppc64le" || len(args) != 2 || - linuxProbeToolName(args[0]) != "clang" || + !s.isCompilerToken(args[0]) || (args[1] != "-mlittle-endian" && args[1] != "-mbig-endian") { return false, true, s.unsupportedCommand(command) } @@ -283,13 +455,6 @@ func isKnownLinuxProbeScript(command, script string, expected ...string) bool { return true } -func isLinuxProbeToolVersionCommand(command, tool string) bool { - fields := strings.Fields(command) - return len(fields) == 2 && - linuxProbeToolName(fields[0]) == tool && - fields[1] == "--version" -} - func isKnownBindgenVersionCommand(command string) bool { fields := strings.Fields(command) return len(fields) == 4 && @@ -307,63 +472,76 @@ func isKnownRustAvailableProbe(command string) bool { return len(args) == 0 || (len(args) == 1 && linuxProbeToolName(args[0]) == "rustc") } -func isKnownCCCanLinkProbe(command string) bool { +func (s *linuxProbeShell) ccCanLinkProbeArgs(command string) ([]string, bool, error) { args, ok := linuxProbeScriptArgs(command, "cc-can-link.sh") - if !ok || len(args) == 0 || linuxProbeToolName(args[0]) != "clang" { - return false + if !ok { + return nil, false, nil } - for _, arg := range args[1:] { - switch arg { - case "-fintegrated-as", "-m32", "-m64", "-static": - default: - return false - } + if len(args) == 0 || !s.isCompilerToken(args[0]) { + return nil, true, s.unsupportedCommand(command) } - return true + return args[1:], true, nil } -func isKnownStackProtectorProbe(command string) bool { - for _, script := range []string{ - "gcc-x86_32-has-stack-protector.sh", - "gcc-x86_64-has-stack-protector.sh", +func (s *linuxProbeShell) stackProtectorProbeArgs(command string) (int, []string, bool, error) { + for bits, script := range map[int]string{ + 32: "gcc-x86_32-has-stack-protector.sh", + 64: "gcc-x86_64-has-stack-protector.sh", } { - if isKnownLinuxProbeScript(command, script, "clang", "-fintegrated-as") { - return true + args, ok := linuxProbeScriptArgs(command, script) + if !ok { + continue + } + if len(args) == 0 || !s.isCompilerToken(args[0]) { + return 0, nil, true, s.unsupportedCommand(command) } + return bits, args[1:], true, nil } - return false + return 0, nil, false, nil } -func isKnownRELRProbe(command string) bool { +func (s *linuxProbeShell) relrProbeTools(command string) (string, string, bool, error) { fields := strings.Fields(command) - if len(fields) != 6 || fields[0] != "env" { - return false + if len(fields) == 0 || fields[0] != "env" { + return "", "", false, nil + } + if len(fields) != 6 || !isLinuxProbeScriptPath(strings.Trim(fields[5], `"'`), "tools-support-relr.sh") { + return "", "", true, s.unsupportedCommand(command) } - want := []struct { - name string - tool string - }{ - {name: "CC", tool: "clang"}, - {name: "LD", tool: "ld.lld"}, - {name: "NM", tool: "llvm-nm"}, - {name: "OBJCOPY", tool: "llvm-objcopy"}, - } - for i, expected := range want { - assignment := strings.Trim(fields[i+1], `"'`) + values := map[string]string{} + for _, field := range fields[1:5] { + assignment := strings.Trim(field, `"'`) name, value, ok := strings.Cut(assignment, "=") - if !ok || name != expected.name || linuxProbeToolName(value) != expected.tool { - return false + if !ok || value == "" { + return "", "", true, s.unsupportedCommand(command) + } + if _, duplicate := values[name]; duplicate { + return "", "", true, s.unsupportedCommand(command) } + values[name] = value } - path := strings.Trim(fields[5], `"'`) - return isLinuxProbeScriptPath(path, "tools-support-relr.sh") + linkerMatches := linuxProbeToolName(values["LD"]) == s.linkerToolName() + if s.toolProbe != nil { + linkerMatches = probeToolValueMatches(values["LD"], s.toolProbe.linkerPath) + } + if len(values) != 4 || !s.isCompilerToken(values["CC"]) || !linkerMatches { + return "", "", true, s.unsupportedCommand(command) + } + if s.toolProbe != nil { + if !probeToolValueMatches(values["NM"], s.toolProbe.nmPath) || !probeToolValueMatches(values["OBJCOPY"], s.toolProbe.objcopyPath) { + return "", "", true, s.unsupportedCommand(command) + } + } else if linuxProbeToolName(values["NM"]) != "llvm-nm" || linuxProbeToolName(values["OBJCOPY"]) != "llvm-objcopy" { + return "", "", true, s.unsupportedCommand(command) + } + return values["NM"], values["OBJCOPY"], true, nil } func (s *linuxProbeShell) knownClangOptionProbe(ctx context.Context, command string) (bool, bool, error) { fields := strings.Fields(command) compiler := -1 for i, field := range fields { - if isLinuxProbeCompilerToken(field) { + if s.isCompilerToken(field) { compiler = i break } @@ -373,15 +551,25 @@ func (s *linuxProbeShell) knownClangOptionProbe(ctx context.Context, command str } hasNullInput := false hasCompileMode := false + preprocessOnly := false var candidate []string for i := compiler + 1; i < len(fields); i++ { field := strings.TrimSuffix(fields[i], ";") switch field { - case "-c", "-E": + case "-c": hasCompileMode = true - case "-Werror", "-fintegrated-as": + case "-E": + hasCompileMode = true + preprocessOnly = true + case "-Werror": + case "-fintegrated-as", "-fno-integrated-as": + if s.toolProbe != nil { + candidate = append(candidate, field) + } case "$CLANG_FLAGS", "$(CLANG_FLAGS)": - candidate = append(candidate, "-fintegrated-as") + if clangFlags := s.clangFlags(); clangFlags != "" { + candidate = append(candidate, clangFlags) + } case "-x", "-o": i++ case "/dev/null", "-": @@ -399,6 +587,10 @@ func (s *linuxProbeShell) knownClangOptionProbe(ctx context.Context, command str } key := normalizeLinuxProbeCandidate(candidate) if s.toolProbe != nil { + if preprocessOnly { + supported, err := s.toolProbe.SupportsPreprocessorOption(ctx, candidate) + return supported, true, err + } supported, err := s.toolProbe.SupportsOption(ctx, "cc_option", candidate, nil) return supported, true, err } @@ -485,11 +677,11 @@ func (s *linuxProbeShell) knownClangSourceProbe(ctx context.Context, command str if s.toolProbe == nil { return true, true, nil } - source, candidate, err := parseLinuxSourceProbe(command) + source, mode, candidate, err := s.parseLinuxSourceProbe(command) if err != nil { return false, true, err } - supported, err := s.toolProbe.SupportsSource(ctx, "c", candidate, source) + supported, err := s.toolProbe.SupportsSource(ctx, "c", mode, candidate, source) return supported, true, err } } @@ -506,7 +698,7 @@ func (s *linuxProbeShell) knownClangAssemblerProbe(ctx context.Context, command if s.toolProbe == nil { return true, true, nil } - source, candidate, err := parseLinuxSourceProbe(command) + source, mode, candidate, err := s.parseLinuxSourceProbe(command) if err != nil { return false, true, err } @@ -514,17 +706,17 @@ func (s *linuxProbeShell) knownClangAssemblerProbe(ctx context.Context, command if err != nil { return false, true, fmt.Errorf("invalid Linux assembler source probe: %w", err) } - supported, err := s.toolProbe.SupportsSource(ctx, "assembler-with-cpp", candidate, source) + supported, err := s.toolProbe.SupportsSource(ctx, "assembler-with-cpp", mode, candidate, source) return supported, true, err } } return false, false, nil } -func parseLinuxSourceProbe(command string) (string, []string, error) { +func (s *linuxProbeShell) parseLinuxSourceProbe(command string) (string, string, []string, error) { left, right, ok := strings.Cut(command, "|") if !ok { - return "", nil, fmt.Errorf("unsupported Linux source probe %q", command) + return "", "", nil, fmt.Errorf("unsupported Linux source probe %q", command) } left = strings.TrimSpace(left) var quoted string @@ -533,31 +725,40 @@ func parseLinuxSourceProbe(command string) (string, []string, error) { } else if strings.HasPrefix(left, `printf "%b\n" `) { quoted = strings.TrimSpace(strings.TrimPrefix(left, `printf "%b\n" `)) } else { - return "", nil, fmt.Errorf("unsupported Linux source producer %q", left) + return "", "", nil, fmt.Errorf("unsupported Linux source producer %q", left) } source, err := unquoteLinuxProbeSource(quoted) if err != nil { - return "", nil, err + return "", "", nil, err } fields := strings.Fields(strings.TrimSpace(right)) compiler := -1 for i, field := range fields { - if isLinuxProbeCompilerToken(field) { + if s.isCompilerToken(field) { compiler = i break } } if compiler < 0 { - return "", nil, fmt.Errorf("Linux source probe has no clang invocation") + return "", "", nil, fmt.Errorf("Linux source probe has no selected compiler invocation") } + mode := "" var candidate []string for i := compiler + 1; i < len(fields); i++ { field := strings.TrimSuffix(fields[i], ";") switch field { - case "-c", "-S", "-", "/dev/null": + case "-c", "-S": + if mode != "" && mode != field { + return "", "", nil, fmt.Errorf("Linux source probe has conflicting compiler modes %q and %q", mode, field) + } + mode = field + continue + case "-", "/dev/null": continue case "$CLANG_FLAGS", "$(CLANG_FLAGS)": - candidate = append(candidate, "-fintegrated-as") + if clangFlags := s.clangFlags(); clangFlags != "" { + candidate = append(candidate, clangFlags) + } continue case "-x", "-o": i++ @@ -565,7 +766,10 @@ func parseLinuxSourceProbe(command string) (string, []string, error) { } candidate = append(candidate, field) } - return source, candidate, nil + if mode == "" { + return "", "", nil, fmt.Errorf("Linux source probe has no compile mode") + } + return source, mode, candidate, nil } func unquoteLinuxProbeSource(quoted string) (string, error) { @@ -610,14 +814,9 @@ func unquoteLinuxProbeSource(quoted string) (string, error) { return out.String(), nil } -func isLinuxProbeCompilerToken(field string) bool { - field = strings.Trim(field, `"'`) - return linuxProbeToolName(field) == "clang" || field == "$CC" || field == "$(CC)" -} - func (s *linuxProbeShell) knownLLDOptionProbe(ctx context.Context, command string) (bool, bool, error) { fields := strings.Fields(command) - if len(fields) < 3 || linuxProbeToolName(fields[0]) != "ld.lld" || fields[1] != "-v" { + if len(fields) < 3 || linuxProbeToolName(fields[0]) != s.linkerToolName() || fields[1] != "-v" { return false, false, nil } candidate := strings.Join(fields[2:], " ") @@ -633,6 +832,14 @@ func (s *linuxProbeShell) knownLLDOptionProbe(ctx context.Context, command strin } func (s *linuxProbeShell) unsupportedCommand(command string) error { + if s.toolProbe != nil { + return fmt.Errorf( + "unsupported measured %s Linux Kconfig probe command for architecture %q: %q", + s.toolProbe.compilerName, + s.architecture, + command, + ) + } return fmt.Errorf( "unsupported Clang 22.1.8 Linux Kconfig probe command for architecture %q: %q", s.architecture, @@ -673,13 +880,16 @@ func shellExpr(command string) (string, error) { return "", fmt.Errorf("unsupported expr command %q", command) } -func shellTest(expr string) (bool, error) { +func (s *linuxProbeShell) shellTest(ctx context.Context, expr string) (bool, error) { if value, ok := strings.CutPrefix(expr, "-z "); ok { return unquoteShell(value) == "", nil } if value, ok := strings.CutPrefix(expr, "-e "); ok { path := unquoteShell(value) if strings.HasSuffix(path, "include/plugin-version.h") { + if s.toolProbe != nil { + return s.toolProbe.compilerPluginHeaderExists(ctx, path) + } return false, nil } return false, fmt.Errorf("unsupported Linux Kconfig test path %q", path) @@ -725,10 +935,10 @@ func normalizeLinuxProbeArchitecture(value string) (string, error) { } } -func isClangPrintPluginCommand(command string) bool { +func (s *linuxProbeShell) isCompilerPrintPluginCommand(command string) bool { fields := strings.Fields(command) return len(fields) == 2 && - linuxProbeToolName(fields[0]) == "clang" && + s.isCompilerToken(fields[0]) && fields[1] == "-print-file-name=plugin" } diff --git a/internal/kconfig/tool_probe.go b/internal/kconfig/tool_probe.go index d3287ce3..e0ab5d12 100644 --- a/internal/kconfig/tool_probe.go +++ b/internal/kconfig/tool_probe.go @@ -12,7 +12,6 @@ import ( "path/filepath" "regexp" "runtime" - "slices" "strconv" "strings" "sync" @@ -20,39 +19,67 @@ import ( ) const ( - linuxProbeTimeout = 20 * time.Second - linuxProbeOutputLimit = 64 << 10 + linuxProbeTimeout = 20 * time.Second + linuxProbeOutputLimit = 64 << 10 + linuxProbeMinimumLLVMVersion = 150000 + linuxProbeMinimumGCCVersion = 80100 + linuxProbeMinimumBinutilsVersion = 23000 ) -// LinuxToolProbeOptions describes integrity-pinned host tools used to answer +// LinuxToolProbeOptions describes integrity-pinned compiler tools used to answer // Kconfig and Kbuild capability probes. Tools are executed directly with argv; // probe text is never passed to a command shell. type LinuxToolProbeOptions struct { Profile string Architecture string TargetTriple string - ClangPath string - LLDPath string - TempDir string - Identity string - Timeout time.Duration - OutputLimit int + CompilerPath string + LinkerPath string + ArchiverPath string + NMPath string + ObjcopyPath string + CompilerArgs []string + // LinkerDriverArgs are the selected CcToolchain's link-action flags that + // accompany CompilerArgs only when the compiler driver performs a link. + LinkerDriverArgs []string + // DisableCCCanLink and DisableGCCPlugins make capabilities whose complete + // runtime closure is unavailable fail closed without consulting ambient + // executor files. Both default to false for existing callers. + DisableCCCanLink bool + DisableGCCPlugins bool + TempDir string + Identity string + Timeout time.Duration + OutputLimit int } // LinuxToolProbe executes and memoizes safe compiler/linker capability probes. type LinuxToolProbe struct { - profile LinuxTargetProfile - clangPath string - lldPath string - tempDir string - identity string - timeout time.Duration - outputLimit int - mu sync.Mutex - cache map[string]bool - clangVersion string - clangCode int - lldCode int + profile LinuxTargetProfile + compilerPath string + linkerPath string + archiverPath string + nmPath string + objcopyPath string + compilerArgs []string + linkerDriverArgs []string + disableCCCanLink bool + disableGCCPlugins bool + tempDir string + identity string + timeout time.Duration + outputLimit int + mu sync.Mutex + cache map[string]bool + compilerFamily string + compilerName string + compilerVersion string + compilerCode int + assemblerName string + assemblerCode int + linkerName string + linkerVersion string + linkerCode int } func NewLinuxToolProbe(opts LinuxToolProbeOptions) (*LinuxToolProbe, error) { @@ -63,18 +90,42 @@ func NewLinuxToolProbe(opts LinuxToolProbeOptions) (*LinuxToolProbe, error) { if err := profile.ValidateTargetIdentity(opts.Architecture, opts.TargetTriple); err != nil { return nil, err } - if opts.ClangPath == "" || opts.LLDPath == "" { - return nil, fmt.Errorf("real Linux probes require both clang and ld.lld paths") + if opts.CompilerPath == "" || opts.LinkerPath == "" || opts.ArchiverPath == "" || opts.NMPath == "" || opts.ObjcopyPath == "" { + return nil, fmt.Errorf("real Linux probes require compiler, linker, archiver, nm, and objcopy paths") } - clangPath, err := filepath.Abs(opts.ClangPath) + if err := validateCompilerPrefixArgs(opts.CompilerArgs); err != nil { + return nil, fmt.Errorf("invalid configured compiler prefix: %w", err) + } + if err := validateLinkerDriverPrefixArgs(opts.LinkerDriverArgs); err != nil { + return nil, fmt.Errorf("invalid configured linker-driver prefix: %w", err) + } + compilerPath, err := filepath.Abs(opts.CompilerPath) + if err != nil { + return nil, fmt.Errorf("resolve compiler path: %w", err) + } + linkerPath, err := filepath.Abs(opts.LinkerPath) + if err != nil { + return nil, fmt.Errorf("resolve linker path: %w", err) + } + archiverPath, err := filepath.Abs(opts.ArchiverPath) if err != nil { - return nil, fmt.Errorf("resolve clang path: %w", err) + return nil, fmt.Errorf("resolve archiver path: %w", err) } - lldPath, err := filepath.Abs(opts.LLDPath) + nmPath, err := filepath.Abs(opts.NMPath) if err != nil { - return nil, fmt.Errorf("resolve ld.lld path: %w", err) + return nil, fmt.Errorf("resolve nm path: %w", err) } - for name, path := range map[string]string{"clang": clangPath, "ld.lld": lldPath} { + objcopyPath, err := filepath.Abs(opts.ObjcopyPath) + if err != nil { + return nil, fmt.Errorf("resolve objcopy path: %w", err) + } + for name, path := range map[string]string{ + "compiler": compilerPath, + "linker": linkerPath, + "archiver": archiverPath, + "nm": nmPath, + "objcopy": objcopyPath, + } { info, statErr := os.Stat(path) if statErr != nil { return nil, fmt.Errorf("stat probe %s %q: %w", name, path, statErr) @@ -83,16 +134,14 @@ func NewLinuxToolProbe(opts LinuxToolProbeOptions) (*LinuxToolProbe, error) { return nil, fmt.Errorf("probe %s %q is not an executable file", name, path) } } - identity := opts.Identity - if identity == "" { - identity, err = toolPairIdentity(clangPath, lldPath) - if err != nil { - return nil, err - } - } p := &LinuxToolProbe{ - profile: profile, clangPath: clangPath, lldPath: lldPath, - tempDir: opts.TempDir, identity: identity, cache: map[string]bool{}, + profile: profile, compilerPath: compilerPath, linkerPath: linkerPath, + archiverPath: archiverPath, nmPath: nmPath, objcopyPath: objcopyPath, + compilerArgs: append([]string(nil), opts.CompilerArgs...), + linkerDriverArgs: append([]string(nil), opts.LinkerDriverArgs...), + disableCCCanLink: opts.DisableCCCanLink, + disableGCCPlugins: opts.DisableGCCPlugins, + tempDir: opts.TempDir, identity: opts.Identity, cache: map[string]bool{}, timeout: opts.Timeout, outputLimit: opts.OutputLimit, } if p.timeout <= 0 { @@ -103,31 +152,174 @@ func NewLinuxToolProbe(opts LinuxToolProbeOptions) (*LinuxToolProbe, error) { } ctx, cancel := context.WithTimeout(context.Background(), p.timeout) defer cancel() - clangText, err := p.run(ctx, clangPath, []string{"--version"}, nil) + // Linux's cc-version.sh identifies the compiler from predefined macros, + // not from the branding printed by --version. First use the unadorned + // version command only as a compatibility hint for the legacy implicit + // Clang target prefix, then make the configured preprocessing invocation + // authoritative below. In particular, this permits compiler wrappers + // whose own --version output does not identify the wrapped frontend. + compilerText, versionErr := p.run(ctx, compilerPath, []string{"--version"}, nil) + if versionErr != nil { + if _, ok := versionErr.(*exec.ExitError); !ok { + return nil, fmt.Errorf("read compiler version text: %w", versionErr) + } + } + if family, name, _, code, parseErr := parseCompilerVersion(compilerText); parseErr == nil { + p.compilerFamily = family + p.compilerName = name + p.compilerCode = code + } + configuredCompilerArgs := p.configuredCompilerArgs() + if len(configuredCompilerArgs) != 0 { + versionArgs := append(configuredCompilerArgs, "--version") + compilerText, versionErr = p.run(ctx, compilerPath, versionArgs, nil) + if versionErr != nil { + if _, ok := versionErr.(*exec.ExitError); !ok { + return nil, fmt.Errorf("read configured compiler version text: %w", versionErr) + } + } + } + p.compilerVersion = strings.TrimSpace(strings.SplitN(compilerText, "\n", 2)[0]) + compilerInfo, err := p.identifyConfiguredCompiler(ctx) if err != nil { - return nil, fmt.Errorf("identify clang probe tool: %w", err) + return nil, err } - p.clangVersion, p.clangCode, err = parseLLVMVersion(clangText, "clang") + p.compilerFamily, p.compilerName, p.compilerCode, err = parseCompilerMacroIdentity(compilerInfo) if err != nil { return nil, err } - if p.clangCode != linuxProbeCCVersion { - return nil, fmt.Errorf("probe clang version is %d, want pinned LLVM %d", p.clangCode, linuxProbeCCVersion) + if p.compilerFamily == "clang" && p.compilerCode < linuxProbeMinimumLLVMVersion { + return nil, fmt.Errorf("probe clang version is %d, want at least Linux 6.18 LLVM minimum %d", p.compilerCode, linuxProbeMinimumLLVMVersion) } - lldText, err := p.run(ctx, lldPath, []string{"--version"}, nil) + if p.compilerFamily == "gcc" && p.compilerCode < linuxProbeMinimumGCCVersion { + return nil, fmt.Errorf("probe GCC version is %d, want at least %d", p.compilerCode, linuxProbeMinimumGCCVersion) + } + linkerText, err := p.run(ctx, linkerPath, []string{"--version"}, nil) if err != nil { - return nil, fmt.Errorf("identify ld.lld probe tool: %w", err) + return nil, fmt.Errorf("identify linker probe tool: %w", err) } - _, p.lldCode, err = parseLLVMVersion(lldText, "LLD") + p.linkerName, p.linkerVersion, p.linkerCode, err = parseLinkerVersion(linkerText) if err != nil { return nil, err } - if p.lldCode != linuxProbeLDVersion { - return nil, fmt.Errorf("probe ld.lld version is %d, want pinned LLVM %d", p.lldCode, linuxProbeLDVersion) + switch p.linkerName { + case linuxProbeLDName: + if p.linkerCode < linuxProbeMinimumLLVMVersion { + return nil, fmt.Errorf("probe ld.lld version is %d, want at least Linux 6.18 LLVM minimum %d", p.linkerCode, linuxProbeMinimumLLVMVersion) + } + case "BFD": + if p.linkerCode < linuxProbeMinimumBinutilsVersion { + return nil, fmt.Errorf("probe GNU ld version is %d, want at least %d", p.linkerCode, linuxProbeMinimumBinutilsVersion) + } + default: + return nil, fmt.Errorf("probe linker has unsupported family %q", p.linkerName) + } + assemblerText := compilerText + integratedAssembler := false + if p.compilerFamily == "clang" { + integratedAssembler, err = p.detectClangIntegratedAssembler(ctx) + if err != nil { + return nil, err + } + } + if integratedAssembler { + p.assemblerName = linuxProbeASName + p.assemblerCode = linuxProbeASVersion + } else { + assemblerArgs := append(p.configuredCompilerArgs(), "-Wa,--version", "-c", "-x", "assembler-with-cpp", os.DevNull, "-o", os.DevNull) + assemblerText, err = p.run(ctx, compilerPath, assemblerArgs, nil) + if err != nil { + return nil, fmt.Errorf("identify assembler through compiler driver: %w", err) + } + p.assemblerName, p.assemblerCode, err = parseGNUAssemblerVersion(assemblerText) + if err != nil { + return nil, err + } + if p.assemblerCode < linuxProbeMinimumBinutilsVersion { + return nil, fmt.Errorf("probe GNU assembler version is %d, want at least %d", p.assemblerCode, linuxProbeMinimumBinutilsVersion) + } + } + archiverText, err := p.run(ctx, archiverPath, []string{"--version"}, nil) + if err != nil { + return nil, fmt.Errorf("identify archiver probe tool: %w", err) + } + nmText, err := p.run(ctx, nmPath, []string{"--version"}, nil) + if err != nil { + return nil, fmt.Errorf("identify nm probe tool: %w", err) + } + objcopyText, err := p.run(ctx, objcopyPath, []string{"--version"}, nil) + if err != nil { + return nil, fmt.Errorf("identify objcopy probe tool: %w", err) + } + if p.identity == "" { + p.identity, err = toolIdentityWithVersionLines( + []string{compilerText, compilerInfo, assemblerText, linkerText, archiverText, nmText, objcopyText}, + compilerPath, + linkerPath, + archiverPath, + nmPath, + objcopyPath, + ) + if err != nil { + return nil, err + } } + p.identity = extendToolIdentity( + p.identity, + p.profile, + p.compilerArgs, + p.linkerDriverArgs, + !p.disableCCCanLink, + !p.disableGCCPlugins, + ) return p, nil } +const linuxCompilerIdentitySource = `#if defined(__clang__) +Clang __clang_major__ __clang_minor__ __clang_patchlevel__ +#elif defined(__GNUC__) +GCC __GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__ +#else +unknown +#endif +` + +// identifyConfiguredCompiler reproduces the substantive part of Linux's +// scripts/cc-version.sh: preprocess predefined compiler macros through the +// complete configured compiler prefix. stderr is intentionally ignored just +// as cc-version.sh redirects it, while a non-zero compiler exit remains fatal. +func (p *LinuxToolProbe) identifyConfiguredCompiler(ctx context.Context) (string, error) { + args := append(p.configuredCompilerArgs(), "-E", "-P", "-x", "c", "-") + stdout, _, err := p.runSeparate(ctx, p.compilerPath, args, []byte(linuxCompilerIdentitySource)) + if err != nil { + return "", fmt.Errorf("identify configured compiler from predefined macros: %w", err) + } + return stdout, nil +} + +var clangCC1AssemblerPattern = regexp.MustCompile(`(?:^|[\s"])-cc1as(?:[\s"]|$)`) + +func (p *LinuxToolProbe) detectClangIntegratedAssembler(ctx context.Context) (bool, error) { + selected := "" + for _, arg := range p.configuredCompilerArgs() { + if arg == "-fintegrated-as" || arg == "-fno-integrated-as" { + selected = arg + } + } + if selected != "" { + return selected == "-fintegrated-as", nil + } + args := append(p.configuredCompilerArgs(), "-###", "-c", "-x", "assembler-with-cpp", os.DevNull, "-o", os.DevNull) + trace, err := p.run(ctx, p.compilerPath, args, nil) + if err != nil { + return false, fmt.Errorf("identify Clang assembler selection: %w", err) + } + if strings.TrimSpace(trace) == "" { + return false, fmt.Errorf("identify Clang assembler selection: empty -### output") + } + return clangCC1AssemblerPattern.MatchString(trace), nil +} + func probeToolModeIsExecutable(goos string, mode os.FileMode) bool { if mode.IsDir() { return false @@ -140,7 +332,85 @@ func probeToolModeIsExecutable(goos string, mode os.FileMode) bool { func (p *LinuxToolProbe) Identity() string { return p.identity } -func toolPairIdentity(paths ...string) (string, error) { +func (p *LinuxToolProbe) CompilerFamily() string { return p.compilerFamily } + +func (p *LinuxToolProbe) CompilerVersionText() string { return p.compilerVersion } + +func (p *LinuxToolProbe) ClangFlags() string { + if p.compilerFamily != "clang" { + return "" + } + if p.assemblerName == linuxProbeASName { + return "-fintegrated-as" + } + return "-fno-integrated-as" +} + +func (p *LinuxToolProbe) compilerToolName() string { + return linuxProbeToolName(p.compilerPath) +} + +func (p *LinuxToolProbe) linkerToolName() string { + return linuxProbeToolName(p.linkerPath) +} + +func (p *LinuxToolProbe) ArchiverPath() string { return p.archiverPath } + +func (p *LinuxToolProbe) NMPath() string { return p.nmPath } + +func (p *LinuxToolProbe) ObjcopyPath() string { return p.objcopyPath } + +func probeToolValueMatches(value, selectedPath string) bool { + value = strings.Trim(value, `"'`) + if value == "" { + return false + } + if absolute, err := filepath.Abs(value); err == nil && filepath.Clean(absolute) == filepath.Clean(selectedPath) { + return true + } + return !strings.ContainsAny(value, `/\\`) && linuxProbeToolName(value) == linuxProbeToolName(selectedPath) +} + +func (p *LinuxToolProbe) configuredCompilerArgs() []string { + if len(p.compilerArgs) != 0 { + return append([]string(nil), p.compilerArgs...) + } + // Before callers could pass the configured CcToolchain command line, the + // measured probe always supplied Clang's target explicitly. Preserve that + // behavior for a legacy caller probing a non-host Linux target. GCC has no + // equivalent driver option; a GCC cross compiler must encode its target in + // the selected executable or in the configured compiler prefix. + if p.compilerFamily == "clang" && !linuxProbeProfileMatchesHost(p.profile) { + return []string{"--target=" + p.profile.TargetTriple} + } + return nil +} + +func linuxProbeProfileMatchesHost(profile LinuxTargetProfile) bool { + if runtime.GOOS != "linux" { + return false + } + switch runtime.GOARCH { + case "amd64": + return profile.Name == "x86_64" + case "arm64": + return profile.Name == "aarch64" + case "arm": + return profile.Name == "armv7" + case "riscv64": + return profile.Name == "riscv64" + case "ppc64le": + return profile.Name == "ppc64le" + default: + return false + } +} + +func toolIdentity(paths ...string) (string, error) { + return toolIdentityWithVersionLines(nil, paths...) +} + +func toolIdentityWithVersionLines(versionOutputs []string, paths ...string) (string, error) { h := sha256.New() for _, path := range paths { file, err := os.Open(path) @@ -157,10 +427,106 @@ func toolPairIdentity(paths ...string) (string, error) { } h.Write([]byte{0}) } + for _, output := range versionOutputs { + line := strings.TrimSpace(strings.SplitN(output, "\n", 2)[0]) + h.Write([]byte(line)) + h.Write([]byte{0}) + } return "sha256-" + hex.EncodeToString(h.Sum(nil)), nil } +func extendToolIdentity(base string, profile LinuxTargetProfile, compilerArgs, linkerDriverArgs []string, policy ...bool) string { + allowCCCanLink := true + allowGCCPlugins := true + if len(policy) > 0 { + allowCCCanLink = policy[0] + } + if len(policy) > 1 { + allowGCCPlugins = policy[1] + } + h := sha256.New() + values := append([]string{ + "linux.bzl/measured-toolchain/v2", + base, + profile.Name, + profile.TargetTriple, + "compiler-args", + }, compilerArgs...) + values = append(values, "linker-driver-args") + values = append(values, linkerDriverArgs...) + values = append(values, + "allow-cc-can-link", strconv.FormatBool(allowCCCanLink), + "allow-gcc-plugins", strconv.FormatBool(allowGCCPlugins), + ) + for _, value := range values { + fmt.Fprintf(h, "%d:", len(value)) + h.Write([]byte(value)) + } + return "sha256-" + hex.EncodeToString(h.Sum(nil)) +} + +func validateCompilerPrefixArgs(args []string) error { + for i, arg := range args { + if err := validateProbeToken(arg); err != nil { + return fmt.Errorf("argument %d: %w", i, err) + } + if strings.HasPrefix(arg, "@") { + return fmt.Errorf("response-file argument %q is prohibited", arg) + } + switch arg { + case "-c", "-S", "-E", "-M", "-MM", "-MD", "-MMD", "-o", "--output", "-MF", "-MT", "-MQ", "-MJ", "--serialize-diagnostics", "-save-temps", "--save-temps": + return fmt.Errorf("compiler-controlled input, output, or mode argument %q is prohibited", arg) + } + for _, prefix := range []string{ + "--output=", "-MF=", "-MJ=", "--serialize-diagnostics=", "-save-temps=", "--save-temps=", + } { + if strings.HasPrefix(arg, prefix) { + return fmt.Errorf("compiler-controlled output argument %q is prohibited", arg) + } + } + } + return nil +} + +func validateLinkerDriverPrefixArgs(args []string) error { + expectOperand := "" + for i, arg := range args { + if err := validateProbeToken(arg); err != nil { + return fmt.Errorf("argument %d: %w", i, err) + } + if expectOperand != "" { + if strings.HasPrefix(arg, "-") || strings.ContainsAny(arg, `\`) { + return fmt.Errorf("unsafe %s operand %q", expectOperand, arg) + } + expectOperand = "" + continue + } + switch arg { + case "-c", "-S", "-E", "-M", "-MM", "-MD", "-MMD", "-o", "--output", "-MF", "-MT", "-MQ", "-MJ", "--serialize-diagnostics", "-save-temps", "--save-temps": + return fmt.Errorf("linker-driver-controlled input, output, or mode argument %q is prohibited", arg) + } + for _, prefix := range []string{ + "--output=", "-MF=", "-MJ=", "--serialize-diagnostics=", "-save-temps=", "--save-temps=", + } { + if strings.HasPrefix(arg, prefix) { + return fmt.Errorf("linker-driver-controlled output argument %q is prohibited", arg) + } + } + if !strings.HasPrefix(arg, "-") { + return fmt.Errorf("linker-driver input or positional argument %q is prohibited", arg) + } + if arg == "-target" || arg == "-resource-dir" { + expectOperand = arg + } + } + if expectOperand != "" { + return fmt.Errorf("missing operand for final linker-driver option %s", expectOperand) + } + return nil +} + var llvmVersionPattern = regexp.MustCompile(`(?i)(?:clang version|LLD(?: version)?) ([0-9]+)\.([0-9]+)\.([0-9]+)`) +var semanticVersionPattern = regexp.MustCompile(`([0-9]+)\.([0-9]+)(?:\.([0-9]+))?`) func parseLLVMVersion(output, tool string) (string, int, error) { line := strings.TrimSpace(strings.SplitN(output, "\n", 2)[0]) @@ -177,6 +543,85 @@ func parseLLVMVersion(output, tool string) (string, int, error) { return line, major*10000 + minor*100 + patch, nil } +func parseCompilerVersion(output string) (string, string, string, int, error) { + line := strings.TrimSpace(strings.SplitN(output, "\n", 2)[0]) + lower := strings.ToLower(line) + if strings.Contains(lower, "clang version") { + text, code, err := parseLLVMVersion(line, "clang") + return "clang", linuxProbeCCName, text, code, err + } + if strings.Contains(lower, "gcc") || strings.Contains(lower, "gnu compiler collection") { + code, err := parseLastSemanticVersion(line, "GCC") + return "gcc", "GCC", line, code, err + } + return "", "", "", 0, fmt.Errorf("probe compiler returned an unsupported version line %q", line) +} + +func parseCompilerMacroIdentity(output string) (string, string, int, error) { + fields := strings.Fields(output) + if len(fields) < 4 || (fields[0] != "Clang" && fields[0] != "GCC") { + return "", "", 0, fmt.Errorf("configured compiler returned unsupported predefined macros %q", strings.TrimSpace(output)) + } + parts := [3]int{} + for i := range parts { + value, err := strconv.Atoi(fields[i+1]) + if err != nil || value < 0 || (i != 0 && value > 99) { + return "", "", 0, fmt.Errorf("configured compiler returned invalid macro identity %q", strings.TrimSpace(output)) + } + parts[i] = value + } + if parts[0] == 0 { + return "", "", 0, fmt.Errorf("configured compiler returned invalid macro identity %q", strings.TrimSpace(output)) + } + if fields[0] == "Clang" { + return "clang", linuxProbeCCName, parts[0]*10000 + parts[1]*100 + parts[2], nil + } + return "gcc", "GCC", parts[0]*10000 + parts[1]*100 + parts[2], nil +} + +func parseLinkerVersion(output string) (string, string, int, error) { + line := strings.TrimSpace(strings.SplitN(output, "\n", 2)[0]) + if strings.Contains(strings.ToLower(line), "lld") { + text, code, err := parseLLVMVersion(line, "LLD") + return linuxProbeLDName, text, code, err + } + if strings.Contains(line, "GNU ld") { + code, err := parseLastSemanticVersion(line, "GNU ld") + return "BFD", line, code, err + } + return "", "", 0, fmt.Errorf("probe linker returned an unsupported version line %q", line) +} + +func parseGNUAssemblerVersion(output string) (string, int, error) { + for _, line := range strings.Split(output, "\n") { + line = strings.TrimSpace(line) + if !strings.Contains(line, "GNU assembler") { + continue + } + code, err := parseLastSemanticVersion(line, "GNU assembler") + return "GNU", code, err + } + return "", 0, fmt.Errorf("probe assembler returned unsupported version output %q", strings.TrimSpace(output)) +} + +func parseLastSemanticVersion(line, tool string) (int, error) { + matches := semanticVersionPattern.FindAllStringSubmatch(line, -1) + if len(matches) == 0 { + return 0, fmt.Errorf("probe %s returned an unsupported version line %q", tool, line) + } + match := matches[len(matches)-1] + major, _ := strconv.Atoi(match[1]) + minor, _ := strconv.Atoi(match[2]) + patch := 0 + if match[3] != "" { + patch, _ = strconv.Atoi(match[3]) + } + if minor > 99 || patch > 99 { + return 0, fmt.Errorf("probe %s version cannot be represented by Linux: %q", tool, line) + } + return major*10000 + minor*100 + patch, nil +} + // SupportsOption performs one controlled cc-option/as-option/ld-option probe. // A normal non-zero tool exit reports unsupported; malformed argv and tool // execution failures are errors. @@ -191,13 +636,6 @@ func (p *LinuxToolProbe) SupportsOption(ctx context.Context, kind string, candid if err != nil { return false, fmt.Errorf("invalid %s context: %w", kind, err) } - // Native CPU selection depends on the repository worker's processor, which - // is not represented in Bazel's repository or action cache keys. Keep the - // measured probe aligned with the cache-safe fixed probe policy instead of - // allowing the host running module resolution to change generated metadata. - if slices.Contains(candidate, "-march=native") { - return false, nil - } key := strings.Join([]string{ p.identity, p.profile.Name, p.profile.TargetTriple, kind, strings.Join(probeContext, "\x00"), strings.Join(candidate, "\x00"), @@ -215,7 +653,7 @@ func (p *LinuxToolProbe) SupportsOption(ctx context.Context, kind string, candid if kind == "ld_option" { args := append([]string{"-v"}, execContext...) args = append(args, candidate...) - _, err = p.run(timedCtx, p.lldPath, args, nil) + _, err = p.run(timedCtx, p.linkerPath, args, nil) } else { output, createErr := os.CreateTemp(p.tempDir, "linux-bzl-probe-*.o") if createErr != nil { @@ -231,11 +669,11 @@ func (p *LinuxToolProbe) SupportsOption(ctx context.Context, kind string, candid if kind == "as_option" { language = "assembler-with-cpp" } - args := []string{"--target=" + p.profile.TargetTriple, "-Werror"} + args := append(p.configuredCompilerArgs(), "-Werror") args = append(args, execContext...) args = append(args, candidate...) args = append(args, "-x", language, "-c", "-o", outputPath, "-") - _, err = p.run(timedCtx, p.clangPath, args, []byte("\n")) + _, err = p.run(timedCtx, p.compilerPath, args, []byte("\n")) } if err == nil { supported = true @@ -248,12 +686,43 @@ func (p *LinuxToolProbe) SupportsOption(ctx context.Context, kind string, candid return supported, nil } -// SupportsSource compiles one allowlisted Kconfig feature-test source using -// controlled language/input/output arguments. -func (p *LinuxToolProbe) SupportsSource(ctx context.Context, language string, candidate []string, source string) (bool, error) { +// SupportsPreprocessorOption performs Linux's cc-option-bit check. Unlike a +// normal cc-option, this intentionally stops after preprocessing so assembler +// availability cannot change the selected -m32/-m64 driver flag. +func (p *LinuxToolProbe) SupportsPreprocessorOption(ctx context.Context, candidate []string) (bool, error) { + if err := validateProbeCandidate("cc_option_bit", candidate); err != nil { + return false, fmt.Errorf("invalid cc_option_bit candidate: %w", err) + } + key := strings.Join([]string{ + p.identity, p.profile.Name, p.profile.TargetTriple, "cc-option-bit", + strings.Join(candidate, "\x00"), + }, "\x01") + if supported, ok := p.cachedCapability(key); ok { + return supported, nil + } + timedCtx, cancel := context.WithTimeout(ctx, p.timeout) + defer cancel() + args := append(p.configuredCompilerArgs(), "-Werror") + args = append(args, candidate...) + args = append(args, "-E", "-x", "c", os.DevNull, "-o", os.DevNull) + _, runErr := p.run(timedCtx, p.compilerPath, args, nil) + supported, err := capabilityResult(runErr) + if err != nil { + return false, err + } + p.cacheCapability(key, supported) + return supported, nil +} + +// SupportsSource runs one allowlisted Kconfig feature-test source using its +// original compile/assembly mode and controlled input/output arguments. +func (p *LinuxToolProbe) SupportsSource(ctx context.Context, language, mode string, candidate []string, source string) (bool, error) { if language != "c" && language != "assembler-with-cpp" { return false, fmt.Errorf("unsupported Linux source probe language %q", language) } + if mode != "-c" && mode != "-S" { + return false, fmt.Errorf("unsupported Linux source probe mode %q", mode) + } if len(candidate) != 0 { if err := validateProbeCandidate("source", candidate); err != nil { return false, fmt.Errorf("invalid Linux source probe candidate: %w", err) @@ -261,7 +730,7 @@ func (p *LinuxToolProbe) SupportsSource(ctx context.Context, language string, ca } digest := sha256.Sum256([]byte(source)) key := strings.Join([]string{ - p.identity, p.profile.Name, p.profile.TargetTriple, "source", language, + p.identity, p.profile.Name, p.profile.TargetTriple, "source", language, mode, strings.Join(candidate, "\x00"), hex.EncodeToString(digest[:]), }, "\x01") p.mu.Lock() @@ -282,10 +751,9 @@ func (p *LinuxToolProbe) SupportsSource(ctx context.Context, language string, ca defer os.Remove(outputPath) timedCtx, cancel := context.WithTimeout(ctx, p.timeout) defer cancel() - args := []string{"--target=" + p.profile.TargetTriple, "-Werror"} - args = append(args, candidate...) - args = append(args, "-x", language, "-c", "-o", outputPath, "-") - _, runErr := p.run(timedCtx, p.clangPath, args, []byte(source)) + args := append(p.configuredCompilerArgs(), candidate...) + args = append(args, "-x", language, mode, "-o", outputPath, "-") + _, runErr := p.run(timedCtx, p.compilerPath, args, []byte(source)) supported := runErr == nil if runErr != nil { if _, ok := runErr.(*exec.ExitError); !ok { @@ -298,6 +766,327 @@ func (p *LinuxToolProbe) SupportsSource(ctx context.Context, language string, ca return supported, nil } +const linuxCCCanLinkSource = `#include +int main(void) +{ + printf("\n"); + return 0; +} +` + +// CanLink reproduces scripts/cc-can-link.sh with a fixed input and output. +// Script arguments have already been separated from the recognized command; +// only compiler options that cannot select an input, output, or plugin are +// accepted here. +func (p *LinuxToolProbe) CanLink(ctx context.Context, scriptArgs []string) (bool, error) { + if err := validateLinkDriverProbeArgs(scriptArgs); err != nil { + return false, fmt.Errorf("invalid cc-can-link arguments: %w", err) + } + if p.disableCCCanLink { + return false, nil + } + digest := sha256.Sum256([]byte(linuxCCCanLinkSource)) + key := strings.Join([]string{ + p.identity, p.profile.Name, p.profile.TargetTriple, "cc-can-link", + strings.Join(scriptArgs, "\x00"), hex.EncodeToString(digest[:]), + }, "\x01") + if supported, ok := p.cachedCapability(key); ok { + return supported, nil + } + + output, err := os.CreateTemp(p.tempDir, "linux-bzl-can-link-*") + if err != nil { + return false, fmt.Errorf("create cc-can-link output: %w", err) + } + outputPath := output.Name() + if err := output.Close(); err != nil { + os.Remove(outputPath) + return false, fmt.Errorf("close cc-can-link output: %w", err) + } + defer os.Remove(outputPath) + + timedCtx, cancel := context.WithTimeout(ctx, p.timeout) + defer cancel() + args := append(p.configuredCompilerArgs(), p.linkerDriverArgs...) + args = append(args, scriptArgs...) + args = append(args, "-Werror", "-Wl,--fatal-warnings", "-x", "c", "-", "-o", outputPath) + _, runErr := p.run(timedCtx, p.compilerPath, args, []byte(linuxCCCanLinkSource)) + supported, err := capabilityResult(runErr) + if err != nil { + return false, err + } + if supported { + if err := requireProbeRegularFile(outputPath, "cc-can-link executable"); err != nil { + return false, err + } + } + p.cacheCapability(key, supported) + return supported, nil +} + +const linuxStackProtectorProbeSource = "int foo(void) { char X[200]; return 3; }\n" + +// SupportsX86StackProtector reproduces the legacy x86 stack-protector helper +// scripts. Those scripts check generated assembly for the %gs canary access, +// so merely checking whether the option parses would not be equivalent. +func (p *LinuxToolProbe) SupportsX86StackProtector(ctx context.Context, bits int, scriptArgs []string) (bool, error) { + if p.profile.Name != "x86_64" { + return false, fmt.Errorf("x86 stack-protector probe requires x86_64 profile, got %q", p.profile.Name) + } + if bits != 32 && bits != 64 { + return false, fmt.Errorf("invalid x86 stack-protector width %d", bits) + } + wantArgs := []string{} + if clangFlags := p.ClangFlags(); clangFlags != "" { + wantArgs = []string{clangFlags} + } + if len(scriptArgs) != len(wantArgs) { + return false, fmt.Errorf("invalid x86 stack-protector script arguments %q, want %q", scriptArgs, wantArgs) + } + for i, arg := range scriptArgs { + if arg != wantArgs[i] { + return false, fmt.Errorf("invalid x86 stack-protector script argument %q, want %q", arg, wantArgs[i]) + } + } + key := strings.Join([]string{ + p.identity, p.profile.Name, p.profile.TargetTriple, "x86-stack-protector", + strconv.Itoa(bits), strings.Join(scriptArgs, "\x00"), + }, "\x01") + if supported, ok := p.cachedCapability(key); ok { + return supported, nil + } + + timedCtx, cancel := context.WithTimeout(ctx, p.timeout) + defer cancel() + args := append(p.configuredCompilerArgs(), scriptArgs...) + args = append(args, "-S", "-x", "c", "-c", fmt.Sprintf("-m%d", bits), "-O0") + if bits == 64 { + args = append(args, "-mcmodel=kernel", "-fno-PIE") + } + args = append(args, "-fstack-protector", "-", "-o", "-") + assembly, runErr := p.run(timedCtx, p.compilerPath, args, []byte(linuxStackProtectorProbeSource)) + compiled, err := capabilityResult(runErr) + if err != nil { + return false, err + } + supported := compiled && strings.Contains(assembly, "%gs") + p.cacheCapability(key, supported) + return supported, nil +} + +// SupportsRELR reproduces scripts/tools-support-relr.sh using the selected +// compiler and linker plus the NM and OBJCOPY executables named by the +// recognized Kconfig command. Every input and output path is controlled here. +func (p *LinuxToolProbe) SupportsRELR(ctx context.Context) (bool, error) { + key := strings.Join([]string{ + p.identity, p.profile.Name, p.profile.TargetTriple, "tools-support-relr", + }, "\x01") + if supported, ok := p.cachedCapability(key); ok { + return supported, nil + } + + tempDir, err := os.MkdirTemp(p.tempDir, "linux-bzl-relr-*") + if err != nil { + return false, fmt.Errorf("create RELR probe directory: %w", err) + } + defer os.RemoveAll(tempDir) + objectPath := filepath.Join(tempDir, "probe.o") + sharedPath := filepath.Join(tempDir, "probe.so") + binaryPath := filepath.Join(tempDir, "probe.bin") + timedCtx, cancel := context.WithTimeout(ctx, p.timeout) + defer cancel() + + compileArgs := append(p.configuredCompilerArgs(), "-c", "-x", "c", "-", "-o", objectPath) + _, runErr := p.run(timedCtx, p.compilerPath, compileArgs, []byte("void *p = &p;\n")) + if supported, resultErr := capabilityResult(runErr); resultErr != nil || !supported { + return supported, resultErr + } + if err := requireProbeRegularFile(objectPath, "RELR object"); err != nil { + return false, err + } + + _, runErr = p.run(timedCtx, p.linkerPath, []string{ + objectPath, "-shared", "-Bsymbolic", "--pack-dyn-relocs=relr", "-o", sharedPath, + }, nil) + if runErr != nil { + if _, ok := runErr.(*exec.ExitError); !ok { + return false, runErr + } + fallbackOutput, fallbackErr := p.run(timedCtx, p.linkerPath, []string{ + objectPath, "-shared", "-Bsymbolic", "-z", "pack-relative-relocs", "-o", sharedPath, + }, nil) + fallbackSupported, resultErr := capabilityResult(fallbackErr) + if resultErr != nil { + return false, resultErr + } + if !fallbackSupported || strings.Contains(fallbackOutput, "pack-relative-relocs") { + p.cacheCapability(key, false) + return false, nil + } + } + if err := requireProbeRegularFile(sharedPath, "RELR shared object"); err != nil { + return false, err + } + + _, nmStderr, nmErr := p.runSeparate(timedCtx, p.nmPath, []string{sharedPath}, nil) + nmSupported, resultErr := capabilityResult(nmErr) + if resultErr != nil { + return false, resultErr + } + if !nmSupported || strings.TrimSpace(nmStderr) != "" { + p.cacheCapability(key, false) + return false, nil + } + _, runErr = p.run(timedCtx, p.objcopyPath, []string{"-O", "binary", sharedPath, binaryPath}, nil) + supported, err := capabilityResult(runErr) + if err != nil { + return false, err + } + if supported { + if err := requireProbeRegularFile(binaryPath, "RELR binary"); err != nil { + return false, err + } + } + p.cacheCapability(key, supported) + return supported, nil +} + +func requireProbeRegularFile(path, description string) error { + info, err := os.Stat(path) + if err != nil { + return fmt.Errorf("stat %s %q: %w", description, path, err) + } + if !info.Mode().IsRegular() { + return fmt.Errorf("%s %q is not a regular file", description, path) + } + return nil +} + +func (p *LinuxToolProbe) compilerPrintFileName(ctx context.Context, name string) (string, error) { + if name != "plugin" { + return "", fmt.Errorf("unsupported compiler print-file-name value %q", name) + } + if p.disableGCCPlugins { + return "", nil + } + timedCtx, cancel := context.WithTimeout(ctx, p.timeout) + defer cancel() + args := append(p.configuredCompilerArgs(), "-print-file-name="+name) + stdout, stderr, runErr := p.runSeparate(timedCtx, p.compilerPath, args, nil) + if runErr != nil { + if _, ok := runErr.(*exec.ExitError); ok { + return "", nil + } + return "", runErr + } + if strings.TrimSpace(stderr) != "" { + return "", fmt.Errorf("compiler print-file-name wrote to stderr: %q", strings.TrimSpace(stderr)) + } + value := strings.TrimSpace(stdout) + if value == "" || strings.ContainsAny(value, "\x00\r\n") { + return "", fmt.Errorf("compiler print-file-name returned invalid path %q", value) + } + return value, nil +} + +func (p *LinuxToolProbe) compilerPluginHeaderExists(ctx context.Context, path string) (bool, error) { + if p.disableGCCPlugins { + return false, nil + } + pluginDir, err := p.compilerPrintFileName(ctx, "plugin") + if err != nil { + return false, err + } + if pluginDir == "" { + return false, nil + } + want := filepath.Clean(filepath.Join(pluginDir, "include", "plugin-version.h")) + if filepath.Clean(path) != want { + return false, fmt.Errorf("compiler plugin header probe path %q does not match %q", path, want) + } + info, err := os.Stat(want) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, fmt.Errorf("stat compiler plugin header %q: %w", want, err) + } + return !info.IsDir(), nil +} + +func (p *LinuxToolProbe) auxiliaryToolFirstLineContains(ctx context.Context, tool, option, needle string) (bool, error) { + var executable string + switch tool { + case "ar": + executable = p.archiverPath + case "nm": + executable = p.nmPath + case "objcopy": + executable = p.objcopyPath + default: + return false, fmt.Errorf("unsupported auxiliary probe tool %q", tool) + } + if option != "--help" && option != "--version" { + return false, fmt.Errorf("unsupported auxiliary probe option %q", option) + } + timedCtx, cancel := context.WithTimeout(ctx, p.timeout) + defer cancel() + stdout, _, runErr := p.runSeparate(timedCtx, executable, []string{option}, nil) + supported, err := capabilityResult(runErr) + if err != nil || !supported { + return supported, err + } + line := strings.SplitN(stdout, "\n", 2)[0] + return strings.Contains(strings.ToLower(line), strings.ToLower(needle)), nil +} + +func (p *LinuxToolProbe) cachedCapability(key string) (bool, bool) { + p.mu.Lock() + defer p.mu.Unlock() + value, ok := p.cache[key] + return value, ok +} + +func (p *LinuxToolProbe) cacheCapability(key string, value bool) { + p.mu.Lock() + p.cache[key] = value + p.mu.Unlock() +} + +func capabilityResult(err error) (bool, error) { + if err == nil { + return true, nil + } + if _, ok := err.(*exec.ExitError); ok { + return false, nil + } + return false, err +} + +func validateLinkDriverProbeArgs(args []string) error { + if len(args) == 0 { + return nil + } + if err := validateProbeCandidate("cc_can_link", args); err != nil { + return err + } + for _, arg := range args { + lower := strings.ToLower(arg) + for _, prefix := range []string{ + "--config", "--config-system-dir", "--gcc-toolchain", "--ld-path", "--resource-dir", + "-fuse-ld", "-resource-dir", "-specs", "-wrapper", + } { + if lower == prefix || strings.HasPrefix(lower, prefix+"=") { + return fmt.Errorf("tool-selection option is prohibited: %q", arg) + } + } + if strings.HasPrefix(arg, "-B") { + return fmt.Errorf("tool-selection option is prohibited: %q", arg) + } + } + return nil +} + // SupportsKbuildSource compiles a bounded source fragment from a recognized // Kbuild capability check with its concrete compiler context. Kbuild's // as-instr helper feeds printf's %b output to the compiler, so escape decoding @@ -346,10 +1135,10 @@ func (p *LinuxToolProbe) SupportsKbuildSource( defer os.Remove(outputPath) timedCtx, cancel := context.WithTimeout(ctx, p.timeout) defer cancel() - args := []string{"--target=" + p.profile.TargetTriple, "-Werror"} + args := append(p.configuredCompilerArgs(), "-Werror") args = append(args, execContext...) args = append(args, "-Wa,--fatal-warnings", "-x", language, "-c", "-o", outputPath, "-") - _, runErr := p.run(timedCtx, p.clangPath, args, []byte(decoded)) + _, runErr := p.run(timedCtx, p.compilerPath, args, []byte(decoded)) supported := runErr == nil if runErr != nil { if _, ok := runErr.(*exec.ExitError); !ok { @@ -466,18 +1255,17 @@ func (p *LinuxToolProbe) supportsPowerPCCompilerScript(ctx context.Context, scri timedCtx, cancel := context.WithTimeout(ctx, p.timeout) defer cancel() compile := func(source string, featureFlags ...string) (string, bool, error) { - args := []string{ - "--target=" + p.profile.TargetTriple, + args := append(p.configuredCompilerArgs(), endian, "-m64", "-mabi=elfv2", "-S", "-x", "c", "-O2", - } + ) args = append(args, featureFlags...) args = append(args, "-", "-o", "-") - output, err := p.run(timedCtx, p.clangPath, args, []byte(source)) + output, err := p.run(timedCtx, p.compilerPath, args, []byte(source)) if err == nil { return output, true, nil } @@ -613,7 +1401,7 @@ func safeProbeOperand(option, operand string) bool { // KBUILD_{CPP,C,A,LD}FLAGS contain include/search paths that are irrelevant to // option acceptance. They are deliberately omitted rather than handed to a -// repository-time probe. Output/plugin options remain hard errors. +// controlled probe action. Output/plugin options remain hard errors. func sanitizeProbeContext(kind string, argv []string) ([]string, error) { out := make([]string, 0, len(argv)) skipOperand := false @@ -666,22 +1454,35 @@ func sanitizeProbeContext(kind string, argv []string) ([]string, error) { } func (p *LinuxToolProbe) run(ctx context.Context, executable string, args []string, input []byte) (string, error) { + stdout, stderr, err := p.runSeparate(ctx, executable, args, input) + return stdout + stderr, err +} + +func (p *LinuxToolProbe) runSeparate(ctx context.Context, executable string, args []string, input []byte) (string, string, error) { cmd := exec.CommandContext(ctx, executable, args...) - cmd.Env = []string{"LANG=C", "LC_ALL=C", "PATH="} + cmd.Env = make([]string, 0, len(os.Environ())+2) + for _, entry := range os.Environ() { + if strings.HasPrefix(entry, "LANG=") || strings.HasPrefix(entry, "LC_ALL=") { + continue + } + cmd.Env = append(cmd.Env, entry) + } + cmd.Env = append(cmd.Env, "LANG=C", "LC_ALL=C") if input != nil { cmd.Stdin = bytes.NewReader(input) } - output := &limitedProbeBuffer{remaining: p.outputLimit} - cmd.Stdout = output - cmd.Stderr = output + stdout := &limitedProbeBuffer{remaining: p.outputLimit} + stderr := &limitedProbeBuffer{remaining: p.outputLimit} + cmd.Stdout = stdout + cmd.Stderr = stderr err := cmd.Run() if ctx.Err() != nil { - return output.String(), fmt.Errorf("Linux probe timed out or was cancelled: %w", ctx.Err()) + return stdout.String(), stderr.String(), fmt.Errorf("Linux probe timed out or was cancelled: %w", ctx.Err()) } - if output.exceeded { - return output.String(), fmt.Errorf("Linux probe output exceeded %d bytes", p.outputLimit) + if stdout.exceeded || stderr.exceeded { + return stdout.String(), stderr.String(), fmt.Errorf("Linux probe output exceeded %d bytes per stream", p.outputLimit) } - return output.String(), err + return stdout.String(), stderr.String(), err } type limitedProbeBuffer struct { diff --git a/internal/kconfig/tool_probe_test.go b/internal/kconfig/tool_probe_test.go index 101e5121..2fc258e0 100644 --- a/internal/kconfig/tool_probe_test.go +++ b/internal/kconfig/tool_probe_test.go @@ -4,6 +4,7 @@ import ( "context" "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -11,11 +12,23 @@ import ( func writeProbeTool(t *testing.T, path, version, counter string) { t.Helper() + macroIdentity := "unknown" + if matches := semanticVersionPattern.FindAllStringSubmatch(version, -1); len(matches) != 0 { + parts := matches[len(matches)-1] + patch := parts[3] + if patch == "" { + patch = "0" + } + if strings.Contains(strings.ToLower(version), "clang") { + macroIdentity = "Clang " + parts[1] + " " + parts[2] + " " + patch + } + } script := `#!/bin/sh -if [ "$1" = "--version" ]; then - echo '` + version + `' - exit 0 -fi +case " $* " in + *' --version '*) echo '` + version + `'; exit 0 ;; + *' -E -P -x c - '*) echo '` + macroIdentity + `'; exit 0 ;; + *' -### '*) echo '"clang" "-cc1as"' >&2; exit 0 ;; +esac printf x >> '` + counter + `' for arg in "$@"; do if [ "$arg" = "-fnot-supported" ]; then @@ -29,6 +42,41 @@ exit 0 } } +func addAuxiliaryProbeTools(t *testing.T, dir, family string, opts *LinuxToolProbeOptions) { + t.Helper() + outputs := map[string]string{} + switch family { + case "llvm": + outputs = map[string]string{ + "llvm-ar": "LLVM archiver version 22.1.8", + "llvm-nm": "LLVM nm version 22.1.8", + "llvm-objcopy": "llvm-objcopy version 22.1.8", + } + case "gnu": + outputs = map[string]string{ + "ar": "GNU ar (GNU Binutils) 2.44", + "nm": "GNU nm (GNU Binutils) 2.44", + "objcopy": "GNU objcopy (GNU Binutils) 2.44", + } + default: + t.Fatalf("unsupported auxiliary test tool family %q", family) + } + for name, output := range outputs { + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte("#!/bin/sh\necho '"+output+"'\n"), 0o755); err != nil { + t.Fatal(err) + } + switch { + case strings.HasSuffix(name, "objcopy"): + opts.ObjcopyPath = path + case strings.HasSuffix(name, "nm"): + opts.NMPath = path + default: + opts.ArchiverPath = path + } + } +} + func testRealToolProbe(t *testing.T, profile string) (*LinuxToolProbe, string) { return testRealToolProbeWithNames(t, profile, "clang", "ld.lld") } @@ -45,16 +93,80 @@ func testRealToolProbeWithNames(t *testing.T, profile, clangName, lldName string if err != nil { t.Fatal(err) } - probe, err := NewLinuxToolProbe(LinuxToolProbeOptions{ + opts := LinuxToolProbeOptions{ Profile: profile, Architecture: target.Arch, TargetTriple: target.TargetTriple, - ClangPath: clang, LLDPath: lld, TempDir: dir, - }) + CompilerPath: clang, LinkerPath: lld, TempDir: dir, + } + addAuxiliaryProbeTools(t, dir, "llvm", &opts) + probe, err := NewLinuxToolProbe(opts) if err != nil { t.Fatal(err) } return probe, counter } +func testGCCProbe(t *testing.T) (*LinuxToolProbe, string) { + return testGCCProbeWithName(t, "gcc") +} + +func testGCCProbeWithName(t *testing.T, compilerName string) (*LinuxToolProbe, string) { + t.Helper() + dir := t.TempDir() + invocations := filepath.Join(dir, "invocations") + gcc := filepath.Join(dir, compilerName) + ld := filepath.Join(dir, "ld") + pluginDir := filepath.Join(dir, "plugin") + if err := os.MkdirAll(filepath.Join(pluginDir, "include"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(pluginDir, "include", "plugin-version.h"), []byte("/* test */\n"), 0o644); err != nil { + t.Fatal(err) + } + gccScript := `#!/bin/sh +case " $* " in + *' --version '*) echo 'gcc (GCC) 15.2.0'; exit 0 ;; + *' -E -P -x c - '*) echo 'GCC 15 2 0'; exit 0 ;; + *' -print-file-name=plugin '*) echo '` + pluginDir + `'; exit 0 ;; +esac +printf '%s\n' "$*" >> '` + invocations + `' +case " $* " in + *' -Wa,--version '*) echo 'GNU assembler (GNU Binutils) 2.44'; exit 0 ;; + *' -fnot-supported '*) exit 1 ;; +esac +out= +while [ "$#" -gt 0 ]; do + if [ "$1" = "-o" ]; then shift; out="$1"; fi + shift +done +[ -z "$out" ] || [ "$out" = "-" ] || : > "$out" +exit 0 +` + ldScript := `#!/bin/sh +if [ "$1" = "--version" ]; then + echo 'GNU ld (GNU Binutils) 2.44' + exit 0 +fi +printf 'ld %s\n' "$*" >> '` + invocations + `' +exit 0 +` + if err := os.WriteFile(gcc, []byte(gccScript), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(ld, []byte(ldScript), 0o755); err != nil { + t.Fatal(err) + } + opts := LinuxToolProbeOptions{ + Profile: "x86_64", Architecture: "x86", TargetTriple: "x86_64-linux-gnu", + CompilerPath: gcc, LinkerPath: ld, TempDir: dir, + } + addAuxiliaryProbeTools(t, dir, "gnu", &opts) + probe, err := NewLinuxToolProbe(opts) + if err != nil { + t.Fatal(err) + } + return probe, invocations +} + func TestProbeToolModeIsExecutable(t *testing.T) { for _, test := range []struct { name string @@ -76,6 +188,120 @@ func TestProbeToolModeIsExecutable(t *testing.T) { } } +func TestToolIdentityIncludesAssembler(t *testing.T) { + dir := t.TempDir() + compiler := filepath.Join(dir, "compiler") + assembler := filepath.Join(dir, "assembler") + linker := filepath.Join(dir, "linker") + for path, contents := range map[string]string{ + compiler: "compiler", + assembler: "assembler-one", + linker: "linker", + } { + if err := os.WriteFile(path, []byte(contents), 0o755); err != nil { + t.Fatal(err) + } + } + first, err := toolIdentity(compiler, assembler, linker) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(assembler, []byte("assembler-two"), 0o755); err != nil { + t.Fatal(err) + } + second, err := toolIdentity(compiler, assembler, linker) + if err != nil { + t.Fatal(err) + } + if first == second { + t.Fatalf("tool identity did not change with assembler: %q", first) + } +} + +func TestToolIdentityIncludesVersionOutput(t *testing.T) { + dir := t.TempDir() + compiler := filepath.Join(dir, "compiler") + assembler := filepath.Join(dir, "assembler") + linker := filepath.Join(dir, "linker") + for _, path := range []string{compiler, assembler, linker} { + if err := os.WriteFile(path, []byte("stable wrapper"), 0o755); err != nil { + t.Fatal(err) + } + } + first, err := toolIdentityWithVersionLines( + []string{"gcc (GCC) 14.3.0", "GNU assembler 2.44", "GNU ld 2.44"}, + compiler, + assembler, + linker, + ) + if err != nil { + t.Fatal(err) + } + second, err := toolIdentityWithVersionLines( + []string{"gcc (GCC) 15.2.0", "GNU assembler 2.44", "GNU ld 2.44"}, + compiler, + assembler, + linker, + ) + if err != nil { + t.Fatal(err) + } + if first == second { + t.Fatalf("tool identity did not change with compiler version: %q", first) + } +} + +func TestConfiguredToolIdentityIncludesCompilerPrefix(t *testing.T) { + profile, err := LinuxTargetProfileByName("x86_64") + if err != nil { + t.Fatal(err) + } + first := extendToolIdentity("sha256-base", profile, []string{"-DTOOLCHAIN=one"}, nil) + second := extendToolIdentity("sha256-base", profile, []string{"-DTOOLCHAIN=two"}, nil) + if first == second { + t.Fatalf("configured tool identities are equal: %q", first) + } + linked := extendToolIdentity("sha256-base", profile, []string{"-DTOOLCHAIN=one"}, []string{"-fuse-ld=lld"}) + if first == linked { + t.Fatalf("linker-driver prefix did not change tool identity: %q", first) + } + policyDisabled := extendToolIdentity("sha256-base", profile, []string{"-DTOOLCHAIN=one"}, nil, false, false) + if first == policyDisabled { + t.Fatalf("measured probe policy did not change tool identity: %q", first) + } +} + +func TestValidateCompilerPrefixArgsRejectsControlledOutputs(t *testing.T) { + for _, args := range [][]string{ + {"-c"}, + {"-o", "stolen.o"}, + {"-MF=stolen.d"}, + {"@response.params"}, + } { + if err := validateCompilerPrefixArgs(args); err == nil { + t.Fatalf("validateCompilerPrefixArgs(%q) succeeded", args) + } + } + if err := validateCompilerPrefixArgs([]string{"-nostdinc", "-B/toolchain/bin", "--target=x86_64-linux-gnu"}); err != nil { + t.Fatalf("validateCompilerPrefixArgs() rejected safe prefix: %v", err) + } +} + +func TestValidateLinkerDriverPrefixArgs(t *testing.T) { + for _, args := range [][]string{ + {"-o", "stolen"}, + {"input.o"}, + {"@response.params"}, + } { + if err := validateLinkerDriverPrefixArgs(args); err == nil { + t.Fatalf("validateLinkerDriverPrefixArgs(%q) succeeded", args) + } + } + if err := validateLinkerDriverPrefixArgs([]string{"-B/toolchain/bin", "-L/toolchain/lib", "-fuse-ld=lld"}); err != nil { + t.Fatalf("validateLinkerDriverPrefixArgs() failed: %v", err) + } +} + func TestLinuxProbeShellWithToolsAcceptsWindowsSuffixedToolPaths(t *testing.T) { probe, _ := testRealToolProbeWithNames(t, "armv7", "clang.exe", "ld.lld.exe") shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) @@ -86,12 +312,12 @@ func TestLinuxProbeShellWithToolsAcceptsWindowsSuffixedToolPaths(t *testing.T) { command string want string }{ - {command: `{ command -v ` + probe.clangPath + `; } >/dev/null 2>&1 && echo "y" || echo "n"`, want: "y"}, - {command: `{ command -v ` + probe.lldPath + `; } >/dev/null 2>&1 && echo "y" || echo "n"`, want: "y"}, - {command: "/src/scripts/cc-version.sh " + probe.clangPath, want: "Clang 220108"}, - {command: "/src/scripts/as-version.sh " + probe.clangPath + " -fintegrated-as", want: "LLVM 0"}, - {command: "/src/scripts/ld-version.sh " + probe.lldPath, want: "LLD 220108"}, - {command: probe.clangPath + " --version", want: "clang version 22.1.8"}, + {command: `{ command -v ` + probe.compilerPath + `; } >/dev/null 2>&1 && echo "y" || echo "n"`, want: "y"}, + {command: `{ command -v ` + probe.linkerPath + `; } >/dev/null 2>&1 && echo "y" || echo "n"`, want: "y"}, + {command: "/src/scripts/cc-version.sh " + probe.compilerPath, want: "Clang 220108"}, + {command: "/src/scripts/as-version.sh " + probe.compilerPath + " -fintegrated-as", want: "LLVM 0"}, + {command: "/src/scripts/ld-version.sh " + probe.linkerPath, want: "LLD 220108"}, + {command: probe.compilerPath + " --version", want: "clang version 22.1.8"}, } { got, runErr := shell(context.Background(), test.command) if runErr != nil || got != test.want { @@ -100,6 +326,106 @@ func TestLinuxProbeShellWithToolsAcceptsWindowsSuffixedToolPaths(t *testing.T) { } } +func TestLinuxToolProbeDetectsClangExternalGNUAssembler(t *testing.T) { + dir := t.TempDir() + clang := filepath.Join(dir, "clang") + lld := filepath.Join(dir, "ld.lld") + invocations := filepath.Join(dir, "invocations") + clangScript := `#!/bin/sh +if [ "$1" = "--version" ]; then echo 'clang version 22.1.8'; exit 0; fi +case " $* " in + *' -E -P -x c - '*) echo 'Clang 22 1 8'; exit 0 ;; + *' -### '*) echo '"/toolchain/bin/as" "--64"' >&2; exit 0 ;; + *' -Wa,--version '*) echo 'GNU assembler (GNU Binutils) 2.44'; exit 0 ;; +esac + printf '%s\n' "$*" >> '` + invocations + `' + echo 'movq %gs:40, %rax' +exit 0 +` + if err := os.WriteFile(clang, []byte(clangScript), 0o755); err != nil { + t.Fatal(err) + } + writeProbeTool(t, lld, "LLD version 22.1.8", filepath.Join(dir, "counter")) + opts := LinuxToolProbeOptions{ + Profile: "x86_64", Architecture: "x86", TargetTriple: "x86_64-linux-gnu", + CompilerPath: clang, LinkerPath: lld, TempDir: dir, + } + addAuxiliaryProbeTools(t, dir, "gnu", &opts) + probe, err := NewLinuxToolProbe(opts) + if err != nil { + t.Fatal(err) + } + if got, want := probe.ClangFlags(), "-fno-integrated-as"; got != want { + t.Fatalf("ClangFlags() = %q, want %q", got, want) + } + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + command := "/src/scripts/as-version.sh " + clang + " -fno-integrated-as" + if got, err := shell(context.Background(), command); err != nil || got != "GNU 24400" { + t.Fatalf("shell(%q) = %q, %v; want GNU 24400", command, got, err) + } + assertExternalAssemblerInvocation := func(command string) { + t.Helper() + data, err := os.ReadFile(invocations) + if err != nil { + t.Fatal(err) + } + fields := strings.Fields(string(data)) + if !slices.Contains(fields, "-fno-integrated-as") { + t.Fatalf("compiler invocation for %s = %q, missing -fno-integrated-as", command, data) + } + if slices.Contains(fields, "-fintegrated-as") { + t.Fatalf("compiler invocation for %s = %q, unexpectedly selected the integrated assembler", command, data) + } + } + resetInvocations := func() { + t.Helper() + if err := os.WriteFile(invocations, nil, 0o600); err != nil { + t.Fatal(err) + } + } + + for _, test := range []struct { + name string + clangFlags string + }{ + {name: "variable", clangFlags: "$(CLANG_FLAGS)"}, + {name: "expanded", clangFlags: "-fno-integrated-as"}, + } { + resetInvocations() + command := `{ ` + clang + ` -Werror ` + test.clangFlags + ` -fexternal-assembler-` + test.name + `-test -c -x c /dev/null -o .tmp.o; } >/dev/null 2>&1 && echo "y" || echo "n"` + if got, err := shell(context.Background(), command); err != nil || got != "y" { + t.Fatalf("shell(%q) = %q, %v; want y", command, got, err) + } + assertExternalAssemblerInvocation("cc-option " + test.name) + } + + resetInvocations() + command = `{ printf "%b\n" ".arch_extension lse" | ` + clang + ` $(CLANG_FLAGS) -Wa,--fatal-warnings -c -x assembler-with-cpp -o /dev/null -; } >/dev/null 2>&1 && echo "y" || echo "n"` + if got, err := shell(context.Background(), command); err != nil || got != "y" { + t.Fatalf("shell(%q) = %q, %v; want y", command, got, err) + } + assertExternalAssemblerInvocation("source probe") + + resetInvocations() + command = `{ /src/scripts/gcc-x86_64-has-stack-protector.sh ` + clang + ` -fno-integrated-as; } >/dev/null 2>&1 && echo "y" || echo "n"` + if got, err := shell(context.Background(), command); err != nil || got != "y" { + t.Fatalf("shell(%q) = %q, %v; want y", command, got, err) + } + assertExternalAssemblerInvocation("x86 stack-protector probe") + if _, err := probe.SupportsX86StackProtector(context.Background(), 64, []string{"-fintegrated-as"}); err == nil || !strings.Contains(err.Error(), "invalid x86 stack-protector script argument") { + t.Fatalf("SupportsX86StackProtector() mismatched assembler error = %v", err) + } + if _, err := probe.SupportsX86StackProtector(context.Background(), 64, nil); err == nil || !strings.Contains(err.Error(), "invalid x86 stack-protector script arguments") { + t.Fatalf("SupportsX86StackProtector() missing assembler argument error = %v", err) + } + if _, err := probe.SupportsX86StackProtector(context.Background(), 64, []string{"-fno-integrated-as", "-m64"}); err == nil || !strings.Contains(err.Error(), "invalid x86 stack-protector script argument") { + t.Fatalf("SupportsX86StackProtector() extra argument error = %v", err) + } +} + func TestLinuxToolProbeRunsAndCachesRealCompilerProbe(t *testing.T) { probe, counter := testRealToolProbe(t, "armv7") for i := 0; i < 2; i++ { @@ -120,7 +446,423 @@ func TestLinuxToolProbeRunsAndCachesRealCompilerProbe(t *testing.T) { } } -func TestLinuxProbeShellWithToolsRejectsHostNativeMarchWithoutExecution(t *testing.T) { +func TestLinuxToolProbeMeasuresGCCGNUIdentity(t *testing.T) { + probe, invocations := testGCCProbe(t) + if got, want := probe.CompilerFamily(), "gcc"; got != want { + t.Fatalf("CompilerFamily() = %q, want %q", got, want) + } + if got, want := probe.CompilerVersionText(), "gcc (GCC) 15.2.0"; got != want { + t.Fatalf("CompilerVersionText() = %q, want %q", got, want) + } + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + for command, want := range map[string]string{ + "/src/scripts/cc-version.sh " + probe.compilerPath: "GCC 150200", + "/src/scripts/as-version.sh " + probe.compilerPath: "GNU 24400", + "/src/scripts/ld-version.sh " + probe.linkerPath: "BFD 24400", + probe.compilerPath + " --version": "gcc (GCC) 15.2.0", + } { + got, runErr := shell(context.Background(), command) + if runErr != nil || got != want { + t.Fatalf("shell(%q) = %q, %v; want %q", command, got, runErr, want) + } + } + data, err := os.ReadFile(invocations) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), "-Wa,--version -c -x assembler-with-cpp "+os.DevNull+" -o "+os.DevNull) { + t.Fatalf("assembler was not identified through the compiler driver: %q", data) + } +} + +func TestLinuxToolProbeIdentifiesConfiguredFrontendFromMacros(t *testing.T) { + dir := t.TempDir() + compiler := filepath.Join(dir, "compiler-wrapper") + linker := filepath.Join(dir, "ld.lld") + invocations := filepath.Join(dir, "compiler-invocations") + compilerScript := `#!/bin/sh +printf '%s\n' "$*" >> '` + invocations + `' +case " $* " in + ' --version '*) echo 'opaque wrapper version 1.0'; exit 0 ;; + *' --frontend=clang --version '*) echo 'clang version 22.1.8'; exit 0 ;; + *' --frontend=clang -E -P -x c - '*) echo 'Clang 22 1 9'; exit 0 ;; + *' --frontend=clang -### '*) echo '"clang" "-cc1as"' >&2; exit 0 ;; +esac +exit 1 +` + if err := os.WriteFile(compiler, []byte(compilerScript), 0o755); err != nil { + t.Fatal(err) + } + writeProbeTool(t, linker, "LLD version 22.1.8", filepath.Join(dir, "count")) + opts := LinuxToolProbeOptions{ + Profile: "x86_64", Architecture: "x86", TargetTriple: "x86_64-linux-gnu", + CompilerPath: compiler, LinkerPath: linker, CompilerArgs: []string{"--frontend=clang"}, TempDir: dir, + } + addAuxiliaryProbeTools(t, dir, "llvm", &opts) + probe, err := NewLinuxToolProbe(opts) + if err != nil { + t.Fatal(err) + } + if got, want := probe.CompilerFamily(), "clang"; got != want { + t.Fatalf("CompilerFamily() = %q, want %q", got, want) + } + if got, want := probe.compilerCode, 220109; got != want { + t.Fatalf("compilerCode = %d, want %d", got, want) + } + if got, want := probe.CompilerVersionText(), "clang version 22.1.8"; got != want { + t.Fatalf("CompilerVersionText() = %q, want %q", got, want) + } + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + if got, runErr := shell(context.Background(), "/src/scripts/cc-version.sh "+compiler); runErr != nil || got != "Clang 220109" { + t.Fatalf("configured cc-version = %q, %v; want Clang 220109", got, runErr) + } + data, err := os.ReadFile(invocations) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"--frontend=clang --version", "--frontend=clang -E -P -x c -"} { + if !strings.Contains(string(data), want) { + t.Fatalf("configured compiler invocations %q do not contain %q", data, want) + } + } +} + +func TestLinuxToolProbeLegacyClangPrefixAddsNonHostTarget(t *testing.T) { + for _, name := range []string{"x86_64", "aarch64", "armv7", "riscv64", "ppc64le"} { + profile, err := LinuxTargetProfileByName(name) + if err != nil { + t.Fatal(err) + } + if linuxProbeProfileMatchesHost(profile) { + continue + } + probe := &LinuxToolProbe{profile: profile, compilerFamily: "clang"} + got := probe.configuredCompilerArgs() + want := []string{"--target=" + profile.TargetTriple} + if strings.Join(got, "\x00") != strings.Join(want, "\x00") { + t.Fatalf("configuredCompilerArgs() = %q, want %q", got, want) + } + probe.compilerArgs = []string{"-DTOOLCHAIN_CONFIGURED=1"} + if got := probe.configuredCompilerArgs(); len(got) != 1 || got[0] != "-DTOOLCHAIN_CONFIGURED=1" { + t.Fatalf("configured compiler prefix was not authoritative: %q", got) + } + return + } + t.Fatal("no non-host Linux target profile found") +} + +func TestLinuxProbeShellWithToolsMeasuresCCCanLink(t *testing.T) { + probe, invocations := testGCCProbe(t) + probe.compilerArgs = []string{"-DTOOLCHAIN_PREFIX=1"} + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + command := `{ /src/scripts/cc-can-link.sh ` + probe.compilerPath + ` -m64 -static; } >/dev/null 2>&1 && echo "y" || echo "n"` + got, err := shell(context.Background(), command) + if err != nil || got != "y" { + t.Fatalf("shell(%q) = %q, %v; want y, nil", command, got, err) + } + data, err := os.ReadFile(invocations) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"-DTOOLCHAIN_PREFIX=1", "-m64", "-static", "-Werror", "-Wl,--fatal-warnings"} { + if !strings.Contains(string(data), want) { + t.Fatalf("cc-can-link invocation %q does not contain %q", data, want) + } + } + unsafe := `{ /src/scripts/cc-can-link.sh ` + probe.compilerPath + ` -o /tmp/escape; } >/dev/null 2>&1 && echo "y" || echo "n"` + if _, err := shell(context.Background(), unsafe); err == nil || !strings.Contains(err.Error(), "controlled") { + t.Fatalf("unsafe cc-can-link error = %v", err) + } + toolSelection := `{ /src/scripts/cc-can-link.sh ` + probe.compilerPath + ` -B/undeclared; } >/dev/null 2>&1 && echo "y" || echo "n"` + if _, err := shell(context.Background(), toolSelection); err == nil || !strings.Contains(err.Error(), "tool-selection") { + t.Fatalf("tool-selecting cc-can-link error = %v", err) + } +} + +func TestLinuxProbeShellWithToolsReproducesCCOptionBitPreprocessing(t *testing.T) { + probe, invocations := testGCCProbe(t) + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + command := `{ gcc -Werror -m64 -E -x c /dev/null -o /dev/null; } >/dev/null 2>&1 && echo "y" || echo "n"` + got, err := shell(context.Background(), command) + if err != nil || got != "y" { + t.Fatalf("shell(%q) = %q, %v; want y, nil", command, got, err) + } + data, err := os.ReadFile(invocations) + if err != nil { + t.Fatal(err) + } + invocation := string(data) + lines := strings.Split(strings.TrimSpace(invocation), "\n") + last := lines[len(lines)-1] + if !strings.Contains(" "+last+" ", " -E ") || strings.Contains(" "+last+" ", " -c ") { + t.Fatalf("cc-option-bit invocation = %q, want preprocessing without assembly", invocation) + } +} + +func TestLinuxProbeShellWithToolsMeasuresGCCPluginHeader(t *testing.T) { + probe, _ := testGCCProbe(t) + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + pluginDir, err := shell(context.Background(), probe.compilerPath+" -print-file-name=plugin") + if err != nil { + t.Fatal(err) + } + header := filepath.Join(pluginDir, "include", "plugin-version.h") + command := `{ test -e ` + header + `; } >/dev/null 2>&1 && echo "y" || echo "n"` + got, err := shell(context.Background(), command) + if err != nil || got != "y" { + t.Fatalf("shell(%q) = %q, %v; want y, nil", command, got, err) + } + wrong := `{ test -e ` + filepath.Join(t.TempDir(), "include", "plugin-version.h") + `; } >/dev/null 2>&1 && echo "y" || echo "n"` + if _, err := shell(context.Background(), wrong); err == nil || !strings.Contains(err.Error(), "does not match") { + t.Fatalf("mismatched plugin header error = %v", err) + } +} + +func TestLinuxProbeShellWithToolsHonorsDisabledLinkAndPluginPolicy(t *testing.T) { + probe, invocations := testGCCProbe(t) + probe.disableCCCanLink = true + probe.disableGCCPlugins = true + if err := os.WriteFile(invocations, nil, 0o644); err != nil { + t.Fatal(err) + } + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + linkCommand := `{ /src/scripts/cc-can-link.sh ` + probe.compilerPath + ` -m64; } >/dev/null 2>&1 && echo "y" || echo "n"` + if got, runErr := shell(context.Background(), linkCommand); runErr != nil || got != "n" { + t.Fatalf("disabled cc-can-link = %q, %v; want n, nil", got, runErr) + } + if got, runErr := shell(context.Background(), probe.compilerPath+" -print-file-name=plugin"); runErr != nil || got != "" { + t.Fatalf("disabled plugin directory = %q, %v; want empty, nil", got, runErr) + } + header := filepath.Join(t.TempDir(), "include", "plugin-version.h") + if err := os.MkdirAll(filepath.Dir(header), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(header, []byte("ambient"), 0o644); err != nil { + t.Fatal(err) + } + headerCommand := `{ test -e ` + header + `; } >/dev/null 2>&1 && echo "y" || echo "n"` + if got, runErr := shell(context.Background(), headerCommand); runErr != nil || got != "n" { + t.Fatalf("disabled plugin header = %q, %v; want n, nil", got, runErr) + } + if data, readErr := os.ReadFile(invocations); readErr != nil || len(data) != 0 { + t.Fatalf("disabled policy executed compiler: %q, %v", data, readErr) + } +} + +func TestLinuxProbeShellWithToolsMeasuresAuxiliaryToolFamilies(t *testing.T) { + for _, test := range []struct { + name string + newProbe func(*testing.T) (*LinuxToolProbe, string) + wantLLVM string + wantGNUObj string + }{ + {name: "LLVM", newProbe: func(t *testing.T) (*LinuxToolProbe, string) { return testRealToolProbe(t, "x86_64") }, wantLLVM: "y", wantGNUObj: "n"}, + {name: "GNU", newProbe: testGCCProbe, wantLLVM: "n", wantGNUObj: "y"}, + } { + t.Run(test.name, func(t *testing.T) { + probe, _ := test.newProbe(t) + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + commands := map[string]string{ + `{ ` + probe.nmPath + ` --help | head -n 1 | grep -qi llvm; } >/dev/null 2>&1 && echo "y" || echo "n"`: test.wantLLVM, + `{ ` + probe.archiverPath + ` --help | head -n 1 | grep -qi llvm; } >/dev/null 2>&1 && echo "y" || echo "n"`: test.wantLLVM, + `{ ` + probe.objcopyPath + ` --version | head -n1 | grep -qv llvm; } >/dev/null 2>&1 && echo "y" || echo "n"`: test.wantGNUObj, + } + for command, want := range commands { + got, runErr := shell(context.Background(), command) + if runErr != nil || got != want { + t.Errorf("shell(%q) = %q, %v; want %q", command, got, runErr, want) + } + } + }) + } +} + +func TestLinuxProbeShellWithToolsMeasuresLegacyX86StackProtector(t *testing.T) { + dir := t.TempDir() + compiler := filepath.Join(dir, "gcc") + if err := os.WriteFile(compiler, []byte("#!/bin/sh\necho 'movq %gs:40, %rax'\n"), 0o755); err != nil { + t.Fatal(err) + } + profile, err := LinuxTargetProfileByName("x86_64") + if err != nil { + t.Fatal(err) + } + probe := &LinuxToolProbe{ + profile: profile, compilerPath: compiler, compilerFamily: "gcc", compilerName: "GCC", + identity: "test-stack-protector", tempDir: dir, timeout: time.Second, outputLimit: linuxProbeOutputLimit, + cache: map[string]bool{}, + } + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + for _, bits := range []string{"32", "64"} { + command := `{ /src/scripts/gcc-x86_` + bits + `-has-stack-protector.sh ` + compiler + `; } >/dev/null 2>&1 && echo "y" || echo "n"` + got, runErr := shell(context.Background(), command) + if runErr != nil || got != "y" { + t.Errorf("shell(%q) = %q, %v; want y, nil", command, got, runErr) + } + } +} + +func TestLinuxProbeShellWithToolsMeasuresRELR(t *testing.T) { + dir := t.TempDir() + compiler := filepath.Join(dir, "gcc") + linker := filepath.Join(dir, "ld") + archiver := filepath.Join(dir, "ar") + nm := filepath.Join(dir, "nm") + objcopy := filepath.Join(dir, "objcopy") + compilerScript := `#!/bin/sh +case " $* " in + *' --version '*) echo 'gcc (GCC) 15.2.0'; exit 0 ;; + *' -E -P -x c - '*) echo 'GCC 15 2 0'; exit 0 ;; + *' -Wa,--version '*) echo 'GNU assembler (GNU Binutils) 2.44'; exit 0 ;; +esac +out= +while [ "$#" -gt 0 ]; do + if [ "$1" = "-o" ]; then shift; out="$1"; fi + shift +done +[ -z "$out" ] || : > "$out" +` + linkerScript := `#!/bin/sh +if [ "$1" = "--version" ]; then echo 'GNU ld (GNU Binutils) 2.44'; exit 0; fi +out= +while [ "$#" -gt 0 ]; do + if [ "$1" = "-o" ]; then shift; out="$1"; fi + shift +done +[ -z "$out" ] || : > "$out" +` + auxiliaryScripts := map[string]string{ + archiver: "#!/bin/sh\necho 'GNU ar (GNU Binutils) 2.44'\n", + nm: `#!/bin/sh +if [ "$1" = "--version" ] || [ "$1" = "--help" ]; then echo 'GNU nm (GNU Binutils) 2.44'; fi +`, + objcopy: `#!/bin/sh +if [ "$1" = "--version" ]; then echo 'GNU objcopy (GNU Binutils) 2.44'; exit 0; fi +for last do :; done +: > "$last" +`, + } + for path, contents := range auxiliaryScripts { + if err := os.WriteFile(path, []byte(contents), 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(compiler, []byte(compilerScript), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(linker, []byte(linkerScript), 0o755); err != nil { + t.Fatal(err) + } + probe, err := NewLinuxToolProbe(LinuxToolProbeOptions{ + Profile: "x86_64", Architecture: "x86", TargetTriple: "x86_64-linux-gnu", + CompilerPath: compiler, LinkerPath: linker, ArchiverPath: archiver, NMPath: nm, ObjcopyPath: objcopy, + TempDir: dir, + }) + if err != nil { + t.Fatal(err) + } + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + command := `env "CC=` + compiler + `" "LD=` + linker + `" "NM=` + nm + `" "OBJCOPY=` + objcopy + `" /src/scripts/tools-support-relr.sh` + wrapped := `{ ` + command + `; } >/dev/null 2>&1 && echo "y" || echo "n"` + got, err := shell(context.Background(), wrapped) + if err != nil || got != "y" { + t.Fatalf("shell(%q) = %q, %v; want y, nil", command, got, err) + } + mismatched := strings.Replace(command, `"NM=`+nm+`"`, `"NM=/undeclared/nm"`, 1) + if _, err := shell(context.Background(), `{ `+mismatched+`; } >/dev/null 2>&1 && echo "y" || echo "n"`); err == nil || !strings.Contains(err.Error(), "unsupported measured") { + t.Fatalf("mismatched RELR tools error = %v", err) + } +} + +func TestLinuxToolProbeUsesConfiguredCompilerPrefix(t *testing.T) { + probe, invocations := testGCCProbe(t) + probe.compilerArgs = []string{"-DTOOLCHAIN_PREFIX_REPLAYED=1", "-B/toolchain/bin"} + supported, err := probe.SupportsOption(context.Background(), "cc_option", []string{"-fexample"}, nil) + if err != nil || !supported { + t.Fatalf("SupportsOption() = %v, %v", supported, err) + } + data, err := os.ReadFile(invocations) + if err != nil { + t.Fatal(err) + } + invocation := string(data) + for _, want := range []string{"-DTOOLCHAIN_PREFIX_REPLAYED=1", "-B/toolchain/bin", "-fexample"} { + if !strings.Contains(invocation, want) { + t.Fatalf("compiler invocation %q does not contain %q", invocation, want) + } + } +} + +func TestLinuxToolProbeGCCOmitsClangTargetFlag(t *testing.T) { + probe, invocations := testGCCProbe(t) + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + command := `{ ` + probe.compilerPath + ` -Werror -fno-omit-frame-pointer -c -x c /dev/null -o /dev/null; } >/dev/null 2>&1 && echo "y" || echo "n"` + got, err := shell(context.Background(), command) + if err != nil || got != "y" { + t.Fatalf("shell(%q) = %q, %v; want y, nil", command, got, err) + } + data, err := os.ReadFile(invocations) + if err != nil { + t.Fatal(err) + } + args := string(data) + if strings.Contains(args, "--target=") { + t.Fatalf("GCC probe arguments contain Clang target flag: %q", args) + } + for _, want := range []string{"-Werror", "-fno-omit-frame-pointer", "-x c", "-c"} { + if !strings.Contains(args, want) { + t.Fatalf("GCC probe arguments %q do not contain %q", args, want) + } + } +} + +func TestLinuxProbeShellWithToolsRecognizesTargetPrefixedGCC(t *testing.T) { + probe, invocations := testGCCProbeWithName(t, "x86_64-linux-gnu-gcc") + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + command := `{ ` + probe.compilerPath + ` -Werror -fno-omit-frame-pointer -c -x c /dev/null -o /dev/null; } >/dev/null 2>&1 && echo "y" || echo "n"` + got, err := shell(context.Background(), command) + if err != nil || got != "y" { + t.Fatalf("shell(%q) = %q, %v; want y, nil", command, got, err) + } + if data, readErr := os.ReadFile(invocations); readErr != nil || !strings.Contains(string(data), "-fno-omit-frame-pointer") { + t.Fatalf("target-prefixed GCC invocations = %q, %v", data, readErr) + } +} + +func TestLinuxProbeShellWithToolsMeasuresHostNativeMarch(t *testing.T) { probe, counter := testRealToolProbe(t, "x86_64") shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) if err != nil { @@ -128,15 +870,15 @@ func TestLinuxProbeShellWithToolsRejectsHostNativeMarchWithoutExecution(t *testi } command := `{ clang -Werror -march=native -c -x c /dev/null -o /dev/null; } >/dev/null 2>&1 && echo "y" || echo "n"` got, err := shell(context.Background(), command) - if err != nil || got != "n" { - t.Fatalf("shell(%q) = %q, %v; want n, nil", command, got, err) + if err != nil || got != "y" { + t.Fatalf("shell(%q) = %q, %v; want y, nil", command, got, err) } data, readErr := os.ReadFile(counter) if readErr != nil && !os.IsNotExist(readErr) { t.Fatal(readErr) } - if len(data) != 0 { - t.Fatalf("host-native probe executed the compiler %d times, want zero", len(data)) + if len(data) == 0 { + t.Fatal("host-native probe did not execute the selected compiler") } } @@ -145,10 +887,11 @@ func TestLinuxToolProbeMeasuresSafeKbuildAssemblerSource(t *testing.T) { clang := filepath.Join(dir, "clang") lld := filepath.Join(dir, "ld.lld") clangScript := `#!/bin/sh -if [ "$1" = "--version" ]; then - echo 'clang version 22.1.8' - exit 0 -fi +case " $* " in + *' --version '*) echo 'clang version 22.1.8'; exit 0 ;; + *' -E -P -x c - '*) echo 'Clang 22 1 8'; exit 0 ;; + *' -### '*) echo '"clang" "-cc1as"' >&2; exit 0 ;; +esac input=$(/bin/cat) case "$input" in 'mov r0,r0') ;; @@ -167,10 +910,12 @@ exit 0 t.Fatal(err) } writeProbeTool(t, lld, "LLD version 22.1.8", filepath.Join(dir, "count")) - probe, err := NewLinuxToolProbe(LinuxToolProbeOptions{ + opts := LinuxToolProbeOptions{ Profile: "armv7", Architecture: "arm", TargetTriple: "arm-linux-gnueabi", - ClangPath: clang, LLDPath: lld, TempDir: dir, - }) + CompilerPath: clang, LinkerPath: lld, TempDir: dir, + } + addAuxiliaryProbeTools(t, dir, "llvm", &opts) + probe, err := NewLinuxToolProbe(opts) if err != nil { t.Fatal(err) } @@ -220,18 +965,121 @@ func TestLinuxToolProbeAllowsARMAPCSMachineFlag(t *testing.T) { } } -func TestLinuxToolProbeRejectsUnpinnedVersion(t *testing.T) { - dir := t.TempDir() - clang := filepath.Join(dir, "clang") - lld := filepath.Join(dir, "ld.lld") - writeProbeTool(t, clang, "clang version 21.1.8", filepath.Join(dir, "count")) - writeProbeTool(t, lld, "LLD 22.1.8", filepath.Join(dir, "count")) - _, err := NewLinuxToolProbe(LinuxToolProbeOptions{ - Profile: "x86_64", Architecture: "x86", TargetTriple: "x86_64-linux-gnu", - ClangPath: clang, LLDPath: lld, - }) - if err == nil || !strings.Contains(err.Error(), "want pinned LLVM") { - t.Fatalf("NewLinuxToolProbe() error = %v", err) +func TestLinuxToolProbeEnforcesLinuxMinimumLLVMVersion(t *testing.T) { + for _, test := range []struct { + name string + clangVersion string + lldVersion string + wantError string + }{ + {name: "minimum accepted", clangVersion: "15.0.0", lldVersion: "15.0.0"}, + {name: "newer accepted", clangVersion: "21.1.8", lldVersion: "21.1.8"}, + {name: "old clang", clangVersion: "14.0.6", lldVersion: "15.0.0", wantError: "clang version"}, + {name: "old lld", clangVersion: "15.0.0", lldVersion: "14.0.6", wantError: "ld.lld version"}, + } { + t.Run(test.name, func(t *testing.T) { + dir := t.TempDir() + clang := filepath.Join(dir, "clang") + lld := filepath.Join(dir, "ld.lld") + writeProbeTool(t, clang, "clang version "+test.clangVersion, filepath.Join(dir, "count")) + writeProbeTool(t, lld, "LLD "+test.lldVersion, filepath.Join(dir, "count")) + opts := LinuxToolProbeOptions{ + Profile: "x86_64", Architecture: "x86", TargetTriple: "x86_64-linux-gnu", + CompilerPath: clang, LinkerPath: lld, + } + addAuxiliaryProbeTools(t, dir, "llvm", &opts) + _, err := NewLinuxToolProbe(opts) + if test.wantError == "" && err != nil { + t.Fatalf("NewLinuxToolProbe() error = %v", err) + } + if test.wantError != "" && (err == nil || !strings.Contains(err.Error(), test.wantError) || !strings.Contains(err.Error(), "want at least")) { + t.Fatalf("NewLinuxToolProbe() error = %v, want %q minimum error", err, test.wantError) + } + }) + } +} + +func TestLinuxToolProbeAllowsIndependentCompilerAndLinkerFamilies(t *testing.T) { + for _, test := range []struct { + name string + compilerVersion string + linkerVersion string + wantCompiler string + wantLinker string + }{ + {name: "Clang with GNU ld", compilerVersion: "clang version 22.1.8", linkerVersion: "GNU ld (GNU Binutils) 2.44", wantCompiler: "clang", wantLinker: "BFD"}, + {name: "GCC with LLD", compilerVersion: "gcc (GCC) 15.2.0", linkerVersion: "LLD version 22.1.8", wantCompiler: "gcc", wantLinker: "LLD"}, + } { + t.Run(test.name, func(t *testing.T) { + dir := t.TempDir() + compiler := filepath.Join(dir, test.wantCompiler) + macroIdentity := map[string]string{"clang": "Clang 22 1 8", "gcc": "GCC 15 2 0"}[test.wantCompiler] + compilerScript := "#!/bin/sh\ncase \" $* \" in\n *' --version '*) echo '" + test.compilerVersion + "'; exit 0 ;;\n *' -E -P -x c - '*) echo '" + macroIdentity + "'; exit 0 ;;\nesac\n" + if test.wantCompiler == "gcc" { + compilerScript += "case \" $* \" in *' -Wa,--version '*) echo 'GNU assembler (GNU Binutils) 2.44';; esac\n" + } else { + compilerScript += "case \" $* \" in *' -### '*) echo '\"clang\" \"-cc1as\"' >&2;; esac\n" + } + if err := os.WriteFile(compiler, []byte(compilerScript), 0o755); err != nil { + t.Fatal(err) + } + linker := filepath.Join(dir, "ld") + if err := os.WriteFile(linker, []byte("#!/bin/sh\necho '"+test.linkerVersion+"'\n"), 0o755); err != nil { + t.Fatal(err) + } + opts := LinuxToolProbeOptions{ + Profile: "x86_64", Architecture: "x86", TargetTriple: "x86_64-linux-gnu", + CompilerPath: compiler, LinkerPath: linker, + } + addAuxiliaryProbeTools(t, dir, "llvm", &opts) + probe, err := NewLinuxToolProbe(opts) + if err != nil { + t.Fatal(err) + } + if probe.compilerFamily != test.wantCompiler || probe.linkerName != test.wantLinker { + t.Fatalf("families = %q/%q, want %q/%q", probe.compilerFamily, probe.linkerName, test.wantCompiler, test.wantLinker) + } + }) + } +} + +func TestLinuxToolProbeRejectsOldGCCAndBinutils(t *testing.T) { + for _, test := range []struct { + name string + gccVersion string + asVersion string + ldVersion string + want string + }{ + {name: "old GCC", gccVersion: "7.5.0", asVersion: "2.44", ldVersion: "2.44", want: "GCC version"}, + {name: "old assembler", gccVersion: "15.2.0", asVersion: "2.29", ldVersion: "2.44", want: "assembler version"}, + {name: "old linker", gccVersion: "15.2.0", asVersion: "2.44", ldVersion: "2.29", want: "ld version"}, + } { + t.Run(test.name, func(t *testing.T) { + dir := t.TempDir() + gcc := filepath.Join(dir, "gcc") + versionParts := strings.Split(test.gccVersion, ".") + gccScript := "#!/bin/sh\ncase \" $* \" in\n *' -E -P -x c - '*) echo 'GCC " + strings.Join(versionParts, " ") + "' ;;\n *' -Wa,--version '*) echo 'GNU assembler (GNU Binutils) " + test.asVersion + "' ;;\n *) echo 'gcc (GCC) " + test.gccVersion + "' ;;\nesac\n" + if err := os.WriteFile(gcc, []byte(gccScript), 0o755); err != nil { + t.Fatal(err) + } + ld := filepath.Join(dir, "ld") + if err := os.WriteFile(ld, []byte("#!/bin/sh\necho 'GNU ld (GNU Binutils) "+test.ldVersion+"'\n"), 0o755); err != nil { + t.Fatal(err) + } + opts := LinuxToolProbeOptions{ + Profile: "x86_64", + Architecture: "x86", + TargetTriple: "x86_64-linux-gnu", + CompilerPath: gcc, + LinkerPath: ld, + } + addAuxiliaryProbeTools(t, dir, "gnu", &opts) + _, err := NewLinuxToolProbe(opts) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("NewLinuxToolProbe() error = %v, want %q", err, test.want) + } + }) } } @@ -262,26 +1110,89 @@ func TestLinuxProbeShellWithToolsCompilesAllowlistedSource(t *testing.T) { } } +func TestLinuxProbeShellWithToolsPreservesSourceProbeModeAndWarnings(t *testing.T) { + probe, invocations := testGCCProbe(t) + shell, err := LinuxProbeShellWithTools(probe, LinuxProbeDefaultRustcVersion, LinuxProbeDefaultRustcLLVMVersion) + if err != nil { + t.Fatal(err) + } + tests := []struct { + name string + command string + wantMode string + wantWerror bool + }{ + { + name: "assembly output without warnings as errors", + command: `{ echo 'int __seg_fs fs; int __seg_gs gs;' | ` + probe.compilerPath + ` -x c - -S -o /dev/null; } >/dev/null 2>&1 && echo "y" || echo "n"`, + wantMode: "-S", + }, + { + name: "object output with warnings as errors", + command: `{ echo '__attribute__((no_profile_instrument_function)) int x();' | ` + probe.compilerPath + ` -x c - -c -o /dev/null -Werror; } >/dev/null 2>&1 && echo "y" || echo "n"`, + wantMode: "-c", + wantWerror: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if err := os.WriteFile(invocations, nil, 0o644); err != nil { + t.Fatal(err) + } + got, runErr := shell(context.Background(), test.command) + if runErr != nil || got != "y" { + t.Fatalf("shell() = %q, %v; want y, nil", got, runErr) + } + data, err := os.ReadFile(invocations) + if err != nil { + t.Fatal(err) + } + args := strings.Fields(string(data)) + contains := func(want string) bool { + for _, arg := range args { + if arg == want { + return true + } + } + return false + } + if !contains(test.wantMode) { + t.Fatalf("source probe args %q do not contain mode %q", data, test.wantMode) + } + otherMode := map[string]string{"-c": "-S", "-S": "-c"}[test.wantMode] + if contains(otherMode) { + t.Fatalf("source probe args %q unexpectedly contain mode %q", data, otherMode) + } + if gotWerror := contains("-Werror"); gotWerror != test.wantWerror { + t.Fatalf("source probe args %q contain -Werror = %v, want %v", data, gotWerror, test.wantWerror) + } + }) + } +} + func TestLinuxProbeShellWithToolsDecodesAssemblerPrintfSource(t *testing.T) { dir := t.TempDir() clang := filepath.Join(dir, "clang") lld := filepath.Join(dir, "ld.lld") captured := filepath.Join(dir, "source") clangScript := `#!/bin/sh -if [ "$1" = "--version" ]; then - echo 'clang version 22.1.8' - exit 0 -fi +case " $* " in + *' --version '*) echo 'clang version 22.1.8'; exit 0 ;; + *' -E -P -x c - '*) echo 'Clang 22 1 8'; exit 0 ;; + *' -### '*) echo '"clang" "-cc1as"' >&2; exit 0 ;; +esac /bin/cat > '` + captured + `' ` if err := os.WriteFile(clang, []byte(clangScript), 0o755); err != nil { t.Fatal(err) } writeProbeTool(t, lld, "LLD version 22.1.8", filepath.Join(dir, "count")) - probe, err := NewLinuxToolProbe(LinuxToolProbeOptions{ + opts := LinuxToolProbeOptions{ Profile: "x86_64", Architecture: "x86", TargetTriple: "x86_64-linux-gnu", - ClangPath: clang, LLDPath: lld, TempDir: dir, - }) + CompilerPath: clang, LinkerPath: lld, TempDir: dir, + } + addAuxiliaryProbeTools(t, dir, "llvm", &opts) + probe, err := NewLinuxToolProbe(opts) if err != nil { t.Fatal(err) } @@ -383,7 +1294,11 @@ func TestLinuxToolProbeTimeoutAndOutputCap(t *testing.T) { clang := filepath.Join(dir, "clang") lld := filepath.Join(dir, "ld.lld") tool := `#!/bin/sh -if [ "$1" = "--version" ]; then echo 'clang version 22.1.8'; exit 0; fi +case " $* " in + *' --version '*) echo 'clang version 22.1.8'; exit 0 ;; + *' -E -P -x c - '*) echo 'Clang 22 1 8'; exit 0 ;; + *' -### '*) echo '"clang" "-cc1as"' >&2; exit 0 ;; +esac ` + test.body + ` ` if err := os.WriteFile(clang, []byte(tool), 0o755); err != nil { @@ -393,10 +1308,12 @@ if [ "$1" = "--version" ]; then echo 'clang version 22.1.8'; exit 0; fi if err := os.WriteFile(lld, []byte(lldTool), 0o755); err != nil { t.Fatal(err) } - probe, err := NewLinuxToolProbe(LinuxToolProbeOptions{ + opts := LinuxToolProbeOptions{ Profile: "x86_64", Architecture: "x86", TargetTriple: "x86_64-linux-gnu", - ClangPath: clang, LLDPath: lld, TempDir: dir, Timeout: 50 * time.Millisecond, OutputLimit: 32, - }) + CompilerPath: clang, LinkerPath: lld, TempDir: dir, Timeout: 50 * time.Millisecond, OutputLimit: 32, + } + addAuxiliaryProbeTools(t, dir, "llvm", &opts) + probe, err := NewLinuxToolProbe(opts) if err != nil { t.Fatal(err) } @@ -427,30 +1344,58 @@ func TestLinuxProbeShellWithToolsUsesMeasuredVersions(t *testing.T) { } func TestParseLinuxSourceProbeAcceptsKconfigCompilerVariables(t *testing.T) { + shell := &linuxProbeShell{} for _, compiler := range []string{"$CC", "$(CC)", "/pinned/bin/clang"} { command := "echo 'int foo(void) { return 0; }' | " + compiler + " $(CLANG_FLAGS) -x c - -c -o /dev/null -Werror" - source, candidate, err := parseLinuxSourceProbe(command) + source, mode, candidate, err := shell.parseLinuxSourceProbe(command) if err != nil { t.Fatalf("parseLinuxSourceProbe(%q): %v", command, err) } if source != "int foo(void) { return 0; }" { t.Fatalf("source = %q", source) } + if mode != "-c" { + t.Fatalf("mode = %q, want -c", mode) + } if got, want := strings.Join(candidate, " "), "-fintegrated-as -Werror"; got != want { t.Fatalf("candidate = %q, want %q", got, want) } } } +func TestParseLinuxSourceProbeAcceptsSelectedTargetPrefixedGCC(t *testing.T) { + shell := &linuxProbeShell{ + toolProbe: &LinuxToolProbe{compilerPath: "/pinned/bin/x86_64-linux-gnu-gcc"}, + } + command := "echo 'int foo(void) { return 0; }' | x86_64-linux-gnu-gcc -x c - -c -o /dev/null -Werror" + source, mode, candidate, err := shell.parseLinuxSourceProbe(command) + if err != nil { + t.Fatal(err) + } + if source != "int foo(void) { return 0; }" { + t.Fatalf("source = %q", source) + } + if mode != "-c" { + t.Fatalf("mode = %q, want -c", mode) + } + if got, want := strings.Join(candidate, " "), "-Werror"; got != want { + t.Fatalf("candidate = %q, want %q", got, want) + } +} + func TestParseLinuxSourceProbeUnquotesVPCLMULImmediate(t *testing.T) { + shell := &linuxProbeShell{} command := `printf "%b\n" "vpclmulqdq \$0x10,%ymm0,%ymm1,%ymm2" | clang -fintegrated-as -Wa,--fatal-warnings -c -x assembler-with-cpp -o /dev/null -` - source, candidate, err := parseLinuxSourceProbe(command) + source, mode, candidate, err := shell.parseLinuxSourceProbe(command) if err != nil { t.Fatal(err) } if want := `vpclmulqdq $0x10,%ymm0,%ymm1,%ymm2`; source != want { t.Fatalf("source = %q, want %q", source, want) } + if mode != "-c" { + t.Fatalf("mode = %q, want -c", mode) + } if got, want := strings.Join(candidate, " "), "-fintegrated-as -Wa,--fatal-warnings"; got != want { t.Fatalf("candidate = %q, want %q", got, want) } @@ -458,7 +1403,16 @@ func TestParseLinuxSourceProbeUnquotesVPCLMULImmediate(t *testing.T) { func TestKnownRELRProbeAcceptsPinnedToolPaths(t *testing.T) { command := `env "CC=/pinned/bin/clang" "LD=/pinned/bin/ld.lld" "NM=llvm-nm" "OBJCOPY=llvm-objcopy" /src/scripts/tools-support-relr.sh` - if !isKnownRELRProbe(command) { - t.Fatalf("isKnownRELRProbe(%q) = false", command) + shell := &linuxProbeShell{ + toolProbe: &LinuxToolProbe{ + compilerPath: "/pinned/bin/clang", + linkerPath: "/pinned/bin/ld.lld", + nmPath: "/tools/llvm-nm", + objcopyPath: "/tools/llvm-objcopy", + }, + } + nm, objcopy, recognized, err := shell.relrProbeTools(command) + if err != nil || !recognized || nm != "llvm-nm" || objcopy != "llvm-objcopy" { + t.Fatalf("relrProbeTools(%q) = %q, %q, %v, %v", command, nm, objcopy, recognized, err) } } diff --git a/internal/map_directory_kconfig.bzl b/internal/map_directory_kconfig.bzl index 3cf49146..f36fb82e 100644 --- a/internal/map_directory_kconfig.bzl +++ b/internal/map_directory_kconfig.bzl @@ -1,6 +1,10 @@ """Bazel 9 feasibility spike for execution-time Kconfig graph expansion.""" -load("@rules_cc//cc:action_names.bzl", "C_COMPILE_ACTION_NAME") +load( + "@rules_cc//cc:action_names.bzl", + "CPP_LINK_EXECUTABLE_ACTION_NAME", + "C_COMPILE_ACTION_NAME", +) load( "@rules_cc//cc:find_cc_toolchain.bzl", "CC_TOOLCHAIN_TYPE", @@ -14,6 +18,10 @@ visibility("//tests/map_directory") _HEX_DIGITS = "0123456789abcdef" _PLAN_VERSION = "v1" _SOURCE_INPUT_PREFIX = "source:" +_GCC_TOOLCHAIN_SETTING = "//tests/map_directory:use_gcc_toolchain" +_COMPILE_OUTPUT_SENTINEL = "__linux_bzl_map_output__.o" +_COMPILE_RECIPE_FLAGS_SENTINEL = "-D__LINUX_BZL_MAP_RECIPE_FLAGS__" +_COMPILE_SOURCE_SENTINEL = "__linux_bzl_map_source__.c" def _is_decimal(value): if not value: @@ -77,6 +85,7 @@ def _map_compiler_selected_objects( if source_key not in additional_inputs: fail("map_directory plan selected undeclared source %r" % canonical_path) source_markers[index] = struct( + canonical_path = canonical_path, file = additional_inputs[source_key], marker = children[path], ) @@ -90,6 +99,16 @@ def _map_compiler_selected_objects( if not compile_paths: fail("map_directory plan selected no compile actions") + # The compact plan's source markers are the union of the source-input + # closures for the selected recipes. Until the plan carries a per-recipe + # closure, give every mapped compile that conservative union. In + # particular, declaring only the primary .c file would leave quoted and + # source-tree headers outside remote/sandboxed actions. + selected_source_inputs = [ + source_markers[index].file + for index in sorted(source_markers.keys()) + ] + declared_outputs = {} for path in compile_paths: marker = children[path] @@ -113,25 +132,34 @@ def _map_compiler_selected_objects( source = source_markers[source_index] output = template_ctx.declare_file(output_path, directory = output_directory) args = template_ctx.args() - args.add("--target=" + additional_params["target_triple"]) - args.add(additional_params["compile_flag"]) - args.add("-Werror") - args.add("-c") + args.add("-recipe") + args.add(marker) + args.add("-compiler") + args.add(tools["cc"]) + args.add("-source") args.add(source.file) - args.add("-o") + args.add("-output") args.add(output) + args.add("-expected_source") + args.add(source.canonical_path) + args.add("-expected_object") + args.add(object_path) + args.add("-expected_content_id") + args.add(content_id) + for index in range(int(additional_params["action_arg_count"])): + args.add("-action_arg") + args.add(additional_params["action_arg_%d" % index]) template_ctx.run( - executable = tools["cc"], - inputs = [ + executable = tools["recipe_runner"], + inputs = selected_source_inputs + [ marker, probe_marker, - source.file, source.marker, ], tools = [tools["cc_files"]], outputs = [output], arguments = [args], - progress_message = "Compiling a compiler-selected Kconfig object", + progress_message = "Replaying a compiler-selected Kconfig recipe", ) def _tool_file_for_path(cc_toolchain, tool_path, name): @@ -150,21 +178,38 @@ def _tool_file_for_path(cc_toolchain, tool_path, name): ) return matches[0] -def _tool_file_for_basename(cc_toolchain, basename): - basenames = [basename, basename + ".exe"] - matches = [ - file - for file in cc_toolchain.all_files.to_list() - if file.basename in basenames - ] - if len(matches) != 1: - fail( - "selected C/C++ toolchain must provide exactly one %s; found: %s" % ( - basename, - ", ".join(sorted([file.path for file in matches])) or "none", - ), +def _tool_file_for_sibling(cc_toolchain, tool, basename, name): + path = tool.dirname + "/" + basename + return _tool_file_for_path(cc_toolchain, path, name) + +def _single_file(target, name): + files = target[DefaultInfo].files.to_list() + if len(files) != 1: + fail("%s must provide exactly one executable File; found: %s" % ( + name, + ", ".join(sorted([file.path for file in files])) or "none", + )) + return files[0] + +def _selected_probe_tools(ctx, cc_toolchain, feature_configuration, compiler, compiler_family): + if compiler_family == "clang": + link_driver_path = cc_common.get_tool_for_action( + feature_configuration = feature_configuration, + action_name = CPP_LINK_EXECUTABLE_ACTION_NAME, ) - return matches[0] + link_driver = _tool_file_for_path(cc_toolchain, link_driver_path, "C++ link driver") + return struct( + archiver = _tool_file_for_sibling(cc_toolchain, compiler, "llvm-ar", "archiver"), + linker = _tool_file_for_sibling(cc_toolchain, link_driver, "ld.lld", "linker"), + nm = _tool_file_for_sibling(cc_toolchain, compiler, "llvm-nm", "nm"), + objcopy = _tool_file_for_sibling(cc_toolchain, compiler, "llvm-objcopy", "objcopy"), + ) + return struct( + archiver = _single_file(ctx.attr._gcc_ar, "GCC test archiver"), + linker = _single_file(ctx.attr._gcc_ld, "GCC test linker"), + nm = _single_file(ctx.attr._gcc_nm, "GCC test nm"), + objcopy = _single_file(ctx.attr._gcc_objcopy, "GCC test objcopy"), + ) def _canonical_sources(ctx): prefix = ctx.label.package + "/" if ctx.label.package else "" @@ -180,6 +225,138 @@ def _canonical_sources(ctx): sources[canonical_path] = file return sources +def _configured_compile_action(ctx, cc_toolchain, feature_configuration): + variables = cc_common.create_compile_variables( + feature_configuration = feature_configuration, + cc_toolchain = cc_toolchain, + output_file = _COMPILE_OUTPUT_SENTINEL, + source_file = _COMPILE_SOURCE_SENTINEL, + user_compile_flags = ctx.fragments.cpp.copts + ctx.fragments.cpp.conlyopts + [_COMPILE_RECIPE_FLAGS_SENTINEL], + ) + action_args = cc_common.get_memory_inefficient_command_line( + feature_configuration = feature_configuration, + action_name = C_COMPILE_ACTION_NAME, + variables = variables, + ) + if len([argument for argument in action_args if argument == _COMPILE_RECIPE_FLAGS_SENTINEL]) != 1: + fail("selected C/C++ toolchain must preserve exactly one Kbuild flags marker") + if not any([_COMPILE_SOURCE_SENTINEL in argument for argument in action_args]): + fail("selected C/C++ toolchain compile command does not contain its source operand") + if not any([_COMPILE_OUTPUT_SENTINEL in argument for argument in action_args]): + fail("selected C/C++ toolchain compile command does not contain its output operand") + + controlled = {} + for index, argument in enumerate(action_args): + if argument == _COMPILE_RECIPE_FLAGS_SENTINEL or argument == "-c" or _COMPILE_SOURCE_SENTINEL in argument or _COMPILE_OUTPUT_SENTINEL in argument: + controlled[index] = True + if index > 0 and action_args[index - 1] in ["-o", "--output"]: + controlled[index - 1] = True + flags = [ + argument + for index, argument in enumerate(action_args) + if index not in controlled + ] + prohibited = [ + "--output", + "--save-temps", + "--serialize-diagnostics", + "-E", + "-M", + "-MD", + "-MF", + "-MJ", + "-MM", + "-MMD", + "-MQ", + "-MT", + "-S", + "-c", + "-o", + "-save-temps", + ] + prohibited_prefixes = [ + "--output=", + "--save-temps=", + "--serialize-diagnostics=", + "-MF=", + "-MJ=", + "-save-temps=", + ] + for flag in flags: + if flag.startswith("@") or flag in prohibited: + fail("selected C/C++ toolchain produced unsafe compiler prefix argument %r" % flag) + for prefix in prohibited_prefixes: + if flag.startswith(prefix): + fail("selected C/C++ toolchain produced unsafe compiler prefix argument %r" % flag) + return struct( + action_args = action_args, + environment = dict(cc_common.get_environment_variables( + feature_configuration = feature_configuration, + action_name = C_COMPILE_ACTION_NAME, + variables = variables, + )), + probe_prefix = flags, + ) + +def _configured_linker_driver_prefix(ctx, cc_toolchain, feature_configuration): + """Returns selected executable-link flags without Bazel-owned operands.""" + sentinel = "__linux_bzl_probe_output__" + variables = cc_common.create_link_variables( + cc_toolchain = cc_toolchain, + feature_configuration = feature_configuration, + is_linking_dynamic_library = False, + is_using_linker = True, + output_file = sentinel, + user_link_flags = ctx.fragments.cpp.linkopts, + ) + command_line = cc_common.get_memory_inefficient_command_line( + feature_configuration = feature_configuration, + action_name = CPP_LINK_EXECUTABLE_ACTION_NAME, + variables = variables, + ) + flags = [] + skip_output = False + expect_operand = None + safe_operand_options = [ + "-resource-dir", + "-target", + ] + for argument in command_line: + if skip_output: + if argument != sentinel: + fail("selected C/C++ toolchain link command has unexpected output operand %r" % argument) + skip_output = False + elif expect_operand != None: + if not argument or argument.startswith("-") or argument.startswith("@"): + fail("selected C/C++ toolchain link command has unsafe %s operand %r" % (expect_operand, argument)) + flags.append(argument) + expect_operand = None + elif argument == "-o": + skip_output = True + elif argument == sentinel or argument == "--output=" + sentinel: + pass + elif argument in safe_operand_options: + flags.append(argument) + expect_operand = argument + elif argument.startswith("@") or not argument.startswith("-"): + fail("selected C/C++ toolchain produced unsafe linker-driver prefix argument %r" % argument) + elif argument in ["-c", "-E", "-S", "--output"]: + fail("selected C/C++ toolchain produced unsafe linker-driver prefix argument %r" % argument) + else: + flags.append(argument) + if skip_output: + fail("selected C/C++ toolchain link command is missing its output operand") + if expect_operand != None: + fail("selected C/C++ toolchain link command is missing its %s operand" % expect_operand) + return struct( + environment = dict(cc_common.get_environment_variables( + feature_configuration = feature_configuration, + action_name = CPP_LINK_EXECUTABLE_ACTION_NAME, + variables = variables, + )), + flags = flags, + ) + def _linux_map_directory_kconfig_spike_impl(ctx): cc_toolchain = find_cpp_toolchain(ctx) feature_configuration = cc_common.configure_features( @@ -193,7 +370,24 @@ def _linux_map_directory_kconfig_spike_impl(ctx): action_name = C_COMPILE_ACTION_NAME, ) compiler = _tool_file_for_path(cc_toolchain, compiler_path, "C compiler") - linker = _tool_file_for_basename(cc_toolchain, "ld.lld") + compile_action = _configured_compile_action(ctx, cc_toolchain, feature_configuration) + compiler_prefix = compile_action.probe_prefix + linker_driver = _configured_linker_driver_prefix(ctx, cc_toolchain, feature_configuration) + tool_environment = dict(compile_action.environment) + tool_environment["EXECROOT"] = "." + for name, value in linker_driver.environment.items(): + if name in tool_environment and tool_environment[name] != value: + fail("map_directory spike has conflicting compile/link toolchain environment %s" % name) + tool_environment[name] = value + compiler_id = cc_toolchain.compiler.lower() + compiler_family = "" + if "clang" in compiler_id: + compiler_family = "clang" + elif "gcc" in compiler_id: + compiler_family = "gcc" + else: + fail("map_directory spike does not recognize selected compiler kind %r for %s" % (cc_toolchain.compiler, compiler.path)) + probe_tools = _selected_probe_tools(ctx, cc_toolchain, feature_configuration, compiler, compiler_family) sources = _canonical_sources(ctx) plan = ctx.actions.declare_directory(ctx.label.name + ".plan") @@ -220,25 +414,44 @@ def _linux_map_directory_kconfig_spike_impl(ctx): plan_args.add("-probe_cc") plan_args.add(compiler) plan_args.add("-probe_ld") - plan_args.add(linker) + plan_args.add(probe_tools.linker) + plan_args.add("-probe_ar") + plan_args.add(probe_tools.archiver) + plan_args.add("-probe_nm") + plan_args.add(probe_tools.nm) + plan_args.add("-probe_objcopy") + plan_args.add(probe_tools.objcopy) + for flag in compiler_prefix: + plan_args.add("-probe_cc_arg") + plan_args.add(flag) + for flag in linker_driver.flags: + plan_args.add("-probe_link_arg") + plan_args.add(flag) plan_args.add("-compact_action_plan_out") plan_args.add_all([plan], expand_directories = False) ctx.actions.run( executable = ctx.attr._kconfig_parse[DefaultInfo].files_to_run, inputs = [ctx.file.kconfig, ctx.file.kbuild, ctx.file.config] + ctx.files.srcs, - tools = cc_toolchain.all_files, + tools = depset( + direct = [probe_tools.archiver, probe_tools.linker, probe_tools.nm, probe_tools.objcopy], + transitive = [cc_toolchain.all_files], + ), outputs = [plan], arguments = [plan_args], mnemonic = "MapDirectoryKconfigPlan", progress_message = "Probing the selected compiler and generating a Kconfig action plan for %{label}", execution_requirements = {"supports-path-mapping": "1"}, + env = tool_environment, toolchain = CC_TOOLCHAIN_TYPE, ) additional_inputs = {} for canonical_path, file in sources.items(): additional_inputs[_SOURCE_INPUT_PREFIX + canonical_path] = file + map_params = {"action_arg_count": str(len(compile_action.action_args))} + for index, flag in enumerate(compile_action.action_args): + map_params["action_arg_%d" % index] = flag ctx.actions.map_directory( implementation = _map_compiler_selected_objects, input_directories = {"plan": plan}, @@ -247,12 +460,11 @@ def _linux_map_directory_kconfig_spike_impl(ctx): tools = { "cc": compiler, "cc_files": cc_toolchain.all_files, + "recipe_runner": ctx.attr._recipe_runner[DefaultInfo].files_to_run, }, - additional_params = { - "compile_flag": "-fno-omit-frame-pointer", - "target_triple": ctx.attr.target_triple, - }, + additional_params = map_params, execution_requirements = {"supports-path-mapping": "1"}, + env = tool_environment, mnemonic = "MapDirectoryKconfigCompile", toolchain = CC_TOOLCHAIN_TYPE, ) @@ -264,14 +476,46 @@ def _linux_map_directory_kconfig_spike_impl(ctx): validation_args.add_all([objects], expand_directories = False) validation_args.add("-out") validation_args.add(validated) + validation_args.add("-compiler") + validation_args.add(compiler) + validation_args.add("-linker") + validation_args.add(probe_tools.linker) + validation_args.add("-archiver") + validation_args.add(probe_tools.archiver) + validation_args.add("-nm") + validation_args.add(probe_tools.nm) + validation_args.add("-objcopy") + validation_args.add(probe_tools.objcopy) + validation_args.add("-target_profile") + validation_args.add(ctx.attr.target_profile) + validation_args.add("-linux_arch") + validation_args.add(ctx.attr.linux_arch) + validation_args.add("-target_triple") + validation_args.add(ctx.attr.target_triple) + for flag in compiler_prefix: + validation_args.add("-compiler_arg") + validation_args.add(flag) + for flag in linker_driver.flags: + validation_args.add("-linker_driver_arg") + validation_args.add(flag) ctx.actions.run( executable = ctx.executable.validator, - inputs = [plan, objects], + inputs = [ + plan, + objects, + compiler, + probe_tools.archiver, + probe_tools.linker, + probe_tools.nm, + probe_tools.objcopy, + ], + tools = [cc_toolchain.all_files], outputs = [validated], arguments = [validation_args], mnemonic = "MapDirectoryKconfigValidate", progress_message = "Validating mapped compiler output for %{label}", execution_requirements = {"supports-path-mapping": "1"}, + env = tool_environment, ) return [ @@ -294,12 +538,270 @@ linux_map_directory_kconfig_spike = rule( "target_profile": attr.string(default = "x86_64"), "target_triple": attr.string(default = "x86_64-linux-gnu"), "validator": attr.label(cfg = "exec", executable = True, mandatory = True), + "_gcc_ar": attr.label(default = Label("@map_directory_gcc_x86_64//:ar")), + "_gcc_ld": attr.label(default = Label("@map_directory_gcc_x86_64//:ld")), + "_gcc_nm": attr.label(default = Label("@map_directory_gcc_x86_64//:nm")), + "_gcc_objcopy": attr.label(default = Label("@map_directory_gcc_x86_64//:objcopy")), "_kconfig_parse": attr.label( cfg = "exec", default = Label("//internal/cmd/kconfig_parse:kconfig_parse"), executable = True, ), + "_recipe_runner": attr.label( + cfg = "exec", + default = Label("//internal/cmd/mapdirectoryrecipe"), + executable = True, + ), }, fragments = ["cpp"], toolchains = use_cc_toolchain(), ) + +def _linux_upstream_gcc_kconfig_impl(ctx): + """Resolves the complete upstream Kconfig tree with the selected GCC.""" + cc_toolchain = find_cpp_toolchain(ctx) + feature_configuration = cc_common.configure_features( + ctx = ctx, + cc_toolchain = cc_toolchain, + requested_features = ctx.features, + unsupported_features = ctx.disabled_features, + ) + compiler_path = cc_common.get_tool_for_action( + feature_configuration = feature_configuration, + action_name = C_COMPILE_ACTION_NAME, + ) + compiler = _tool_file_for_path(cc_toolchain, compiler_path, "C compiler") + if "gcc" not in cc_toolchain.compiler.lower(): + fail("upstream GCC Kconfig test selected compiler kind %r, want gcc" % cc_toolchain.compiler) + probe_tools = _selected_probe_tools(ctx, cc_toolchain, feature_configuration, compiler, "gcc") + compile_action = _configured_compile_action(ctx, cc_toolchain, feature_configuration) + compiler_prefix = compile_action.probe_prefix + linker_driver = _configured_linker_driver_prefix(ctx, cc_toolchain, feature_configuration) + tool_environment = dict(compile_action.environment) + tool_environment["EXECROOT"] = "." + for name, value in linker_driver.environment.items(): + if name in tool_environment and tool_environment[name] != value: + fail("upstream GCC Kconfig test has conflicting compile/link toolchain environment %s" % name) + tool_environment[name] = value + + resolved = ctx.actions.declare_file(ctx.label.name + ".config") + auto_conf = ctx.actions.declare_file(ctx.label.name + ".auto.conf") + auto_conf_cmd = ctx.actions.declare_file(ctx.label.name + ".auto.conf.cmd") + autoconf = ctx.actions.declare_file(ctx.label.name + ".autoconf.h") + rustc_cfg = ctx.actions.declare_file(ctx.label.name + ".rustc_cfg") + kernel_release = ctx.actions.declare_file(ctx.label.name + ".kernel.release") + validated = ctx.actions.declare_file(ctx.label.name + ".validated") + + args = ctx.actions.args() + args.add("-root") + args.add(ctx.file.kconfig) + args.add("-srctree") + args.add(ctx.file.kconfig.dirname) + args.add("-resolve_config") + args.add(ctx.file.config, format = ctx.attr.config_name + "=%s") + args.add("-resolved_config_out") + args.add(resolved) + args.add("-resolved_auto_conf_out") + args.add(auto_conf) + args.add("-resolved_auto_conf_cmd_out") + args.add(auto_conf_cmd) + args.add("-resolved_autoconf_out") + args.add(autoconf) + args.add("-resolved_rustc_cfg_out") + args.add(rustc_cfg) + args.add("-resolved_kernel_release_out") + args.add(kernel_release) + args.add("-kernel_version") + args.add("6.18.39") + args.add("-target_profile") + args.add("x86_64") + args.add("-linux_arch") + args.add("x86") + args.add("-target_triple") + args.add("x86_64-linux-gnu") + args.add("-probe_cc") + args.add(compiler) + args.add("-probe_ld") + args.add(probe_tools.linker) + args.add("-probe_ar") + args.add(probe_tools.archiver) + args.add("-probe_nm") + args.add(probe_tools.nm) + args.add("-probe_objcopy") + args.add(probe_tools.objcopy) + + # gcc_toolchain's sysroot is materialized through absolute symlinks and its + # plugin headers are not exposed as declared targets. Fail these two + # capabilities closed explicitly, so local sandbox, standalone, and remote + # execution cannot select different Kconfig graphs from ambient files. + args.add("-probe_allow_cc_can_link=false") + args.add("-probe_allow_gcc_plugins=false") + for flag in compiler_prefix: + args.add("-probe_cc_arg") + args.add(flag) + for flag in linker_driver.flags: + args.add("-probe_link_arg") + args.add(flag) + + resolved_outputs = [ + resolved, + auto_conf, + auto_conf_cmd, + autoconf, + rustc_cfg, + kernel_release, + ] + ctx.actions.run( + executable = ctx.attr._kconfig_parse[DefaultInfo].files_to_run, + inputs = depset( + direct = [ctx.file.kconfig, ctx.file.config], + transitive = [ctx.attr.kconfig_files[DefaultInfo].files], + ), + tools = depset( + direct = [probe_tools.archiver, probe_tools.linker, probe_tools.nm, probe_tools.objcopy], + transitive = [cc_toolchain.all_files], + ), + outputs = resolved_outputs, + arguments = [args], + mnemonic = "UpstreamGCCKconfigResolve", + progress_message = "Resolving upstream Linux 6.18.39 Kconfig with selected GCC for %{label}", + execution_requirements = {"supports-path-mapping": "1"}, + env = tool_environment, + toolchain = CC_TOOLCHAIN_TYPE, + ) + + validation_args = ctx.actions.args() + validation_args.add("-config") + validation_args.add(resolved) + validation_args.add("-out") + validation_args.add(validated) + ctx.actions.run( + executable = ctx.executable.validator, + inputs = [resolved], + outputs = [validated], + arguments = [validation_args], + mnemonic = "UpstreamGCCKconfigValidate", + progress_message = "Validating upstream GCC Kconfig fields for %{label}", + execution_requirements = {"supports-path-mapping": "1"}, + ) + return [ + DefaultInfo(files = depset([validated])), + OutputGroupInfo(resolved_config = depset(resolved_outputs)), + ] + +_linux_upstream_gcc_kconfig = rule( + implementation = _linux_upstream_gcc_kconfig_impl, + attrs = { + "config": attr.label(allow_single_file = True, mandatory = True), + "config_name": attr.string(default = "upstream_gcc"), + "kconfig": attr.label(allow_single_file = True, mandatory = True), + "kconfig_files": attr.label(mandatory = True), + "validator": attr.label(cfg = "exec", executable = True, mandatory = True), + "_gcc_ar": attr.label(default = Label("@map_directory_gcc_x86_64//:ar")), + "_gcc_ld": attr.label(default = Label("@map_directory_gcc_x86_64//:ld")), + "_gcc_nm": attr.label(default = Label("@map_directory_gcc_x86_64//:nm")), + "_gcc_objcopy": attr.label(default = Label("@map_directory_gcc_x86_64//:objcopy")), + "_kconfig_parse": attr.label( + cfg = "exec", + default = Label("//internal/cmd/kconfig_parse:kconfig_parse"), + executable = True, + ), + }, + fragments = ["cpp"], + toolchains = use_cc_toolchain(), +) + +def _map_directory_probe_identity_comparison_impl(ctx): + output = ctx.actions.declare_file(ctx.label.name + ".validated") + args = ctx.actions.args() + args.add("-plan") + args.add_all([ctx.file.first], expand_directories = False) + args.add("-other_plan") + args.add_all([ctx.file.second], expand_directories = False) + args.add("-out") + args.add(output) + ctx.actions.run( + executable = ctx.executable.validator, + inputs = [ctx.file.first, ctx.file.second], + outputs = [output], + arguments = [args], + mnemonic = "MapDirectoryKconfigCompare", + progress_message = "Comparing compiler-selected Kconfig plan identities for %{label}", + execution_requirements = {"supports-path-mapping": "1"}, + ) + return DefaultInfo(files = depset([output])) + +map_directory_probe_identity_comparison = rule( + implementation = _map_directory_probe_identity_comparison_impl, + attrs = { + "first": attr.label(allow_single_file = True, mandatory = True), + "second": attr.label(allow_single_file = True, mandatory = True), + "validator": attr.label(cfg = "exec", executable = True, mandatory = True), + }, +) + +def _select_gcc_toolchain_impl(settings, _attr): + return { + _GCC_TOOLCHAIN_SETTING: True, + "//command_line_option:copt": settings["//command_line_option:copt"] + [ + "-DMAP_DIRECTORY_TOOLCHAIN_PREFIX_REPLAYED=1", + ], + } + +_select_gcc_toolchain = transition( + implementation = _select_gcc_toolchain_impl, + inputs = ["//command_line_option:copt"], + outputs = [ + _GCC_TOOLCHAIN_SETTING, + "//command_line_option:copt", + ], +) + +def _gcc_spike_transition_impl(ctx): + actual = ctx.attr.actual[0] + providers = [actual[DefaultInfo]] + if OutputGroupInfo in actual: + providers.append(actual[OutputGroupInfo]) + return providers + +_gcc_spike_transition = rule( + implementation = _gcc_spike_transition_impl, + attrs = { + "actual": attr.label(cfg = _select_gcc_toolchain, mandatory = True), + "_allowlist_function_transition": attr.label( + default = "@bazel_tools//tools/allowlists/function_transition_allowlist", + ), + }, +) + +def linux_map_directory_gcc_kconfig_spike(name, tags = [], visibility = None, **kwargs): + """Creates a private GCC-selected variant of the map_directory spike.""" + actual_name = name + "_gcc_impl" + linux_map_directory_kconfig_spike( + name = actual_name, + tags = tags, + visibility = ["//visibility:private"], + **kwargs + ) + _gcc_spike_transition( + name = name, + actual = ":" + actual_name, + tags = tags, + visibility = visibility, + ) + +def linux_upstream_gcc_kconfig_test(name, tags = [], visibility = None, **kwargs): + """Resolves upstream Linux Kconfig under the registered hermetic GCC.""" + actual_name = name + "_gcc_impl" + _linux_upstream_gcc_kconfig( + name = actual_name, + tags = tags, + visibility = ["//visibility:private"], + **kwargs + ) + _gcc_spike_transition( + name = name, + actual = ":" + actual_name, + tags = tags, + visibility = visibility, + ) diff --git a/tests/map_directory/BUILD.bazel b/tests/map_directory/BUILD.bazel index 08dddded..12318eac 100644 --- a/tests/map_directory/BUILD.bazel +++ b/tests/map_directory/BUILD.bazel @@ -1,21 +1,85 @@ load("@bazel_skylib//rules:build_test.bzl", "build_test") +load("@bazel_skylib//rules:common_settings.bzl", "bool_flag") load("@rules_go//go:def.bzl", "go_binary") -load("//internal:map_directory_kconfig.bzl", "linux_map_directory_kconfig_spike") +load( + "//internal:map_directory_kconfig.bzl", + "linux_map_directory_gcc_kconfig_spike", + "linux_map_directory_kconfig_spike", + "linux_upstream_gcc_kconfig_test", + "map_directory_probe_identity_comparison", +) package(default_visibility = ["//visibility:private"]) +bool_flag( + name = "use_gcc_toolchain", + build_setting_default = False, +) + +config_setting( + name = "gcc_toolchain_selected", + flag_values = {":use_gcc_toolchain": "true"}, +) + +toolchain( + name = "gcc_cc_toolchain", + exec_compatible_with = [ + "@platforms//cpu:x86_64", + "@platforms//os:linux", + ], + target_compatible_with = [ + "@platforms//cpu:x86_64", + "@platforms//os:linux", + ], + target_settings = [":gcc_toolchain_selected"], + toolchain = "@map_directory_gcc_x86_64//:_cc_toolchain", + toolchain_type = "@rules_cc//cc:toolchain_type", +) + go_binary( name = "validator", srcs = ["validator.go"], pure = "on", + deps = ["//internal/kconfig"], +) + +go_binary( + name = "upstream_validator", + srcs = ["upstream_validator.go"], + pure = "on", ) linux_map_directory_kconfig_spike( name = "compiler_capabilities", srcs = [ + "clang_selected.c", + "gcc_selected.c", + "include/linux/compiler-version.h", + "include/linux/compiler_types.h", + "include/linux/kconfig.h", + "required_local_header.h", + "supported.c", + "unsupported.c", + ], + config = "base.config", + kbuild = "Kbuild", + kconfig = "Kconfig", + tags = [ + "manual", + "requires-bazel-9", + ], + validator = ":validator", +) + +linux_map_directory_gcc_kconfig_spike( + name = "gcc_compiler_capabilities", + srcs = [ + "clang_selected.c", + "gcc_selected.c", "include/linux/compiler-version.h", "include/linux/compiler_types.h", "include/linux/kconfig.h", + "required_local_header.h", "supported.c", "unsupported.c", ], @@ -29,6 +93,49 @@ linux_map_directory_kconfig_spike( validator = ":validator", ) +linux_upstream_gcc_kconfig_test( + name = "upstream_gcc_kconfig", + config = "@map_directory_linux_6_18_39//:arch/x86/configs/x86_64_defconfig", + kconfig = "@map_directory_linux_6_18_39//:Kconfig", + kconfig_files = "@map_directory_linux_6_18_39//:kconfig_files", + tags = [ + "manual", + "requires-bazel-9", + ], + validator = ":upstream_validator", +) + +filegroup( + name = "clang_plan", + srcs = [":compiler_capabilities"], + output_group = "plan", + tags = [ + "manual", + "requires-bazel-9", + ], +) + +filegroup( + name = "gcc_plan", + srcs = [":gcc_compiler_capabilities"], + output_group = "plan", + tags = [ + "manual", + "requires-bazel-9", + ], +) + +map_directory_probe_identity_comparison( + name = "distinct_compiler_plan_identities", + first = ":clang_plan", + second = ":gcc_plan", + tags = [ + "manual", + "requires-bazel-9", + ], + validator = ":validator", +) + build_test( name = "compiler_capabilities_e2e_test", tags = [ @@ -37,3 +144,30 @@ build_test( ], targets = [":compiler_capabilities"], ) + +build_test( + name = "gcc_compiler_capabilities_e2e_test", + tags = [ + "manual", + "requires-bazel-9", + ], + targets = [":gcc_compiler_capabilities"], +) + +build_test( + name = "upstream_gcc_kconfig_e2e_test", + tags = [ + "manual", + "requires-bazel-9", + ], + targets = [":upstream_gcc_kconfig"], +) + +build_test( + name = "distinct_compiler_plan_identities_e2e_test", + tags = [ + "manual", + "requires-bazel-9", + ], + targets = [":distinct_compiler_plan_identities"], +) diff --git a/tests/map_directory/Kbuild b/tests/map_directory/Kbuild index e1e8581f..3d688157 100644 --- a/tests/map_directory/Kbuild +++ b/tests/map_directory/Kbuild @@ -1,4 +1,8 @@ obj-$(CONFIG_MAP_DIRECTORY_CC_SUPPORTED) += supported.o obj-$(CONFIG_MAP_DIRECTORY_CC_UNSUPPORTED) += unsupported.o +obj-$(CONFIG_MAP_DIRECTORY_CLANG_SELECTED) += clang_selected.o +obj-$(CONFIG_MAP_DIRECTORY_GCC_SELECTED) += gcc_selected.o -CFLAGS_supported.o += -fno-omit-frame-pointer +CFLAGS_supported.o += -fno-omit-frame-pointer -DMAP_DIRECTORY_RECIPE_REPLAYED=1 +CFLAGS_clang_selected.o += -DMAP_DIRECTORY_CLANG_RECIPE_REPLAYED=1 +CFLAGS_gcc_selected.o += -DMAP_DIRECTORY_GCC_RECIPE_REPLAYED=1 diff --git a/tests/map_directory/Kconfig b/tests/map_directory/Kconfig index 349dfbcb..35a650b6 100644 --- a/tests/map_directory/Kconfig +++ b/tests/map_directory/Kconfig @@ -1,9 +1,25 @@ mainmenu "map_directory compiler capability fixture" +comma := , if-success = $(shell,{ $(1); } >/dev/null 2>&1 && echo "$(2)" || echo "$(3)") success = $(if-success,$(1),y,n) cc-option = $(success,$(CC) -Werror $(CLANG_FLAGS) $(1) -c -x c /dev/null -o /dev/null) +cc-info := $(shell,$(srctree)/scripts/cc-version.sh $(CC)) +$(error-if,$(success,test -z "$(cc-info)"),Sorry$(comma) this C compiler is not supported.) +cc-name := $(shell,set -- $(cc-info) && echo $1) +cc-version := $(shell,set -- $(cc-info) && echo $2) + +as-info := $(shell,$(srctree)/scripts/as-version.sh $(CC) $(CLANG_FLAGS)) +$(error-if,$(success,test -z "$(as-info)"),Sorry$(comma) this assembler is not supported.) +as-name := $(shell,set -- $(as-info) && echo $1) +as-version := $(shell,set -- $(as-info) && echo $2) + +ld-info := $(shell,$(srctree)/scripts/ld-version.sh $(LD)) +$(error-if,$(success,test -z "$(ld-info)"),Sorry$(comma) this linker is not supported.) +ld-name := $(shell,set -- $(ld-info) && echo $1) +ld-version := $(shell,set -- $(ld-info) && echo $2) + config 64BIT def_bool y @@ -13,8 +29,56 @@ config X86 config X86_64 def_bool X86 && 64BIT +config CC_IS_GCC + def_bool $(success,test "$(cc-name)" = GCC) + +config GCC_VERSION + int + default $(cc-version) if CC_IS_GCC + default 0 + +config CC_IS_CLANG + def_bool $(success,test "$(cc-name)" = Clang) + +config CLANG_VERSION + int + default $(cc-version) if CC_IS_CLANG + default 0 + +config AS_IS_GNU + def_bool $(success,test "$(as-name)" = GNU) + +config AS_IS_LLVM + def_bool $(success,test "$(as-name)" = LLVM) + +config AS_VERSION + int + default $(as-version) + +config LD_IS_BFD + def_bool $(success,test "$(ld-name)" = BFD) + +config LD_IS_LLD + def_bool $(success,test "$(ld-name)" = LLD) + +config LD_VERSION + int + default $(ld-version) if LD_IS_BFD + default 0 + +config LLD_VERSION + int + default $(ld-version) if LD_IS_LLD + default 0 + config MAP_DIRECTORY_CC_SUPPORTED def_bool $(cc-option,-fno-omit-frame-pointer) config MAP_DIRECTORY_CC_UNSUPPORTED def_bool $(cc-option,-fno-linux-bzl-map-directory-spike) + +config MAP_DIRECTORY_CLANG_SELECTED + def_bool CC_IS_CLANG && CLANG_VERSION = 220108 && AS_IS_LLVM && AS_VERSION = 0 && LD_IS_LLD && LLD_VERSION = 220108 + +config MAP_DIRECTORY_GCC_SELECTED + def_bool CC_IS_GCC && GCC_VERSION = 150200 && AS_IS_GNU && AS_VERSION = 24600 && LD_IS_BFD && LD_VERSION = 24600 diff --git a/tests/map_directory/clang_selected.c b/tests/map_directory/clang_selected.c new file mode 100644 index 00000000..1acf8fc4 --- /dev/null +++ b/tests/map_directory/clang_selected.c @@ -0,0 +1,8 @@ +#ifndef MAP_DIRECTORY_CLANG_RECIPE_REPLAYED +#error "the Clang-selected mapped action must replay its emitted Kbuild flags" +#endif + +int map_directory_clang_selected(void) +{ + return 22; +} diff --git a/tests/map_directory/gcc_selected.c b/tests/map_directory/gcc_selected.c new file mode 100644 index 00000000..148dfeac --- /dev/null +++ b/tests/map_directory/gcc_selected.c @@ -0,0 +1,12 @@ +#ifndef MAP_DIRECTORY_TOOLCHAIN_PREFIX_REPLAYED +#error "the configured GCC toolchain prefix was not replayed" +#endif + +#ifndef MAP_DIRECTORY_GCC_RECIPE_REPLAYED +#error "the GCC-selected mapped action must replay its emitted Kbuild flags" +#endif + +int map_directory_gcc_selected(void) +{ + return 15; +} diff --git a/tests/map_directory/required_local_header.h b/tests/map_directory/required_local_header.h new file mode 100644 index 00000000..a792fb19 --- /dev/null +++ b/tests/map_directory/required_local_header.h @@ -0,0 +1,6 @@ +#ifndef MAP_DIRECTORY_REQUIRED_LOCAL_HEADER_H +#define MAP_DIRECTORY_REQUIRED_LOCAL_HEADER_H + +#define MAP_DIRECTORY_REQUIRED_HEADER_VALUE 42 + +#endif diff --git a/tests/map_directory/supported.c b/tests/map_directory/supported.c index 9a2e5e70..2dd5fa79 100644 --- a/tests/map_directory/supported.c +++ b/tests/map_directory/supported.c @@ -1,4 +1,10 @@ +#include "required_local_header.h" + +#ifndef MAP_DIRECTORY_RECIPE_REPLAYED +#error "the mapped action must replay flags from the emitted Kbuild recipe" +#endif + int map_directory_selected(void) { - return 42; + return MAP_DIRECTORY_REQUIRED_HEADER_VALUE; } diff --git a/tests/map_directory/upstream_validator.go b/tests/map_directory/upstream_validator.go new file mode 100644 index 00000000..86f8232e --- /dev/null +++ b/tests/map_directory/upstream_validator.go @@ -0,0 +1,150 @@ +package main + +import ( + "bufio" + "flag" + "fmt" + "os" + "sort" + "strings" +) + +func main() { + configPath := flag.String("config", "", "resolved upstream Linux .config") + outPath := flag.String("out", "", "validation stamp") + flag.Parse() + if *configPath == "" || *outPath == "" || flag.NArg() != 0 { + fmt.Fprintln(os.Stderr, "usage: upstream_validator -config FILE -out FILE") + os.Exit(2) + } + + values, err := readConfig(*configPath) + if err != nil { + fmt.Fprintf(os.Stderr, "read resolved upstream config: %v\n", err) + os.Exit(1) + } + for _, key := range []string{ + "CONFIG_AS_IS_LLVM", + "CONFIG_CC_CAN_LINK", + "CONFIG_CC_IS_CLANG", + "CONFIG_LD_IS_LLD", + } { + if values[key] == "" { + values[key] = "n" + } + } + want := map[string]string{ + "CONFIG_64BIT": "y", + "CONFIG_AS_HAS_NON_CONST_ULEB128": "y", + "CONFIG_AS_IS_GNU": "y", + "CONFIG_AS_IS_LLVM": "n", + "CONFIG_AS_VERSION": "24600", + "CONFIG_AS_WRUSS": "y", + "CONFIG_CC_HAS_ASM_GOTO_OUTPUT": "y", + "CONFIG_CC_HAS_ASM_GOTO_TIED_OUTPUT": "y", + "CONFIG_CC_HAS_ASM_INLINE": "y", + "CONFIG_CC_HAS_ASSUME": "y", + "CONFIG_CC_HAS_AUTO_VAR_INIT_PATTERN": "y", + "CONFIG_CC_HAS_AUTO_VAR_INIT_ZERO": "y", + "CONFIG_CC_HAS_AUTO_VAR_INIT_ZERO_BARE": "y", + "CONFIG_CC_HAS_COUNTED_BY": "y", + "CONFIG_CC_HAS_ENTRY_PADDING": "y", + "CONFIG_CC_HAS_INT128": "y", + "CONFIG_CC_HAS_KASAN_GENERIC": "y", + "CONFIG_CC_HAS_KASAN_SW_TAGS": "y", + "CONFIG_CC_HAS_MARCH_NATIVE": "y", + "CONFIG_CC_HAS_MIN_FUNCTION_ALIGNMENT": "y", + "CONFIG_CC_HAS_MULTIDIMENSIONAL_NONSTRING": "y", + "CONFIG_CC_HAS_NAMED_AS": "y", + "CONFIG_CC_HAS_NAMED_AS_FIXED_SANITIZERS": "y", + "CONFIG_CC_HAS_NO_PROFILE_FN_ATTR": "y", + "CONFIG_CC_HAS_RETURN_THUNK": "y", + "CONFIG_CC_HAS_SANE_FUNCTION_ALIGNMENT": "y", + "CONFIG_CC_HAS_WORKING_NOSANITIZE_ADDRESS": "y", + "CONFIG_CC_HAS_ZERO_CALL_USED_REGS": "y", + "CONFIG_CC_IMPLICIT_FALLTHROUGH": "-Wimplicit-fallthrough=5", + "CONFIG_CC_NO_ARRAY_BOUNDS": "y", + "CONFIG_CC_NO_STRINGOP_OVERFLOW": "y", + // Keep the feasibility test executor-independent until gcc_toolchain's + // sysroot can be materialized without absolute symlinks in Bazel sandboxes. + "CONFIG_CC_CAN_LINK": "n", + "CONFIG_CC_IS_CLANG": "n", + "CONFIG_CC_IS_GCC": "y", + "CONFIG_CLANG_VERSION": "0", + "CONFIG_GCC_NO_STRINGOP_OVERFLOW": "y", + "CONFIG_GCC_VERSION": "150200", + // gcc_toolchain does not expose its plugin header as a declared target; + // sandboxed probing must therefore reject that ambient capability. + "CONFIG_GCC_PLUGINS": "n", + "CONFIG_LD_CAN_USE_KEEP_IN_OVERLAY": "y", + "CONFIG_LD_IS_BFD": "y", + "CONFIG_LD_IS_LLD": "n", + "CONFIG_LD_VERSION": "24600", + "CONFIG_LLD_VERSION": "0", + "CONFIG_TOOLS_SUPPORT_RELR": "y", + "CONFIG_X86": "y", + "CONFIG_X86_64": "y", + } + if values["CONFIG_CC_HAS_IBT"] != "y" && values["CONFIG_CC_HAS_IBT"] != "n" { + fmt.Fprintf(os.Stderr, "CONFIG_CC_HAS_IBT=%q, want a resolved compiler capability\n", values["CONFIG_CC_HAS_IBT"]) + os.Exit(1) + } + if values["CONFIG_CC_HAS_SLS"] != "y" && values["CONFIG_CC_HAS_SLS"] != "n" { + fmt.Fprintf(os.Stderr, "CONFIG_CC_HAS_SLS=%q, want a resolved compiler capability\n", values["CONFIG_CC_HAS_SLS"]) + os.Exit(1) + } + var mismatches []string + for key, expected := range want { + actual := values[key] + // The resolver omits disabled hidden symbols from .config. Kconfig's + // effective value for those absent bools is still n. + if actual == "" && expected == "n" { + actual = "n" + } + if actual != expected { + mismatches = append(mismatches, fmt.Sprintf("%s=%q, want %q", key, actual, expected)) + } + } + if got := values["CONFIG_CC_VERSION_TEXT"]; !strings.Contains(got, "15.2.0") || !strings.Contains(strings.ToLower(got), "gcc") { + mismatches = append(mismatches, fmt.Sprintf("CONFIG_CC_VERSION_TEXT=%q, want GCC 15.2.0 identity", got)) + } + if len(mismatches) != 0 { + sort.Strings(mismatches) + fmt.Fprintln(os.Stderr, strings.Join(mismatches, "\n")) + os.Exit(1) + } + if err := os.WriteFile(*outPath, []byte("upstream Linux 6.18.39 Kconfig resolved with GCC 15.2.0\n"), 0o644); err != nil { + fmt.Fprintf(os.Stderr, "write validation stamp: %v\n", err) + os.Exit(1) + } +} + +func readConfig(path string) (map[string]string, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + + values := map[string]string{} + scanner := bufio.NewScanner(file) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if strings.HasPrefix(line, "# CONFIG_") && strings.HasSuffix(line, " is not set") { + key := strings.TrimSuffix(strings.TrimPrefix(line, "# "), " is not set") + values[key] = "n" + continue + } + if !strings.HasPrefix(line, "CONFIG_") { + continue + } + key, value, ok := strings.Cut(line, "=") + if ok { + values[key] = strings.Trim(value, `"`) + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return values, nil +} diff --git a/tests/map_directory/validator.go b/tests/map_directory/validator.go index 36cf1c7c..1b884896 100644 --- a/tests/map_directory/validator.go +++ b/tests/map_directory/validator.go @@ -2,6 +2,7 @@ package main import ( "debug/elf" + "encoding/json" "flag" "fmt" "os" @@ -9,6 +10,8 @@ import ( "regexp" "sort" "strings" + + "github.com/hermeticbuild/linux.bzl/internal/kconfig" ) var probeMarkerPattern = regexp.MustCompile(`^v1/probe/sha256-[0-9a-f]{64}$`) @@ -36,10 +39,22 @@ func treeFiles(root string) ([]string, error) { return files, nil } -func validatePlan(root string) error { +type compileRecipe struct { + ContentID string `json:"content_id"` + Object string `json:"object"` + Source string `json:"source"` + Flags []string `json:"flags"` +} + +type planValidation struct { + identity string + family string +} + +func validatePlan(root string) (planValidation, error) { files, err := treeFiles(root) if err != nil { - return fmt.Errorf("walk action plan: %w", err) + return planValidation{}, fmt.Errorf("walk action plan: %w", err) } var probes, sources, compiles []string for _, path := range files { @@ -51,20 +66,40 @@ func validatePlan(root string) error { case strings.HasPrefix(path, "v1/compile/"): compiles = append(compiles, path) default: - return fmt.Errorf("unexpected action-plan marker %q", path) + return planValidation{}, fmt.Errorf("unexpected action-plan marker %q", path) } } if len(probes) != 1 || !probeMarkerPattern.MatchString(probes[0]) { - return fmt.Errorf("measured compiler probe markers = %q, want one sha256 marker", probes) + return planValidation{}, fmt.Errorf("measured compiler probe markers = %q, want one sha256 marker", probes) + } + family := "" + for _, path := range compiles { + switch { + case strings.HasSuffix(path, "/clang_selected.o.json"): + if family != "" { + return planValidation{}, fmt.Errorf("compile markers select more than one compiler family: %q", compiles) + } + family = "clang" + case strings.HasSuffix(path, "/gcc_selected.o.json"): + if family != "" { + return planValidation{}, fmt.Errorf("compile markers select more than one compiler family: %q", compiles) + } + family = "gcc" + } + } + if family == "" { + return planValidation{}, fmt.Errorf("compile markers select no compiler family: %q", compiles) } wantSources := []string{ + family + "_selected.c", "include/linux/compiler-version.h", "include/linux/compiler_types.h", "include/linux/kconfig.h", + "required_local_header.h", "supported.c", } if len(sources) != len(wantSources) { - return fmt.Errorf("selected source markers = %q, want %q", sources, wantSources) + return planValidation{}, fmt.Errorf("selected source markers = %q, want %q", sources, wantSources) } for _, want := range wantSources { found := false @@ -75,67 +110,204 @@ func validatePlan(root string) error { } } if !found { - return fmt.Errorf("selected source markers = %q, missing %q", sources, want) + return planValidation{}, fmt.Errorf("selected source markers = %q, missing %q", sources, want) } } - if len(compiles) != 1 || !strings.HasSuffix(compiles[0], "/supported.o.json") { - return fmt.Errorf("compile markers = %q, want only supported.o.json", compiles) + wantObjects := map[string][]string{ + "supported.o": { + "-fno-omit-frame-pointer", + "-DMAP_DIRECTORY_RECIPE_REPLAYED=1", + }, + family + "_selected.o": { + "-DMAP_DIRECTORY_" + strings.ToUpper(family) + "_RECIPE_REPLAYED=1", + }, + } + if len(compiles) != len(wantObjects) { + return planValidation{}, fmt.Errorf("compile markers = %q, want objects %v", compiles, sortedKeys(wantObjects)) + } + seenObjects := map[string]bool{} + for _, compile := range compiles { + data, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(compile))) + if err != nil { + return planValidation{}, fmt.Errorf("read compile recipe: %w", err) + } + var recipe compileRecipe + if err := json.Unmarshal(data, &recipe); err != nil { + return planValidation{}, fmt.Errorf("decode compile recipe: %w", err) + } + parts := strings.Split(compile, "/") + wantFlags, wanted := wantObjects[recipe.Object] + if len(parts) < 5 || recipe.ContentID != parts[2] || !strings.HasSuffix(compile, "/"+recipe.Object+".json") || recipe.Source != strings.TrimSuffix(recipe.Object, ".o")+".c" || !wanted { + return planValidation{}, fmt.Errorf("compile recipe does not match its marker path or selected family: path=%q recipe=%#v", compile, recipe) + } + if seenObjects[recipe.Object] { + return planValidation{}, fmt.Errorf("compile plan repeats recipe for %q", recipe.Object) + } + seenObjects[recipe.Object] = true + for _, want := range wantFlags { + found := false + for _, flag := range recipe.Flags { + if flag == want { + found = true + break + } + } + if !found { + return planValidation{}, fmt.Errorf("compile recipe %q flags = %q, missing replayed Kbuild flag %q", recipe.Object, recipe.Flags, want) + } + } } for _, path := range files { - if strings.Contains(path, "unsupported") { - return fmt.Errorf("unsupported compiler branch appeared in action plan as %q", path) + if strings.Contains(path, "unsupported") || strings.Contains(path, map[string]string{"clang": "gcc_selected", "gcc": "clang_selected"}[family]) { + return planValidation{}, fmt.Errorf("unselected compiler branch appeared in action plan as %q", path) } } + return planValidation{ + identity: strings.TrimPrefix(probes[0], "v1/probe/"), + family: family, + }, nil +} + +func sortedKeys[V any](values map[string]V) []string { + keys := make([]string, 0, len(values)) + for key := range values { + keys = append(keys, key) + } + sort.Strings(keys) + return keys +} + +type repeatedFlag []string + +func (f *repeatedFlag) String() string { return strings.Join(*f, " ") } +func (f *repeatedFlag) Set(value string) error { + *f = append(*f, value) return nil } -func validateObject(root string) error { +func validateObjects(root, family string) error { files, err := treeFiles(root) if err != nil { return fmt.Errorf("walk mapped objects: %w", err) } - if len(files) != 1 || !strings.HasSuffix(files[0], "/supported.o") { - return fmt.Errorf("mapped objects = %q, want exactly supported.o", files) - } - objectPath := filepath.Join(root, filepath.FromSlash(files[0])) - object, err := elf.Open(objectPath) - if err != nil { - return fmt.Errorf("open mapped object %q: %w", files[0], err) - } - defer object.Close() - if object.Type != elf.ET_REL { - return fmt.Errorf("mapped object type = %s, want ET_REL", object.Type) + wantSymbols := map[string]string{ + "supported.o": "map_directory_selected", + family + "_selected.o": "map_directory_" + family + "_selected", } - if object.Machine != elf.EM_X86_64 { - return fmt.Errorf("mapped object machine = %s, want EM_X86_64", object.Machine) - } - symbols, err := object.Symbols() - if err != nil { - return fmt.Errorf("read mapped object symbols: %w", err) + if len(files) != len(wantSymbols) { + return fmt.Errorf("mapped objects = %q, want %v", files, sortedKeys(wantSymbols)) } - for _, symbol := range symbols { - if symbol.Name == "map_directory_selected" { - return nil + seen := map[string]bool{} + for _, path := range files { + base := filepath.Base(path) + wantSymbol, wanted := wantSymbols[base] + if !wanted || seen[base] { + return fmt.Errorf("unexpected or duplicate mapped object %q", path) + } + seen[base] = true + object, err := elf.Open(filepath.Join(root, filepath.FromSlash(path))) + if err != nil { + return fmt.Errorf("open mapped object %q: %w", path, err) + } + if object.Type != elf.ET_REL || object.Machine != elf.EM_X86_64 { + object.Close() + return fmt.Errorf("mapped object %q has type %s machine %s, want ET_REL x86_64", path, object.Type, object.Machine) + } + symbols, err := object.Symbols() + object.Close() + if err != nil { + return fmt.Errorf("read mapped object %q symbols: %w", path, err) + } + found := false + for _, symbol := range symbols { + if symbol.Name == wantSymbol { + found = true + break + } + } + if !found { + return fmt.Errorf("mapped object %q does not define %s", path, wantSymbol) } } - return fmt.Errorf("mapped object does not define map_directory_selected") + return nil } func run() error { + var compilerArgs repeatedFlag + var linkerDriverArgs repeatedFlag plan := flag.String("plan", "", "action-plan tree") objects := flag.String("objects", "", "mapped object tree") + otherPlan := flag.String("other_plan", "", "second action-plan tree whose probe identity must differ") out := flag.String("out", "", "validation stamp") + compiler := flag.String("compiler", "", "selected compiler artifact") + linker := flag.String("linker", "", "selected linker artifact") + archiver := flag.String("archiver", "", "selected archiver artifact") + nm := flag.String("nm", "", "selected nm artifact") + objcopy := flag.String("objcopy", "", "selected objcopy artifact") + targetProfile := flag.String("target_profile", "", "selected Linux target profile") + linuxArch := flag.String("linux_arch", "", "selected Linux ARCH") + targetTriple := flag.String("target_triple", "", "selected compiler target triple") + flag.Var(&compilerArgs, "compiler_arg", "configured compiler prefix argument") + flag.Var(&linkerDriverArgs, "linker_driver_arg", "configured linker-driver prefix argument") flag.Parse() - if *plan == "" || *objects == "" || *out == "" { - return fmt.Errorf("-plan, -objects, and -out are required") + if *otherPlan != "" { + if *plan == "" || *out == "" { + return fmt.Errorf("-plan, -other_plan, and -out are required for identity comparison") + } + first, err := validatePlan(*plan) + if err != nil { + return fmt.Errorf("first plan: %w", err) + } + second, err := validatePlan(*otherPlan) + if err != nil { + return fmt.Errorf("second plan: %w", err) + } + if first.identity == second.identity { + return fmt.Errorf("compiler-selected plans share probe identity %q", first.identity) + } + if first.family == second.family { + return fmt.Errorf("compiler-selected plans both selected %s recipes", first.family) + } + contents := fmt.Sprintf("map_directory compiler plans differ: %s/%s != %s/%s\n", first.family, first.identity, second.family, second.identity) + if err := os.WriteFile(*out, []byte(contents), 0o644); err != nil { + return fmt.Errorf("write identity comparison stamp: %w", err) + } + return nil } - if err := validatePlan(*plan); err != nil { + if *plan == "" || *objects == "" || *out == "" || *compiler == "" || *linker == "" || *archiver == "" || *nm == "" || *objcopy == "" || *targetProfile == "" || *linuxArch == "" || *targetTriple == "" { + return fmt.Errorf("-plan, -objects, -out, -compiler, -linker, -archiver, -nm, -objcopy, -target_profile, -linux_arch, and -target_triple are required") + } + planResult, err := validatePlan(*plan) + if err != nil { + return err + } + probe, err := kconfig.NewLinuxToolProbe(kconfig.LinuxToolProbeOptions{ + Profile: *targetProfile, + Architecture: *linuxArch, + TargetTriple: *targetTriple, + CompilerPath: *compiler, + LinkerPath: *linker, + ArchiverPath: *archiver, + NMPath: *nm, + ObjcopyPath: *objcopy, + CompilerArgs: compilerArgs, + LinkerDriverArgs: linkerDriverArgs, + }) + if err != nil { return err } - if err := validateObject(*objects); err != nil { + selectedIdentity := probe.Identity() + if planResult.identity != selectedIdentity { + return fmt.Errorf("plan probe identity = %q, selected tool identity = %q", planResult.identity, selectedIdentity) + } + selectedFamily := probe.CompilerFamily() + if planResult.family != selectedFamily { + return fmt.Errorf("plan selected %s recipes for the measured %s compiler", planResult.family, selectedFamily) + } + if err := validateObjects(*objects, selectedFamily); err != nil { return err } - if err := os.WriteFile(*out, []byte("map_directory compiler capability spike passed\n"), 0o644); err != nil { + if err := os.WriteFile(*out, []byte(fmt.Sprintf("map_directory %s compiler capability spike passed: %s\n", selectedFamily, planResult.identity)), 0o644); err != nil { return fmt.Errorf("write validation stamp: %w", err) } return nil From e888b0aa7a4050c5b16d839fdac675e00c76750f Mon Sep 17 00:00:00 2001 From: fionera Date: Wed, 12 Aug 2026 15:32:42 +0000 Subject: [PATCH 04/46] tests: run map_directory compiler matrix from e2e --- .github/workflows/ci.yml | 79 +++++++- MODULE.bazel | 26 --- MODULE.bazel.lock | 47 +---- e2e/.bazelrc | 5 + e2e/MODULE.bazel | 15 ++ e2e/MODULE.bazel.lock | 47 ++++- e2e/map_directory/BUILD.bazel | 110 +++++++++++ {tests => e2e}/map_directory/Kbuild | 0 {tests => e2e}/map_directory/Kconfig | 0 {tests => e2e}/map_directory/base.config | 0 {tests => e2e}/map_directory/clang_selected.c | 0 {tests => e2e}/map_directory/gcc_selected.c | 0 .../include/linux/compiler-version.h | 0 .../include/linux/compiler_types.h | 0 .../map_directory/include/linux/kconfig.h | 0 .../map_directory/required_local_header.h | 0 {tests => e2e}/map_directory/supported.c | 0 {tests => e2e}/map_directory/unsupported.c | 0 e2e/map_directory/upstream_validator.go | 186 ++++++++++++++++++ .../cmd/mapdirectoryvalidator/BUILD.bazel | 17 ++ .../cmd/mapdirectoryvalidator/main.go | 0 internal/kconfig/BUILD.bazel | 1 - internal/map_directory_kconfig.bzl | 164 ++++++--------- tests/map_directory/BUILD.bazel | 173 ---------------- tests/map_directory/upstream_validator.go | 150 -------------- 25 files changed, 507 insertions(+), 513 deletions(-) create mode 100644 e2e/map_directory/BUILD.bazel rename {tests => e2e}/map_directory/Kbuild (100%) rename {tests => e2e}/map_directory/Kconfig (100%) rename {tests => e2e}/map_directory/base.config (100%) rename {tests => e2e}/map_directory/clang_selected.c (100%) rename {tests => e2e}/map_directory/gcc_selected.c (100%) rename {tests => e2e}/map_directory/include/linux/compiler-version.h (100%) rename {tests => e2e}/map_directory/include/linux/compiler_types.h (100%) rename {tests => e2e}/map_directory/include/linux/kconfig.h (100%) rename {tests => e2e}/map_directory/required_local_header.h (100%) rename {tests => e2e}/map_directory/supported.c (100%) rename {tests => e2e}/map_directory/unsupported.c (100%) create mode 100644 e2e/map_directory/upstream_validator.go create mode 100644 internal/cmd/mapdirectoryvalidator/BUILD.bazel rename tests/map_directory/validator.go => internal/cmd/mapdirectoryvalidator/main.go (100%) delete mode 100644 tests/map_directory/BUILD.bazel delete mode 100644 tests/map_directory/upstream_validator.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 177f9076..982f9e96 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,13 +52,7 @@ jobs: targets=(//...) path_mapping_args=() if [[ -n "${BAZEL_PATH_MAPPING}" ]]; then - targets+=( - //internal/tests:path_mapping_test - //tests/map_directory:compiler_capabilities_e2e_test - //tests/map_directory:distinct_compiler_plan_identities_e2e_test - //tests/map_directory:gcc_compiler_capabilities_e2e_test - //tests/map_directory:upstream_gcc_kconfig_e2e_test - ) + targets+=(//internal/tests:path_mapping_test) path_mapping_args+=("${BAZEL_PATH_MAPPING}") fi bazel --host_jvm_args=-Xmx6g \ @@ -94,6 +88,77 @@ jobs: if-no-files-found: warn retention-days: 14 + map-directory-e2e: + name: map_directory Kconfig (${{ matrix.compiler }}) + runs-on: ubuntu-latest + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + compiler: + - clang + - gcc + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Configure Bazel + uses: bazel-contrib/setup-bazel@0.19.0 + with: + bazelisk-cache: true + disk-cache: ${{ github.workflow }}-map-directory-${{ matrix.compiler }} + module-root: e2e + repository-cache: | + - e2e/.bazelversion + - e2e/MODULE.bazel + - e2e/MODULE.bazel.lock + cache-save: ${{ github.event_name != 'pull_request' }} + + - name: Test with ${{ matrix.compiler }} + working-directory: e2e + env: + BAZEL_BEP: ${{ runner.temp }}/map-directory-${{ matrix.compiler }}.bep.json + BAZEL_LOG: ${{ runner.temp }}/map-directory-${{ matrix.compiler }}.log + BAZEL_PROFILE: ${{ runner.temp }}/map-directory-${{ matrix.compiler }}.profile.gz + run: | + set -euo pipefail + bazel --host_jvm_args=-Xmx6g \ + --bazelrc="${GITHUB_WORKSPACE}/.github/workflows/ci.bazelrc" \ + test //map_directory:compiler_kconfig_e2e_tests \ + --config=path-mapping \ + --config="map-directory-${{ matrix.compiler }}" \ + --notrack_incremental_state \ + --nokeep_state_after_build \ + --discard_analysis_cache \ + --build_event_json_file="${BAZEL_BEP}" \ + --profile="${BAZEL_PROFILE}" \ + 2>&1 | tee "${BAZEL_LOG}" + + - name: Report cache efficiency + if: ${{ !cancelled() }} + env: + BAZEL_BEP: ${{ runner.temp }}/map-directory-${{ matrix.compiler }}.bep.json + BAZEL_LOG: ${{ runner.temp }}/map-directory-${{ matrix.compiler }}.log + BAZEL_PROFILE: ${{ runner.temp }}/map-directory-${{ matrix.compiler }}.profile.gz + run: | + .github/workflows/bazel_cache_report.sh \ + "map_directory Kconfig (${{ matrix.compiler }})" \ + "${BAZEL_PROFILE}" \ + "${BAZEL_BEP}" \ + "${BAZEL_LOG}" + + - name: Upload Bazel profile + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v7 + with: + name: bazel-profile-map-directory-${{ matrix.compiler }} + path: | + ${{ runner.temp }}/map-directory-${{ matrix.compiler }}.profile.gz + ${{ runner.temp }}/map-directory-${{ matrix.compiler }}.bep.json + ${{ runner.temp }}/map-directory-${{ matrix.compiler }}.log + if-no-files-found: warn + retention-days: 14 + examples: name: Standalone examples (${{ matrix.title }}) runs-on: ubuntu-latest diff --git a/MODULE.bazel b/MODULE.bazel index 57d092ff..7d70a301 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -6,7 +6,6 @@ bazel_dep(name = "bazel_lib", version = "3.2.2") bazel_dep(name = "bazel_skylib", version = "1.9.0") bazel_dep(name = "buildifier_prebuilt", version = "8.2.1.1", dev_dependency = True) -bazel_dep(name = "gcc_toolchain", version = "0.12.0", dev_dependency = True) bazel_dep(name = "llvm", version = "0.8.14") bazel_dep(name = "elfutils", version = "0.195") @@ -48,35 +47,10 @@ use_repo(bindgen_toolchains, "rules_rust_bindgen") tar_toolchains = use_extension("@tar.bzl//tar:extensions.bzl", "toolchains", dev_dependency = True) use_repo(tar_toolchains, "bsd_tar_toolchains") -map_directory_gcc_toolchains = use_extension( - "@gcc_toolchain//toolchain:module_extensions.bzl", - "gcc_toolchains", - dev_dependency = True, -) -map_directory_gcc_toolchains.toolchain( - name = "map_directory_gcc_x86_64", - enable_fortran = False, - gcc_version = "15.2.0", - target_arch = "x86_64", -) -use_repo(map_directory_gcc_toolchains, "map_directory_gcc_x86_64") - -map_directory_linux_source_repository = use_repo_rule( - "//:linux.bzl", - "linux_source_repository", -) - -map_directory_linux_source_repository( - name = "map_directory_linux_6_18_39", - dev_dependency = True, - version = "6.18.39", -) - register_toolchains( "@default_rust_toolchains//:all", "@rules_rust_bindgen//:all", "@bsd_tar_toolchains//:all", - "//tests/map_directory:gcc_cc_toolchain", "@llvm//toolchain:all", dev_dependency = True, ) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 590104a6..bf635a4a 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -50,8 +50,7 @@ "https://bcr.bazel.build/modules/bazel_features/1.9.1/MODULE.bazel": "8f679097876a9b609ad1f60249c49d68bfab783dd9be012faf9d82547b14815a", "https://bcr.bazel.build/modules/bazel_lib/3.0.0/MODULE.bazel": "22b70b80ac89ad3f3772526cd9feee2fa412c2b01933fea7ed13238a448d370d", "https://bcr.bazel.build/modules/bazel_lib/3.2.2/MODULE.bazel": "e2c890c8a515d6bca9c66d47718aa9e44b458fde64ec7204b8030bf2d349058c", - "https://bcr.bazel.build/modules/bazel_lib/3.3.1/MODULE.bazel": "732a0d516cf6400d9b3136e4356258aef1bf91de8d5240f87f0112f098920c1d", - "https://bcr.bazel.build/modules/bazel_lib/3.3.1/source.json": "8e5175d7b4125a39b8941d01e38039934d058e03804f46a2b8fd7ae6316b1ce2", + "https://bcr.bazel.build/modules/bazel_lib/3.2.2/source.json": "9e84e115c20e14652c5c21401ae85ff4daa8702e265b5c0b3bf89353f17aa212", "https://bcr.bazel.build/modules/bazel_skylib/1.0.3/MODULE.bazel": "bcb0fd896384802d1ad283b4e4eb4d718eebd8cb820b0a2c3a347fb971afd9d8", "https://bcr.bazel.build/modules/bazel_skylib/1.1.1/MODULE.bazel": "1add3e7d93ff2e6998f9e118022c84d163917d912f5afafb3058e3d2f1545b5e", "https://bcr.bazel.build/modules/bazel_skylib/1.2.0/MODULE.bazel": "44fe84260e454ed94ad326352a698422dbe372b21a1ac9f3eab76eb531223686", @@ -84,8 +83,6 @@ "https://bcr.bazel.build/modules/gazelle/0.36.0/MODULE.bazel": "e375d5d6e9a6ca59b0cb38b0540bc9a05b6aa926d322f2de268ad267a2ee74c0", "https://bcr.bazel.build/modules/gazelle/0.51.3/MODULE.bazel": "618a729142f66de1e2cb776d026413763be5b80d5e3d29ffb9d3d90c5defde90", "https://bcr.bazel.build/modules/gazelle/0.51.3/source.json": "fbe5312a01fb4a2a58caff4a0d40dcf384b6f0bda75e85546663360da1d7538a", - "https://bcr.bazel.build/modules/gcc_toolchain/0.12.0/MODULE.bazel": "0f575f5136b738c6a47ed5198b365bf274fedf9283ea3377189d4ab62a118959", - "https://bcr.bazel.build/modules/gcc_toolchain/0.12.0/source.json": "40f4663ce767e406c57c6de91dd0ffb8a87c12337a8fdc684c664f88e03821a2", "https://bcr.bazel.build/modules/google_benchmark/1.8.2/MODULE.bazel": "a70cf1bba851000ba93b58ae2f6d76490a9feb74192e57ab8e8ff13c34ec50cb", "https://bcr.bazel.build/modules/googletest/1.11.0/MODULE.bazel": "3a83f095183f66345ca86aa13c58b59f9f94a2f81999c093d4eeaa2d262d12f4", "https://bcr.bazel.build/modules/googletest/1.14.0.bcr.1/MODULE.bazel": "22c31a561553727960057361aa33bf20fb2e98584bc4fec007906e27053f80c6", @@ -275,48 +272,6 @@ }, "selectedYankedVersions": {}, "moduleExtensions": { - "@@gcc_toolchain+//:internal.bzl%non_bazel_dependencies": { - "general": { - "bzlTransitiveDigest": "q7o2f2hyvgWoZzlcLHt6NQcltO37YFhGTefWaSqCJiM=", - "usagesDigest": "13mSQ09nHZ81WiU4i3SNGXBI5svRCTTyl8M9oydMMbI=", - "recordedInputs": [ - "REPO_MAPPING:gcc_toolchain+,bazel_tools bazel_tools", - "REPO_MAPPING:gcc_toolchain+,lapack gcc_toolchain++non_bazel_dependencies+lapack" - ], - "generatedRepoSpecs": { - "openssl": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "build_file_content": "filegroup(\n name = \"srcs\",\n srcs = glob(\n include = [\"**\"],\n exclude = [\"**/* *\"],\n ),\n visibility = [\"//visibility:public\"],\n)\n", - "sha256": "40dceb51a4f6a5275bde0e6bf20ef4b91bfc32ed57c0552e2e8e15463372b17a", - "strip_prefix": "openssl-1.1.1n", - "url": "https://www.openssl.org/source/openssl-1.1.1n.tar.gz" - } - }, - "lapack": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "build_file_content": "filegroup(\n name = \"srcs\",\n srcs = glob(\n include = [\"**\"],\n exclude = [\"**/* *\"],\n ),\n visibility = [\"//visibility:public\"],\n)\n", - "patch_cmds": [ - "cat > make.inc < make.inc <