Source file src/cmd/go/internal/work/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 work
     6  
     7  // This file implements the build actions for analysis in go test
     8  // (see load/analysis.go).
     9  //
    10  // There is one analysis tool per go test invocation, containing all
    11  // variables (analyzers and suites) referenced by the configurations
    12  // that enable analyzers for any root package. (A root package is one
    13  // for which go test reports diagnostics, as opposed to a dependency,
    14  // which is analyzed only for the facts its importers need.) The
    15  // tool's driver package is the standard library's
    16  // internal/analysis/gotestchecker.
    17  //
    18  // The action graph is planned before the tool exists, so its topology
    19  // is conservative: one analysisvet action per package in the import
    20  // closure of the root packages, isomorphic to the import graph,
    21  // plus an analysismeta action that runs the tool's metadata query
    22  // (-describe) once the tool is linked, and one analysisreport action
    23  // per root package:
    24  //
    25  //	link(tool) --> analysismeta --> analysisvet(P) --> analysisreport(P) --> run(P.test)
    26  //	                                      ^
    27  //	                                      |
    28  //	                                analysisvet(Q), for each import Q of P
    29  //
    30  // Every analysisvet action depends on the analysismeta action, which
    31  // performs the dynamic stage of resolution: from the metadata (the
    32  // members of each suite, the Requires graph, and which analyzers use
    33  // facts) it expands suites, applies selectors and negations, and
    34  // computes, for each root package, the set of analyzers whose
    35  // diagnostics are reported, and for each analysisvet action, the set
    36  // of analyzers whose results it must produce. An analysisvet action whose set is
    37  // empty merely produces types.
    38  //
    39  // Within the tool, analyzers are identified by pointer; in the
    40  // protocol, they are identified by their index in the tool's
    41  // metadata, a topological order that is deterministic for a given
    42  // tool. Across tools, an analyzer is identified (for caching) by its
    43  // Name and Run function and the variables from which it is
    44  // reachable; see [Builder.analyzerIDs].
    45  //
    46  // Each analysisvet action produces, for each needed analyzer, one
    47  // pass file containing that analyzer's facts (if it uses facts) and,
    48  // for the analyzers reported for a root package, its diagnostics.
    49  // So the facts of an analyzer required by several roots are computed
    50  // and stored once per package. A pass file may instead record a
    51  // failure, which prevents dependent passes and is reported at each
    52  // affected root package.
    53  //
    54  // Analysis results are cached not per tool but per (package,
    55  // analyzer), so that results are shared across invocations even
    56  // though their tools differ:
    57  //
    58  //   - the types of package P are keyed by the inputs of P, including
    59  //     the types of its direct imports and the target configuration,
    60  //     and the dependency identity of the driver package;
    61  //   - the pass file of analyzer A on P is keyed by the inputs of P,
    62  //     the identity of A, whether A's diagnostics are reported,
    63  //     and the facts IDs of the pass files, for each direct import of P,
    64  //     of each analyzer that uses facts in A's Requires closure.
    65  //     (The facts ID of a pass file excludes its diagnostics, which
    66  //     depend on whether they are reported, so that the pass files of
    67  //     a package are shared by invocations that do and do not vet
    68  //     its dependencies.)
    69  //
    70  // The dependency identity of a package is a Merkle hash over its
    71  // import graph that covers the content IDs of the compiled packages
    72  // in its import closure. The identity of an analyzer is the hash of
    73  // its Name and Run function (by run-time symbol name), the dependency
    74  // identity of the driver package, and the dependency identities of
    75  // the packages that declare the linked variables from which the
    76  // analyzer is reachable. It does not depend on which other analyzers
    77  // are linked into the tool.
    78  // Analyzers linked into the same tool are assumed not to interfere
    79  // with one another.
    80  
    81  import (
    82  	"bytes"
    83  	"context"
    84  	"crypto/sha256"
    85  	"encoding/json"
    86  	"errors"
    87  	"fmt"
    88  	"internal/analysis/gotestchecker/protocol"
    89  	"maps"
    90  	"os"
    91  	"path/filepath"
    92  	"runtime"
    93  	"slices"
    94  	"strings"
    95  
    96  	"cmd/go/internal/cache"
    97  	"cmd/go/internal/cfg"
    98  	"cmd/go/internal/load"
    99  	"cmd/go/internal/modload"
   100  	"cmd/go/internal/str"
   101  )
   102  
   103  // analysisResult records the outputs of an analysisvet action.
   104  // It is the action's Provider.
   105  type analysisResult struct {
   106  	types    analysisOutput         // the package's types
   107  	typeErrs []string               // type errors of the package (reported once)
   108  	passes   map[int]analysisOutput // analyzer index -> pass file
   109  }
   110  
   111  // An analysisOutput is a file in the cache and its output ID, plus,
   112  // for a pass file, information read from it (see readPassInfo).
   113  type analysisOutput struct {
   114  	file    string
   115  	id      cache.OutputID
   116  	factsID cache.OutputID    // for pass files of analyzers that use facts
   117  	trivial bool              // pass file has no facts, no failure, and was not skipped
   118  	failure *protocol.Failure // failure of the pass
   119  }
   120  
   121  // analysisResultOf returns the result of analysisvet action a, or nil
   122  // if the action has not produced one (because it failed, or did not
   123  // run).
   124  func analysisResultOf(a *Action) *analysisResult {
   125  	res, _ := a.Provider.(*analysisResult)
   126  	return res
   127  }
   128  
   129  // The types of the protocol between the go command and the analysis
   130  // tool are defined by internal/analysis/gotestchecker/protocol.
   131  
   132  // analysisState is the per-Builder state of analysis in go test.
   133  type analysisState struct {
   134  	actions    []*Action                        // all actions of Mode "analysisvet"
   135  	roots      []*Action                        // analysisvet actions of root packages, in order of request
   136  	rootConfig map[*Action]*load.AnalysisConfig // root analysisvet action -> references that apply to its package
   137  	tool       *Action                          // link action for the tool
   138  	meta       *Action                          // analysismeta action
   139  
   140  	// toolPath is the executable of the tool. toolID identifies
   141  	// the executable for caching its metadata ("" if not cacheable).
   142  	toolPath, toolID string
   143  
   144  	// plan is set by the analysismeta action, before any
   145  	// analysisvet action runs, if the metadata is available.
   146  	plan *analysisPlan
   147  }
   148  
   149  // An analysisPlan holds the metadata of the analysis tool's analyzers
   150  // (by index) and the plan derived from it.
   151  type analysisPlan struct {
   152  	analyzers []analyzerInfo                        // index -> analyzer
   153  	driverID  cache.ActionID                        // dependency identity of the driver package
   154  	need      map[*Action][]int                     // analysisvet action -> sorted indexes of needed pass files
   155  	reported  map[*Action]map[int]*reportedAnalyzer // root analysisvet action -> index -> analyzer whose diagnostics are reported
   156  	refErrs   map[*Action][]string                  // root analysisvet action -> errors in its references
   157  }
   158  
   159  // An analyzerInfo holds the metadata of one of the analysis tool's
   160  // analyzers and information derived from it.
   161  type analyzerInfo struct {
   162  	*protocol.Analyzer                // metadata (Name, Requires, Facts, etc.)
   163  	reqClosure         []int          // sorted indexes of Requires closure (inclusive)
   164  	id                 cache.ActionID // identity
   165  }
   166  
   167  // A reportedAnalyzer describes an analyzer whose diagnostics are
   168  // reported for a root package. (The pass of that analyzer on that
   169  // package is a reported pass.)
   170  type reportedAnalyzer struct {
   171  	name string // "pkg.Var" or "pkg.Var[Name]"
   172  
   173  	// TODO(adonovan): more to come
   174  }
   175  
   176  // AnalysisVetAction returns an action that reports the diagnostics of
   177  // the analyzers enabled for package p by the specified configuration,
   178  // which must be non-nil. The action depends on the analysis of p,
   179  // which in turn depends on the analysis of each of p's dependencies,
   180  // which computes the facts needed by p's analyzers.
   181  // The tool must be supplied later by SetAnalysisTool.
   182  //
   183  // Reporting is a separate action from analysis because the analysis
   184  // action of a root package may be shared with the importers of that
   185  // package (e.g. a package without test files is itself the root, not
   186  // a test variant of it), and its diagnostics must not cause the
   187  // analysis of its importers to fail.
   188  func (b *Builder) AnalysisVetAction(s *modload.Loader, p *load.Package, config *load.AnalysisConfig) *Action {
   189  	if config == nil {
   190  		panic("nil config")
   191  	}
   192  	a := b.analysisVetAction(s, p)
   193  	st := &b.analysis
   194  	if _, ok := st.rootConfig[a]; !ok { // first request to vet p
   195  		st.roots = append(st.roots, a)
   196  		if st.rootConfig == nil {
   197  			st.rootConfig = make(map[*Action]*load.AnalysisConfig)
   198  		}
   199  	}
   200  	st.rootConfig[a] = config // (makes p a root package)
   201  	return &Action{
   202  		Mode:       "analysisreport",
   203  		Package:    p,
   204  		Deps:       []*Action{a},
   205  		Actor:      ActorFunc((*Builder).analysisReport),
   206  		IgnoreFail: true, // report diagnostics even if some analyzers failed
   207  	}
   208  }
   209  
   210  // analysisVetAction returns the analysisvet action for package p,
   211  // creating it (and those of p's dependencies) if necessary. The action
   212  // depends on the build of p and on the analysisvet action of each of
   213  // p's imports, from which it obtains facts.
   214  func (b *Builder) analysisVetAction(s *modload.Loader, p *load.Package) *Action {
   215  	return b.cacheAction("analysisvet", p, func() *Action {
   216  		a1 := b.BuildExportAction(ModeBuild, ModeBuild, p)
   217  		deps := []*Action{a1}
   218  		for _, p1 := range p.Internal.Imports {
   219  			deps = append(deps, b.analysisVetAction(s, p1))
   220  		}
   221  		a := &Action{
   222  			Mode:       "analysisvet",
   223  			Package:    p,
   224  			Deps:       deps,
   225  			Objdir:     b.NewObjdir(),
   226  			VetxOnly:   true,
   227  			IgnoreFail: true, // run the passes not downstream of a failed dependency (see analysisVet)
   228  		}
   229  		b.analysis.actions = append(b.analysis.actions, a)
   230  		if a1.Actor == nil {
   231  			// built-in package, such as unsafe
   232  			return a
   233  		}
   234  		if p.UsesCgo() || p.UsesSwig() {
   235  			a.Deps = append(a.Deps, b.runCgoAction(p, false))
   236  		}
   237  		a.Actor = ActorFunc((*Builder).analysisVet)
   238  		b.addTransitiveCompileActions(a, a1)
   239  		return a
   240  	})
   241  }
   242  
   243  // SetAnalysisTool records the link action of the analysis tool. It
   244  // creates the analysismeta action, which depends on the link action,
   245  // and makes every analysis action depend on it.
   246  func (b *Builder) SetAnalysisTool(link *Action) {
   247  	st := &b.analysis
   248  	st.tool = link
   249  	b.setAnalysisMeta(&Action{
   250  		Mode:   "analysismeta",
   251  		Deps:   []*Action{link},
   252  		Objdir: b.NewObjdir(),
   253  		Actor:  ActorFunc((*Builder).analysisMeta),
   254  	})
   255  }
   256  
   257  // setAnalysisMeta records the analysismeta action and makes every
   258  // analysis action depend on it.
   259  func (b *Builder) setAnalysisMeta(meta *Action) {
   260  	st := &b.analysis
   261  	st.meta = meta
   262  	for _, a := range st.actions {
   263  		if a.Actor != nil {
   264  			a.Deps = append(a.Deps, meta)
   265  		}
   266  	}
   267  }
   268  
   269  // prioritizeAnalysisTool gives the actions that build the analysis
   270  // tool and query its metadata precedence over all others, preserving
   271  // their relative order. No analysis can start until the metadata is
   272  // available, so building the tool early lets analysis proceed as soon
   273  // as each package is compiled, interleaved with the rest of the build,
   274  // rather than in a tail at the end. (The tool's dependencies include
   275  // std packages that the build needs anyway.)
   276  func (b *Builder) prioritizeAnalysisTool(all []*Action) {
   277  	if meta := b.analysis.meta; meta != nil {
   278  		for _, a := range actionList(meta) {
   279  			// Deps gate readiness; priority orders ready actions.
   280  			// This is the only adjustment to Do's DFS priorities.
   281  			a.priority -= len(all)
   282  		}
   283  	}
   284  }
   285  
   286  // HasAnalysisActions reports whether any analysis actions were created.
   287  func (b *Builder) HasAnalysisActions() bool { return len(b.analysis.actions) > 0 }
   288  
   289  // analysisMeta is the actor for the analysismeta action.
   290  // It runs the tool's metadata query and plans the analysis.
   291  func (b *Builder) analysisMeta(ctx context.Context, a *Action) error {
   292  	st := &b.analysis
   293  	st.toolPath = st.tool.BuiltTarget()
   294  	st.toolID = st.tool.buildID
   295  	data, err := b.analysisMetadata(a)
   296  	if err != nil || data == nil {
   297  		return err // (data is nil with -n)
   298  	}
   299  	md := new(protocol.Metadata)
   300  	if err := json.Unmarshal(data, md); err != nil {
   301  		return fmt.Errorf("decoding analysis tool metadata: %v", err)
   302  	}
   303  	driverID, ids := b.analyzerIDs(md)
   304  	b.planAnalysis(md, driverID, ids)
   305  	return nil
   306  }
   307  
   308  // analysisMetadata returns the result of the tool's metadata query,
   309  // running the tool if necessary. The metadata is cached, keyed by
   310  // the tool's build ID, so a warm run need not execute the tool.
   311  // It returns nil with -n.
   312  func (b *Builder) analysisMetadata(a *Action) ([]byte, error) {
   313  	st := &b.analysis
   314  	c := cache.Default()
   315  	h := cache.NewHash("analysis metadata")
   316  	fmt.Fprintf(h, "tool %s\n", st.toolID)
   317  	key := h.Sum()
   318  
   319  	if !cfg.BuildA && st.toolID != "" {
   320  		if data, _, err := cache.GetBytes(c, key); err == nil {
   321  			return data, nil
   322  		}
   323  	}
   324  	sh := b.Shell(a)
   325  	if err := sh.Mkdir(a.Objdir); err != nil {
   326  		return nil, err
   327  	}
   328  	file := a.Objdir + "metadata.json"
   329  	if err := sh.run(a.Objdir, "analysis tool", nil, cfg.BuildToolexec, st.toolPath, "-describe="+file); err != nil {
   330  		if cfg.Goos != runtime.GOOS || cfg.Goarch != runtime.GOARCH {
   331  			// The tool is built for the tests' platform and run
   332  			// on the host, which may not support it.
   333  			return nil, fmt.Errorf("running analysis tool built for %s/%s: %v\n(to run the tests on another platform, use -exec; to disable analysis, use -vet=off)", cfg.Goos, cfg.Goarch, err)
   334  		}
   335  		return nil, err
   336  	}
   337  	if cfg.BuildN {
   338  		return nil, nil
   339  	}
   340  	data, err := os.ReadFile(file)
   341  	if err != nil {
   342  		return nil, err
   343  	}
   344  	if st.toolID != "" {
   345  		if err := cache.PutBytes(c, key, data); err != nil {
   346  			return nil, err
   347  		}
   348  	}
   349  	return data, nil
   350  }
   351  
   352  // analyzerIDs computes the dependency identity of the driver package
   353  // and the identity of each analyzer of the metadata from the compiled
   354  // packages linked into the tool.
   355  //
   356  // The identity of an analyzer derives from its Name and Run function
   357  // (by run-time symbol name), and from the dependency identities of
   358  // the packages that declare the linked variables from which it is
   359  // reachable, as a member or by Requires edges. Their import closures
   360  // contain all the code of the analyzer, wherever it is declared.
   361  // The identity depends on which linked variables reach the analyzer,
   362  // but not on what else is linked into the tool, so that results are
   363  // shared by tools that link different sets of variables, and by all
   364  // the roots that require an analyzer. (An edit to any member of a
   365  // suite changes the identities of all its members, but such edits
   366  // are rare except for the author of the suite.)
   367  //
   368  // Distinct analyzers with the same Name and Run function ("twins")
   369  // reachable from the same variables have the same identity. The tool
   370  // rejects twins within the Requires closure of one member; twins in
   371  // different closures are not detected (unsound, but they do not arise
   372  // by accident).
   373  func (b *Builder) analyzerIDs(md *protocol.Metadata) (driverID cache.ActionID, ids []cache.ActionID) {
   374  	st := &b.analysis
   375  	compiled := make(map[string]*Action) // import path -> compile action
   376  	for _, a1 := range st.tool.Deps {
   377  		if a1.Package != nil {
   378  			compiled[a1.Package.ImportPath] = a1
   379  		}
   380  	}
   381  	// merkle returns the dependency identity of package p: a
   382  	// Merkle hash over its import graph, combining the content ID
   383  	// of p's compiled package with the dependency identities of
   384  	// its direct imports. It thus covers the content IDs of all
   385  	// the compiled packages in the import closure of p. It is
   386  	// memoized per package, so the closures of different
   387  	// packages, which overlap heavily, are each visited once.
   388  	depsMemo := make(map[*load.Package]cache.ActionID)
   389  	var merkle func(p *load.Package) cache.ActionID
   390  	merkle = func(p *load.Package) cache.ActionID {
   391  		if id, ok := depsMemo[p]; ok {
   392  			return id
   393  		}
   394  		h := cache.NewHash("analysis deps")
   395  		fmt.Fprintf(h, "package %q\n", p.ImportPath)
   396  		// Built-in packages such as unsafe
   397  		// have no compile action.
   398  		if a1 := compiled[p.ImportPath]; a1 != nil {
   399  			fmt.Fprintf(h, "content %s\n", a1.BuildContentID())
   400  		}
   401  		// Combine the identities of the direct imports by
   402  		// addition (mod 2^256), which is independent of their
   403  		// order (p.Internal.Imports is not necessarily sorted).
   404  		// XOR would also be, but a test variant's Imports may
   405  		// list a package twice (once from the test files), and
   406  		// XOR would cancel the pair.
   407  		var imports cache.ActionID
   408  		for _, imp := range p.Internal.Imports {
   409  			addActionID(&imports, merkle(imp))
   410  		}
   411  		fmt.Fprintf(h, "imports %x\n", imports)
   412  		id := h.Sum()
   413  		depsMemo[p] = id
   414  		return id
   415  	}
   416  	// The driver package is always linked into the tool, since the
   417  	// synthesized main package imports it.
   418  	driverID = merkle(compiled[load.AnalysisToolDriver].Package)
   419  
   420  	// varPkgs[h] is the set of packages that declare a linked
   421  	// variable from whose members analyzer h is reachable by
   422  	// Requires edges.
   423  	//
   424  	// We assume that a variable's value, and everything reachable
   425  	// from it (its analyzers, their prerequisites, their Run
   426  	// functions, and the code those call), is determined by code
   427  	// within the import closure of the variable's package, so that
   428  	// the closures of these packages contain all the code of the
   429  	// analyzer, wherever it is declared. The assumption fails only
   430  	// if code outside the closure modifies the variable (for
   431  	// example, a checker package that registers itself from an
   432  	// init function in a registry variable that it imports). Such
   433  	// code is linked into the tool only if the package of another
   434  	// variable imports it, so a failure implies interference
   435  	// between variables, which we already exclude (see the package
   436  	// comment). See also the addendum on analyzer identity in the
   437  	// design doc for go.dev/issue/82464.
   438  	varPkgs := make([]map[string]bool, len(md.Analyzers))
   439  	for _, v := range md.Vars {
   440  		if v.Error != "" {
   441  			continue // Members undefined
   442  		}
   443  		pkg := v.Symbol[:strings.LastIndexByte(v.Symbol, '.')]
   444  		var visit func(h int)
   445  		visit = func(h int) {
   446  			if varPkgs[h] == nil {
   447  				varPkgs[h] = make(map[string]bool)
   448  			}
   449  			if !varPkgs[h][pkg] {
   450  				varPkgs[h][pkg] = true
   451  				for _, req := range md.Analyzers[h].Requires {
   452  					visit(req)
   453  				}
   454  			}
   455  		}
   456  		for _, m := range v.Members {
   457  			if m.Analyzer >= 0 {
   458  				visit(m.Analyzer)
   459  			}
   460  		}
   461  	}
   462  
   463  	ids = make([]cache.ActionID, len(md.Analyzers))
   464  	for h, an := range md.Analyzers {
   465  		hash := cache.NewHash("analyzer")
   466  		fmt.Fprintf(hash, "name %q\nrun %q\ndriver %x\n", an.Name, an.RunFunc, driverID)
   467  		// Combine the dependency identities of the packages
   468  		// of varPkgs[h] by addition (see merkle).
   469  		var vars cache.ActionID
   470  		linked := len(varPkgs[h]) > 0
   471  		for pkg := range varPkgs[h] {
   472  			if a1 := compiled[pkg]; a1 != nil {
   473  				addActionID(&vars, merkle(a1.Package))
   474  			} else {
   475  				linked = false
   476  			}
   477  		}
   478  		fmt.Fprintf(hash, "vars %x\n", vars)
   479  		if !linked {
   480  			// The packages of the variables are not
   481  			// known. Use the identity of the tool, which
   482  			// is sound but defeats sharing.
   483  			fmt.Fprintf(hash, "tool %s\n", st.tool.buildID)
   484  		}
   485  		ids[h] = hash.Sum()
   486  	}
   487  	return driverID, ids
   488  }
   489  
   490  // addActionID sets *sum to *sum + id, treating both as 256-bit
   491  // little-endian integers and discarding the carry out.
   492  func addActionID(sum *cache.ActionID, id cache.ActionID) {
   493  	var carry uint16
   494  	for i := range sum {
   495  		s := uint16(sum[i]) + uint16(id[i]) + carry
   496  		sum[i] = byte(s)
   497  		carry = s >> 8
   498  	}
   499  }
   500  
   501  // planAnalysis performs the dynamic stage of resolution, computing
   502  // the analyzers reported for each root package and the set of pass
   503  // files needed from each analysisvet action. It sets st.plan.
   504  // driverID and ids are the identities of the driver package and of each
   505  // analyzer (see analyzerIDs).
   506  func (b *Builder) planAnalysis(md *protocol.Metadata, driverID cache.ActionID, ids []cache.ActionID) {
   507  	st := &b.analysis
   508  
   509  	// Index the metadata. Analyzers are identified by their index
   510  	// in md.Analyzers, which is in topological order (prerequisites
   511  	// first).
   512  	plan := &analysisPlan{
   513  		analyzers: make([]analyzerInfo, len(md.Analyzers)),
   514  		driverID:  driverID,
   515  		reported:  make(map[*Action]map[int]*reportedAnalyzer),
   516  		refErrs:   make(map[*Action][]string),
   517  	}
   518  	for i, an := range md.Analyzers {
   519  		set := map[int]bool{i: true}
   520  		for _, req := range an.Requires {
   521  			for _, j := range plan.analyzers[req].reqClosure { // (computed already)
   522  				set[j] = true
   523  			}
   524  		}
   525  		plan.analyzers[i] = analyzerInfo{
   526  			Analyzer:   an,
   527  			reqClosure: slices.Sorted(maps.Keys(set)),
   528  			id:         ids[i],
   529  		}
   530  	}
   531  
   532  	// closure returns the sorted union of the Requires closures of
   533  	// the analyzers hs.
   534  	closure := func(hs []int) []int {
   535  		set := make(map[int]bool)
   536  		for _, h := range hs {
   537  			for _, h2 := range plan.analyzers[h].reqClosure {
   538  				set[h2] = true
   539  			}
   540  		}
   541  		return slices.Sorted(maps.Keys(set))
   542  	}
   543  
   544  	// Expand suites, apply selectors and negations, and compute
   545  	// the analyzers reported for each root package.
   546  	for _, a := range st.roots {
   547  		plan.reported[a], plan.refErrs[a] = resolveAnalyzers(md, st.rootConfig[a])
   548  	}
   549  
   550  	// Compute the pass files needed from each analysisvet action:
   551  	// one for each pass that runs, whether or not it has facts or
   552  	// diagnostics, so that its outcome (including a failure) is
   553  	// recorded in exactly one place. A root package runs the
   554  	// Requires closure of its reported analyzers; it and each of
   555  	// its transitive dependencies run the Requires closure of the
   556  	// analyzers that use facts in that closure. (Most such pass
   557  	// files are trivial, and are not read by importers.)
   558  	need := make(map[*Action]map[int]bool)
   559  	// add adds the analyzers hs to the needs of action a, and
   560  	// reports whether any of them was new.
   561  	add := func(a *Action, hs []int) bool {
   562  		set := need[a]
   563  		if set == nil {
   564  			set = make(map[int]bool)
   565  			need[a] = set
   566  		}
   567  		added := false
   568  		for _, h := range hs {
   569  			if !set[h] {
   570  				set[h] = true
   571  				added = true
   572  			}
   573  		}
   574  		return added
   575  	}
   576  	// propagate adds the analyzers hs, a Requires closure of
   577  	// analyzers that use facts, to the needs of each analysisvet
   578  	// dependency of a, and recursively of theirs. It stops at a
   579  	// dependency that already had them all: its own dependencies
   580  	// were given them when it was.
   581  	//
   582  	// (It propagates to the dependencies directly: the needs of a
   583  	// root package, the closure of its reported analyzers,
   584  	// already include hs.)
   585  	var propagate func(a *Action, hs []int)
   586  	propagate = func(a *Action, hs []int) {
   587  		for _, dep := range a.Deps {
   588  			if dep.Mode == "analysisvet" && add(dep, hs) {
   589  				propagate(dep, hs)
   590  			}
   591  		}
   592  	}
   593  	for _, a := range st.roots {
   594  		run := closure(slices.Collect(maps.Keys(plan.reported[a])))
   595  		add(a, run)
   596  		var factUsers []int
   597  		for _, h := range run {
   598  			if plan.analyzers[h].Facts {
   599  				factUsers = append(factUsers, h)
   600  			}
   601  		}
   602  		propagate(a, closure(factUsers))
   603  	}
   604  	plan.need = make(map[*Action][]int)
   605  	for a, set := range need {
   606  		plan.need[a] = slices.Sorted(maps.Keys(set))
   607  	}
   608  	st.plan = plan
   609  }
   610  
   611  // resolveAnalyzers performs the dynamic stage of resolution for one
   612  // root package, whose references are described by config. Using
   613  // the tool's metadata, it expands suites, applies selectors, and
   614  // applies negations by Analyzer.Name. It returns the analyzers whose diagnostics are reported, by index, and
   615  // errors in the references.
   616  //
   617  // Validation is per reference: an invalid reference (or member) is
   618  // reported and dropped; the others still run.
   619  func resolveAnalyzers(md *protocol.Metadata, config *load.AnalysisConfig) (map[int]*reportedAnalyzer, []string) {
   620  	var errs []string
   621  	errorf := func(annot *load.AnalysisRef, format string, args ...any) {
   622  		errs = append(errs, annot.Errorf(format, args...).Error())
   623  	}
   624  
   625  	// members returns the valid members selected by reference
   626  	// annot, with their indexes and display names, reporting any
   627  	// errors.
   628  	type member struct {
   629  		index int
   630  		name  string
   631  	}
   632  	members := func(annot *load.AnalysisRef) []member {
   633  		v := md.Var(annot.Var.String())
   634  		if v == nil {
   635  			return nil // not linked (error reported statically)
   636  		}
   637  		if v.Error != "" {
   638  			errorf(annot, "%s", v.Error)
   639  			return nil
   640  		}
   641  		if v.IsSuite != annot.IsSuite() {
   642  			if !v.IsSuite {
   643  				errorf(annot, "%s is an analyzer, not a suite (remove the brackets)", annot.Var)
   644  			} else {
   645  				errorf(annot, "%[1]s is a suite (use %[1]s[*] or select members by name)", annot.Var)
   646  			}
   647  			return nil
   648  		}
   649  		var res []member
   650  		addMember := func(m *protocol.Member) {
   651  			name := annot.Var.String()
   652  			if v.IsSuite {
   653  				name += "[" + m.Name + "]"
   654  			}
   655  			if m.Analyzer < 0 {
   656  				msg := m.Error
   657  				if v.IsSuite {
   658  					msg = fmt.Sprintf("member %s: %s", m.Name, msg)
   659  				}
   660  				errorf(annot, "%s", msg)
   661  				return
   662  			}
   663  			res = append(res, member{m.Analyzer, name})
   664  		}
   665  		if !annot.IsSuite() || annot.AllMembers() {
   666  			for _, m := range v.Members {
   667  				addMember(m)
   668  			}
   669  		} else {
   670  			for _, name := range annot.Members {
   671  				i := slices.IndexFunc(v.Members, func(m *protocol.Member) bool {
   672  					return m.Name == name
   673  				})
   674  				if i < 0 {
   675  					errorf(annot, "suite %s has no member named %s", annot.Var.String(), name)
   676  					continue
   677  				}
   678  				addMember(v.Members[i])
   679  			}
   680  		}
   681  		return res
   682  	}
   683  
   684  	// Enable the members of each positive reference. The first
   685  	// (most specific) enabling reference of each analyzer wins.
   686  	enabled := make(map[int]*reportedAnalyzer)
   687  	for _, annot := range config.Positive {
   688  		for _, m := range members(annot) {
   689  			if _, ok := enabled[m.index]; !ok {
   690  				enabled[m.index] = &reportedAnalyzer{name: m.name}
   691  			}
   692  		}
   693  	}
   694  
   695  	// Apply negations: a negation by name disables every enabled
   696  	// analyzer of that name.
   697  	for _, annot := range config.Negative {
   698  		for h := range enabled {
   699  			if md.Analyzers[h].Name == annot.Name {
   700  				delete(enabled, h)
   701  			}
   702  		}
   703  	}
   704  	return enabled, errs
   705  }
   706  
   707  // analysisVet is the actor for an analysisvet action.
   708  func (b *Builder) analysisVet(ctx context.Context, a *Action) error {
   709  	// Clear the failure that the scheduler propagated from the
   710  	// dependencies: this action decides for itself, pass by pass,
   711  	// what it can do. The analysis of a dependency may have
   712  	// failed (reported there), but its types are available, so
   713  	// this package's types are computed, and the passes not
   714  	// downstream of the failure run; those downstream are skipped.
   715  	// Otherwise the outcome for this package would depend on which
   716  	// other packages are roots (whose analyzers the dependency was
   717  	// analyzed with).
   718  	a.Failed = nil
   719  
   720  	// a.Deps[0] is the build of the package being analyzed.
   721  	if a.Deps[0].Failed != nil {
   722  		return nil // the build of the package failed; skip analysis
   723  	}
   724  	for _, a1 := range a.Deps {
   725  		if a1.Failed != nil && a1.Mode == "cgo run" {
   726  			return nil // cgo failed; skip analysis
   727  		}
   728  	}
   729  	st := &b.analysis
   730  	if cfg.BuildN {
   731  		// Without the tool's metadata, the analysis cannot be
   732  		// planned, so show a placeholder command for each root
   733  		// package.
   734  		if _, ok := st.rootConfig[a]; ok {
   735  			b.Shell(a).ShowCmd("", "%s %s # analyzers determined by -describe", st.toolPath, a.Objdir+"analysis.cfg")
   736  		}
   737  		return nil
   738  	}
   739  	plan := st.plan
   740  	if plan == nil {
   741  		return nil // tool or metadata query failed (reported elsewhere)
   742  	}
   743  
   744  	// Gather the results of the direct imports.
   745  	var deps []*Action
   746  	for _, a1 := range a.Deps {
   747  		if a1.Mode == "analysisvet" && a1.Actor != nil {
   748  			if analysisResultOf(a1) == nil {
   749  				return nil // analysis of dependency failed (reported elsewhere)
   750  			}
   751  			deps = append(deps, a1)
   752  		}
   753  	}
   754  	slices.SortFunc(deps, func(x, y *Action) int {
   755  		return strings.Compare(x.Package.ImportPath, y.Package.ImportPath)
   756  	})
   757  
   758  	reported := func(index int) bool {
   759  		_, ok := plan.reported[a][index]
   760  		return ok
   761  	}
   762  	vcfg0, vetDir := buildVetConfig(a)
   763  
   764  	// The vet config names files generated in vetDir (those generated
   765  	// by cgo) relative to it, since cmd/vet runs there (see trimObjdir).
   766  	// The tool runs in the package directory, so make them absolute.
   767  	absFiles := func(files []string) []string {
   768  		res := make([]string, len(files))
   769  		for i, file := range files {
   770  			if !filepath.IsAbs(file) {
   771  				file = vetDir + file
   772  			}
   773  			res[i] = file
   774  		}
   775  		return res
   776  	}
   777  	var (
   778  		goFiles      = absFiles(vcfg0.GoFiles)
   779  		nonGoFiles   = absFiles(vcfg0.NonGoFiles)
   780  		ignoredFiles = absFiles(vcfg0.IgnoredFiles)
   781  	)
   782  
   783  	// Compute a key for the package's inputs. (We don't use the
   784  	// compile action ID, which depends on incidental details of the
   785  	// action graph, such as whether a tested package is also
   786  	// imported by another tested package.) The types of the direct
   787  	// imports are represented by their output IDs, giving early
   788  	// cutoff when a dependency changes but its API does not.
   789  	pkgID := func() cache.ActionID {
   790  		h := cache.NewHash("analysis pkg " + a.Package.ImportPath)
   791  		fmt.Fprintf(h, "id %q\nimportpath %q\ngoversion %q\n", vcfg0.ID, vcfg0.ImportPath, vcfg0.GoVersion)
   792  		// The target configuration.
   793  		fmt.Fprintf(h, "goos %q\ngoarch %q\ntags %q\ntooltags %q\n", cfg.Goos, cfg.Goarch, cfg.BuildContext.BuildTags, cfg.BuildContext.ToolTags)
   794  		if m := vcfg0.Module; m != nil {
   795  			fmt.Fprintf(h, "module %q %q %q\n", m.Path, m.Version, m.GoVersion)
   796  		}
   797  		// Files are identified by name and content. The name
   798  		// appears in positions, so it must be the actual name
   799  		// (which may be that of an overlay replacement), except
   800  		// for files generated (by cgo or -cover) in the work
   801  		// directory, whose name varies from run to run, and which
   802  		// are identified by base name.
   803  		fmt.Fprintf(h, "dir %q\n", vcfg0.Dir)
   804  		for _, files := range [][]string{goFiles, nonGoFiles, ignoredFiles} {
   805  			for _, file := range files {
   806  				name := file
   807  				if str.HasFilePathPrefix(file, b.WorkDir) {
   808  					name = filepath.Base(file)
   809  				}
   810  				fmt.Fprintf(h, "file %q %s\n", name, b.fileHash(file))
   811  			}
   812  			fmt.Fprintf(h, "\n")
   813  		}
   814  		// Hash only the import mappings that refer to actual
   815  		// imports: the vet config may contain spurious ones
   816  		// (e.g. a self-mapping added when a tested package is
   817  		// also imported by another tested package).
   818  		depPaths := map[string]bool{"unsafe": true}
   819  		for _, a1 := range deps {
   820  			depPaths[a1.Package.ImportPath] = true
   821  		}
   822  		for _, k := range slices.Sorted(maps.Keys(vcfg0.ImportMap)) {
   823  			if v := vcfg0.ImportMap[k]; depPaths[v] {
   824  				fmt.Fprintf(h, "importmap %q %q\n", k, v)
   825  			}
   826  		}
   827  		for _, a1 := range deps {
   828  			fmt.Fprintf(h, "dep %q %x\n", a1.Package.ImportPath, analysisResultOf(a1).types.id)
   829  		}
   830  		return h.Sum()
   831  	}()
   832  
   833  	// Compute the cache keys.
   834  	typesKey := func() cache.ActionID {
   835  		h := cache.NewHash("analysis types " + a.Package.ImportPath)
   836  		fmt.Fprintf(h, "pkg %x\ndriver %x\n", pkgID, plan.driverID)
   837  		return h.Sum()
   838  	}()
   839  	typeErrsKey := func() cache.ActionID {
   840  		h := cache.NewHash("analysis type errors " + a.Package.ImportPath)
   841  		fmt.Fprintf(h, "types %x\n", typesKey)
   842  		return h.Sum()
   843  	}()
   844  	passKey := func(index int) cache.ActionID {
   845  		h := cache.NewHash("analysis pass " + a.Package.ImportPath)
   846  		fmt.Fprintf(h, "pkg %x\nanalyzer %x\nreport %t\n", pkgID, plan.analyzers[index].id, reported(index))
   847  		for _, h2 := range plan.analyzers[index].reqClosure {
   848  			if plan.analyzers[h2].Facts {
   849  				for _, a1 := range deps {
   850  					fmt.Fprintf(h, "dep %q %x %x\n", a1.Package.ImportPath, plan.analyzers[h2].id, analysisResultOf(a1).passes[h2].factsID)
   851  				}
   852  			}
   853  		}
   854  		return h.Sum()
   855  	}
   856  
   857  	// Look up each entry; note the missing ones.
   858  	c := cache.Default()
   859  	get := func(key cache.ActionID) (analysisOutput, bool) {
   860  		if !cfg.BuildA {
   861  			if file, entry, err := cache.GetFile(c, key); err == nil {
   862  				return analysisOutput{file: file, id: entry.OutputID}, true
   863  			}
   864  		}
   865  		return analysisOutput{}, false
   866  	}
   867  	res := &analysisResult{passes: make(map[int]analysisOutput)}
   868  	// The types and type errors are produced together.
   869  	if out, ok := get(typesKey); ok {
   870  		if data, _, err := cache.GetBytes(c, typeErrsKey); err == nil && json.Unmarshal(data, &res.typeErrs) == nil {
   871  			res.types = out
   872  		}
   873  	}
   874  	needTypes := res.types.file == ""
   875  	var missing []int
   876  	for _, index := range plan.need[a] {
   877  		if out, ok := get(passKey(index)); ok && out.readPassInfo() == nil {
   878  			res.passes[index] = out
   879  		} else {
   880  			missing = append(missing, index)
   881  		}
   882  	}
   883  
   884  	// Run the tool, if necessary.
   885  	if len(missing) > 0 || needTypes {
   886  		areq := &protocol.AnalyzeRequest{
   887  			ID:           vcfg0.ID,
   888  			ImportPath:   vcfg0.ImportPath,
   889  			Dir:          vcfg0.Dir,
   890  			GoFiles:      goFiles,
   891  			NonGoFiles:   nonGoFiles,
   892  			IgnoredFiles: ignoredFiles,
   893  			ImportMap:    vcfg0.ImportMap,
   894  			GoVersion:    vcfg0.GoVersion,
   895  			GOARCH:       cfg.Goarch,
   896  			Module:       protocolModule(vcfg0.Module),
   897  			TypeImports:  make(map[string]string),
   898  			Facts:        make(map[int]map[string]string),
   899  			Outputs:      make(map[int]string),
   900  			Report:       []int{},
   901  		}
   902  		for _, a1 := range deps {
   903  			areq.TypeImports[a1.Package.ImportPath] = analysisResultOf(a1).types.file
   904  		}
   905  		if needTypes {
   906  			areq.TypeExport = a.Objdir + "types"
   907  			areq.TypeErrors = a.Objdir + "typeerrors"
   908  		}
   909  		for i, index := range missing {
   910  			areq.Outputs[index] = fmt.Sprintf("%spass%d", a.Objdir, i)
   911  			if reported(index) {
   912  				areq.Report = append(areq.Report, index)
   913  			}
   914  			for _, h2 := range plan.analyzers[index].reqClosure {
   915  				if plan.analyzers[h2].Facts && areq.Facts[h2] == nil {
   916  					files := make(map[string]string)
   917  					for _, a1 := range deps {
   918  						// A trivial pass file need not be read:
   919  						// a missing entry denotes no facts.
   920  						if out, ok := analysisResultOf(a1).passes[h2]; ok && !out.trivial {
   921  							files[a1.Package.ImportPath] = out.file
   922  						}
   923  					}
   924  					areq.Facts[h2] = files
   925  				}
   926  			}
   927  		}
   928  
   929  		sh := b.Shell(a)
   930  		js, err := json.Marshal(areq)
   931  		if err != nil {
   932  			return fmt.Errorf("internal error marshaling analysis config: %v", err)
   933  		}
   934  		if err := sh.Mkdir(a.Objdir); err != nil {
   935  			return err
   936  		}
   937  		if err := sh.writeFile(a.Objdir+"analysis.cfg", js); err != nil {
   938  			return err
   939  		}
   940  		p := a.Package
   941  		if err := sh.run(p.Dir, p.ImportPath, b.cCompilerEnv(), cfg.BuildToolexec, st.toolPath, a.Objdir+"analysis.cfg"); err != nil {
   942  			return err
   943  		}
   944  
   945  		// Save the outputs in the cache.
   946  		put := func(key cache.ActionID, file string) (analysisOutput, error) {
   947  			f, err := os.Open(file)
   948  			if err != nil {
   949  				return analysisOutput{}, err
   950  			}
   951  			defer f.Close()
   952  			id, _, err := c.Put(key, f)
   953  			if err != nil {
   954  				return analysisOutput{}, err
   955  			}
   956  			return analysisOutput{file: c.OutputFile(id), id: id}, nil
   957  		}
   958  		if needTypes {
   959  			data, err := os.ReadFile(areq.TypeErrors)
   960  			if err != nil {
   961  				return err
   962  			}
   963  			if err := json.Unmarshal(data, &res.typeErrs); err != nil {
   964  				return fmt.Errorf("decoding type errors of %s: %v", vcfg0.ID, err)
   965  			}
   966  			if err := cache.PutBytes(c, typeErrsKey, data); err != nil {
   967  				return err
   968  			}
   969  			res.types, err = put(typesKey, areq.TypeExport)
   970  			if err != nil {
   971  				return err
   972  			}
   973  		}
   974  		for _, index := range missing {
   975  			out, err := put(passKey(index), areq.Outputs[index])
   976  			if err != nil {
   977  				return err
   978  			}
   979  			if err := out.readPassInfo(); err != nil {
   980  				return err
   981  			}
   982  			res.passes[index] = out
   983  		}
   984  	}
   985  	a.Provider = res
   986  
   987  	// Report the type errors of this package and the failures of
   988  	// analyzers on it, whether computed or cached. Each is
   989  	// reported once, here; the passes skipped because of it (here
   990  	// and in importers) are not.
   991  	var buf bytes.Buffer
   992  	for _, msg := range res.typeErrs {
   993  		fmt.Fprintf(&buf, "%s\n", msg)
   994  	}
   995  	for _, index := range plan.need[a] {
   996  		if f := res.passes[index].failure; f != nil {
   997  			fmt.Fprintf(&buf, "%s\n", f)
   998  		}
   999  	}
  1000  	if buf.Len() > 0 {
  1001  		return b.Shell(a).reportCmd("", "", buf.Bytes(), errors.New("analysis failed"))
  1002  	}
  1003  	return nil
  1004  }
  1005  
  1006  // analysisReport is the actor for an analysisreport action.
  1007  func (b *Builder) analysisReport(ctx context.Context, r *Action) error {
  1008  	a := r.Deps[0]
  1009  	if a.Actor == nil || a.Deps[0].Failed != nil {
  1010  		return nil // built-in package, or build failed (reported elsewhere)
  1011  	}
  1012  	plan := b.analysis.plan
  1013  	if plan == nil {
  1014  		return nil // tool or metadata query failed (reported elsewhere)
  1015  	}
  1016  	reported := plan.reported[a]
  1017  
  1018  	var buf bytes.Buffer
  1019  	incomplete := false // some reported analyzer failed or was skipped
  1020  
  1021  	// Report errors in the references.
  1022  	for _, msg := range plan.refErrs[a] {
  1023  		fmt.Fprintf(&buf, "%s\n", msg)
  1024  	}
  1025  
  1026  	// Report the diagnostics of the reported analyzers,
  1027  	// ordered by name. (Type errors and failures are
  1028  	// reported by the analysisvet action of the
  1029  	// package in which they occur.)
  1030  	indexes := slices.SortedFunc(maps.Keys(reported), func(x, y int) int {
  1031  		return strings.Compare(reported[x].name, reported[y].name)
  1032  	})
  1033  	res := analysisResultOf(a)
  1034  	if res == nil {
  1035  		// Analysis of the package failed (reported elsewhere).
  1036  		incomplete = len(indexes) > 0
  1037  	} else {
  1038  		for _, index := range indexes {
  1039  			en := reported[index]
  1040  			out, ok := res.passes[index]
  1041  			if !ok {
  1042  				// Every reported analyzer is in plan.need[a].
  1043  				return fmt.Errorf("internal error: no pass file for analyzer %s", en.name)
  1044  			}
  1045  			pf, err := protocol.ReadPass(out.file)
  1046  			if err != nil {
  1047  				return err
  1048  			}
  1049  			if pf.Failure != nil || pf.Skipped {
  1050  				incomplete = true
  1051  			}
  1052  			for _, d := range pf.Diagnostics {
  1053  				fmt.Fprintf(&buf, "%s: %s\n", d.Posn, d.Message)
  1054  			}
  1055  		}
  1056  	}
  1057  	if buf.Len() > 0 {
  1058  		return b.Shell(r).reportCmd("", "", buf.Bytes(), errors.New("analysis reported problems"))
  1059  	}
  1060  
  1061  	if incomplete {
  1062  		// Some analyzer failed or was skipped, because of
  1063  		// an error reported elsewhere (see analysisVet).
  1064  		// The test must not run, but there is nothing more
  1065  		// to say: this action fails as a consequence of the
  1066  		// analysis action, without an error of its own.
  1067  		r.Failed = a
  1068  	}
  1069  
  1070  	return nil
  1071  }
  1072  
  1073  // readPassInfo reads the pass file out.file, written by the analysis
  1074  // tool, and sets the other fields of out from it.
  1075  //
  1076  // factsID is the hash of the parts of the pass file other than its
  1077  // diagnostics: its facts, its failure, and whether it was skipped. It
  1078  // is the part of the pass file on which dependent passes depend.
  1079  //
  1080  // trivial reports whether the pass file has no facts, no failure, and
  1081  // was not skipped. The analysis of an importer need not read a
  1082  // trivial pass file.
  1083  func (out *analysisOutput) readPassInfo() error {
  1084  	pf, err := protocol.ReadPass(out.file)
  1085  	if err != nil {
  1086  		return err
  1087  	}
  1088  	h := sha256.New()
  1089  	fmt.Fprintf(h, "facts %d\n", len(pf.Facts))
  1090  	h.Write(pf.Facts)
  1091  	if f := pf.Failure; f != nil {
  1092  		fmt.Fprintf(h, "failure %q %q %q\n", f.Package, f.Analyzer, f.Message)
  1093  	}
  1094  	fmt.Fprintf(h, "skipped %t\n", pf.Skipped)
  1095  	h.Sum(out.factsID[:0])
  1096  	out.trivial = len(pf.Facts) == 0 && pf.Failure == nil && !pf.Skipped
  1097  	out.failure = pf.Failure
  1098  	return nil
  1099  }
  1100  
  1101  // protocolModule converts the module of a vet configuration to its
  1102  // form in the analysis protocol.
  1103  func protocolModule(m *vetModule) *protocol.Module {
  1104  	if m == nil {
  1105  		return nil
  1106  	}
  1107  	pm := &protocol.Module{
  1108  		Path:      m.Path,
  1109  		Version:   m.Version,
  1110  		Replace:   protocolModule(m.Replace),
  1111  		Time:      m.Time,
  1112  		Main:      m.Main,
  1113  		Indirect:  m.Indirect,
  1114  		Dir:       m.Dir,
  1115  		GoMod:     m.GoMod,
  1116  		GoVersion: m.GoVersion,
  1117  	}
  1118  	if m.Error != nil {
  1119  		pm.Error = &protocol.ModuleError{Err: m.Error.Err}
  1120  	}
  1121  	return pm
  1122  }
  1123  

View as plain text