Source file src/cmd/go/internal/test/analysis.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package test
     6  
     7  // Analysis in go test, which replaces go test's use of cmd/vet when
     8  // enabled by GOEXPERIMENT=vetfiles (see cfg.Experiment.VetFiles).
     9  
    10  import (
    11  	"context"
    12  	"maps"
    13  	"os"
    14  	"path/filepath"
    15  	"slices"
    16  	"strings"
    17  	"sync"
    18  
    19  	"cmd/go/internal/base"
    20  	"cmd/go/internal/cfg"
    21  	"cmd/go/internal/load"
    22  	"cmd/go/internal/modload"
    23  	"cmd/go/internal/work"
    24  )
    25  
    26  // positiveRefs holds the references that enable analyzers for some
    27  // root package.
    28  var positiveRefs = make(map[*load.AnalysisRef]bool)
    29  
    30  // vetAnalysisConfig returns go test's analysis configuration for
    31  // package p, from the -vet flag: the selected members of the vet
    32  // suite, or all of them for -vet=all.
    33  //
    34  // As with cmd/vet, packages in GOROOT are by default checked with
    35  // nearly all analyzers (see gorootAnalysisConfig).
    36  func vetAnalysisConfig(p *load.Package) *load.AnalysisConfig {
    37  	if p.Goroot && !testVet.explicit {
    38  		return gorootAnalysisConfig()
    39  	}
    40  	return userAnalysisConfig()
    41  }
    42  
    43  var userAnalysisConfig = sync.OnceValue(func() *load.AnalysisConfig {
    44  	if testVet.explicit && testVet.flags == nil {
    45  		return load.VetAnalysisConfig(nil) // -vet=all
    46  	}
    47  	var names []string
    48  	for _, flag := range testVet.flags {
    49  		names = append(names, strings.TrimPrefix(flag, "-"))
    50  	}
    51  	return load.VetAnalysisConfig(names)
    52  })
    53  
    54  // gorootAnalysisConfig is the default configuration for packages in
    55  // GOROOT: all vet analyzers except unsafeptr (there is too much
    56  // unsafe.Pointer code that it does not like in low-level packages)
    57  // and unreachable (during testing it is common to make changes, such
    58  // as forced returns, that make code unreachable). See also
    59  // work.vetFlags.
    60  var gorootAnalysisConfig = sync.OnceValue(func() *load.AnalysisConfig {
    61  	config := load.VetAnalysisConfig(nil)
    62  	// TODO(adonovan): this list is temporary; it will soon move
    63  	// into a go.vet file in GOROOT/src.
    64  	for _, name := range []string{"unsafeptr", "unreachable"} {
    65  		config.Negative = append(config.Negative, &load.AnalysisRef{Negative: true, Name: name})
    66  	}
    67  	return config
    68  })
    69  
    70  // addTestAnalysis adds an action to report the analyzers enabled for
    71  // root package p by go test's analysis configuration.
    72  //
    73  // As with cmd/vet before it, the test's run action depends on
    74  // the report, so the test does not run if the analysis fails. The
    75  // install action, if any, also depends on it.
    76  func addTestAnalysis(ld *modload.Loader, b *work.Builder, p *load.Package, runAction, installAction *work.Action) {
    77  	if testVet.off || testC {
    78  		// -vet=off, or go test -c, which is a build, not a test.
    79  		// Building code must not execute it (go.dev/blog/supply-chain),
    80  		// and the analyzers declared by configuration files, as
    81  		// proposed in go.dev/issue/82464, may come from any module,
    82  		// so -c runs no analysis: for consistency, not even go test's
    83  		// vet checks. (This differs from cmd/vet, which -c ran.)
    84  		return
    85  	}
    86  	config := vetAnalysisConfig(p)
    87  	for _, a := range config.Positive {
    88  		positiveRefs[a] = true
    89  	}
    90  	a := b.AnalysisVetAction(ld, p, config)
    91  	// Install will clean the build directory; make sure analysis runs first.
    92  	if installAction != nil {
    93  		installAction.Deps = append(installAction.Deps, a)
    94  	}
    95  	runAction.Deps = append(runAction.Deps, a)
    96  }
    97  
    98  // buildAnalysisTool arranges to build the analysis tool containing
    99  // the variables referenced by the configurations of the root
   100  // packages, and to query its metadata.
   101  //
   102  // The tool is built in this process, in the tests' build
   103  // configuration (whatever their GOOS, GOARCH, build tags, -race,
   104  // -gcflags, and so on), sharing compiled packages with the tests, and
   105  // it runs on the host, as do the tests. (When the tests run under an
   106  // exec wrapper, go test uses cmd/vet instead; see analysisUsesCmdVet.)
   107  func buildAnalysisTool(ld *modload.Loader, ctx context.Context, b *work.Builder, opts load.PackageOpts) {
   108  	if !b.HasAnalysisActions() {
   109  		return
   110  	}
   111  	refs := slices.SortedFunc(maps.Keys(positiveRefs), load.CompareAnalysisRefs)
   112  	for _, err := range synthesizeAnalysisTool(ld, ctx, b, opts, refs) {
   113  		base.Errorf("go: %v", err)
   114  	}
   115  }
   116  
   117  // analysisUsesCmdVet reports whether go test uses cmd/vet in place of
   118  // the analysis tool because the tests run under an exec wrapper:
   119  // either the program named by the -exec flag, or the
   120  // go_$GOOS_$GOARCH_exec program that go test finds in $PATH when the
   121  // target platform is not the host's (see work.FindExecCmd).
   122  //
   123  // The analysis tool is built in the tests' configuration and runs on
   124  // the host. A wrapper indicates that the tests do not run directly on
   125  // the host but in an emulator, device, virtual machine, or other
   126  // sandbox, which may be a security boundary that running the tool on
   127  // the host would bypass; and the tool, built for the target, might
   128  // not run on the host anyway. So go test does not run the tool, and
   129  // instead uses cmd/vet, which is built for the host and runs only the
   130  // analyzers of the standard library. The analysis tool is never
   131  // cross-compiled for the host.
   132  var analysisUsesCmdVet = sync.OnceValue(func() bool {
   133  	return len(work.FindExecCmd()) > 0
   134  })
   135  
   136  // synthesizeAnalysisTool synthesizes the main package of the analysis
   137  // tool, containing the variables referenced by refs, and adds the
   138  // actions to build it and query its metadata to b. It returns errors
   139  // loading the packages of the references.
   140  func synthesizeAnalysisTool(ld *modload.Loader, ctx context.Context, b *work.Builder, opts load.PackageOpts, refs []*load.AnalysisRef) []error {
   141  	pmain, src, errs := load.AnalysisToolPackage(ld, ctx, opts, refs)
   142  	dir := b.CompileAction(work.ModeBuild, work.ModeBuild, pmain).Objdir
   143  	if err := b.BackgroundShell().Mkdir(dir); err != nil {
   144  		base.Fatal(err)
   145  	}
   146  	pmain.Dir = dir
   147  	if !cfg.BuildN {
   148  		if err := os.WriteFile(filepath.Join(dir, pmain.GoFiles[0]), src, 0666); err != nil {
   149  			base.Fatal(err)
   150  		}
   151  	}
   152  	link := b.LinkAction(ld, work.ModeBuild, work.ModeBuild, pmain)
   153  	link.Target = dir + "analysistool" + cfg.ExeSuffix
   154  	link.CacheExecutable = true
   155  	b.SetAnalysisTool(link)
   156  	return errs
   157  }
   158  

View as plain text