| 1 | // Copyright 2018 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 internal/checker defines various implementation helpers for |
| 6 | // the singlechecker and multichecker packages, which provide the |
| 7 | // complete main function for an analysis driver executable |
| 8 | // based on go/packages. |
| 9 | // |
| 10 | // (Note: it is not used by the public 'checker' package, since the |
| 11 | // latter provides a set of pure functions for use as building blocks.) |
| 12 | package checker |
| 13 | |
| 14 | // TODO(adonovan): publish the JSON schema in go/analysis or analysisjson. |
| 15 | |
| 16 | import ( |
| 17 | "flag" |
| 18 | "fmt" |
| 19 | "io" |
| 20 | |
| 21 | "log" |
| 22 | "os" |
| 23 | "runtime" |
| 24 | "runtime/pprof" |
| 25 | "runtime/trace" |
| 26 | "sort" |
| 27 | "strings" |
| 28 | "time" |
| 29 | |
| 30 | "golang.org/x/tools/go/analysis" |
| 31 | "golang.org/x/tools/go/analysis/checker" |
| 32 | "golang.org/x/tools/go/analysis/internal" |
| 33 | "golang.org/x/tools/go/analysis/internal/analysisflags" |
| 34 | "golang.org/x/tools/go/packages" |
| 35 | "golang.org/x/tools/internal/analysis/driverutil" |
| 36 | ) |
| 37 | |
| 38 | var ( |
| 39 | // Debug is a set of single-letter flags: |
| 40 | // |
| 41 | // f show [f]acts as they are created |
| 42 | // p disable [p]arallel execution of analyzers |
| 43 | // s do additional [s]anity checks on fact types and serialization |
| 44 | // t show [t]iming info (NB: use 'p' flag to avoid GC/scheduler noise) |
| 45 | // v show [v]erbose logging |
| 46 | // |
| 47 | Debug = "" |
| 48 | |
| 49 | // Log files for optional performance tracing. |
| 50 | CPUProfile, MemProfile, Trace string |
| 51 | |
| 52 | // IncludeTests indicates whether test files should be analyzed too. |
| 53 | IncludeTests = true |
| 54 | ) |
| 55 | |
| 56 | // RegisterFlags registers command-line flags used by the analysis driver. |
| 57 | func RegisterFlags() { |
| 58 | // When adding flags here, remember to update |
| 59 | // the list of suppressed flags in analysisflags. |
| 60 | |
| 61 | flag.StringVar(&Debug, "debug", Debug, `debug flags, any subset of "fpstv"`) |
| 62 | |
| 63 | flag.StringVar(&CPUProfile, "cpuprofile", "", "write CPU profile to this file") |
| 64 | flag.StringVar(&MemProfile, "memprofile", "", "write memory profile to this file") |
| 65 | flag.StringVar(&Trace, "trace", "", "write trace log to this file") |
| 66 | flag.BoolVar(&IncludeTests, "test", IncludeTests, "indicates whether test files should be analyzed, too") |
| 67 | } |
| 68 | |
| 69 | // Run loads the packages specified by args using go/packages, |
| 70 | // then applies the specified analyzers to them. |
| 71 | // Analysis flags must already have been set. |
| 72 | // Analyzers must be valid according to [analysis.Validate]. |
| 73 | // It provides most of the logic for the main functions of both the |
| 74 | // singlechecker and the multi-analysis commands. |
| 75 | // It returns the appropriate exit code. |
| 76 | // |
| 77 | // TODO(adonovan): tests should not call this function directly. |
| 78 | // Fiddling with global variables (flags such as [analysisflags.Fix]) |
| 79 | // is error-prone and hostile to parallelism. Instead, use unit tests |
| 80 | // of the actual units (e.g. checker.Analyze) and integration tests |
| 81 | // (e.g. TestScript) of whole executables. |
| 82 | func Run(args []string, analyzers []*analysis.Analyzer) (exitcode int) { |
| 83 | // Instead of returning a code directly, |
| 84 | // call this function to monotonically increase the exit code. |
| 85 | // This allows us to keep going in the face of some errors |
| 86 | // without having to remember what code to return. |
| 87 | // |
| 88 | // TODO(adonovan): interpreting exit codes is like reading tea-leaves. |
| 89 | // Instead of wasting effort trying to encode a multidimensional result |
| 90 | // into 7 bits we should just emit structured JSON output, and |
| 91 | // an exit code of 0 or 1 for success or failure. |
| 92 | exitAtLeast := func(code int) { |
| 93 | exitcode = max(code, exitcode) |
| 94 | } |
| 95 | |
| 96 | // Since analysisflags is linked in (for {single,multi}checker), |
| 97 | // the -v flag is registered for complex legacy reasons |
| 98 | // related to cmd/vet CLI. |
| 99 | // Treat it as an undocumented alias for -debug=v. |
| 100 | if v := flag.CommandLine.Lookup("v"); v != nil && |
| 101 | v.Value.(flag.Getter).Get() == true && |
| 102 | !strings.Contains(Debug, "v") { |
| 103 | Debug += "v" |
| 104 | } |
| 105 | |
| 106 | if CPUProfile != "" { |
| 107 | f, err := os.Create(CPUProfile) |
| 108 | if err != nil { |
| 109 | log.Fatal(err) |
| 110 | } |
| 111 | if err := pprof.StartCPUProfile(f); err != nil { |
| 112 | log.Fatal(err) |
| 113 | } |
| 114 | // NB: profile won't be written in case of error. |
| 115 | defer pprof.StopCPUProfile() |
| 116 | } |
| 117 | |
| 118 | if Trace != "" { |
| 119 | f, err := os.Create(Trace) |
| 120 | if err != nil { |
| 121 | log.Fatal(err) |
| 122 | } |
| 123 | if err := trace.Start(f); err != nil { |
| 124 | log.Fatal(err) |
| 125 | } |
| 126 | // NB: trace log won't be written in case of error. |
| 127 | defer func() { |
| 128 | trace.Stop() |
| 129 | log.Printf("To view the trace, run:\n$ go tool trace view %s", Trace) |
| 130 | }() |
| 131 | } |
| 132 | |
| 133 | if MemProfile != "" { |
| 134 | f, err := os.Create(MemProfile) |
| 135 | if err != nil { |
| 136 | log.Fatal(err) |
| 137 | } |
| 138 | // NB: memprofile won't be written in case of error. |
| 139 | defer func() { |
| 140 | runtime.GC() // get up-to-date statistics |
| 141 | if err := pprof.WriteHeapProfile(f); err != nil { |
| 142 | log.Fatalf("Writing memory profile: %v", err) |
| 143 | } |
| 144 | f.Close() |
| 145 | }() |
| 146 | } |
| 147 | |
| 148 | // Load the packages. |
| 149 | if dbg('v') { |
| 150 | log.SetPrefix("") |
| 151 | log.SetFlags(log.Lmicroseconds) // display timing |
| 152 | log.Printf("load %s", args) |
| 153 | } |
| 154 | |
| 155 | // Optimization: if the selected analyzers don't produce/consume |
| 156 | // facts, we need source only for the initial packages. |
| 157 | allSyntax := needFacts(analyzers) |
| 158 | initial, err := load(args, allSyntax) |
| 159 | if err != nil { |
| 160 | log.Print(err) |
| 161 | exitAtLeast(1) |
| 162 | return |
| 163 | } |
| 164 | |
| 165 | // Print package and module errors regardless of RunDespiteErrors. |
| 166 | // Do not exit if there are errors, yet. |
| 167 | if n := packages.PrintErrors(initial); n > 0 { |
| 168 | exitAtLeast(1) |
| 169 | } |
| 170 | |
| 171 | var factLog io.Writer |
| 172 | if dbg('f') { |
| 173 | factLog = os.Stderr |
| 174 | } |
| 175 | |
| 176 | // Run the analysis. |
| 177 | opts := &checker.Options{ |
| 178 | SanityCheck: dbg('s'), |
| 179 | Sequential: dbg('p'), |
| 180 | FactLog: factLog, |
| 181 | } |
| 182 | if dbg('v') { |
| 183 | log.Printf("building graph of analysis passes") |
| 184 | } |
| 185 | graph, err := checker.Analyze(analyzers, initial, opts) |
| 186 | if err != nil { |
| 187 | log.Print(err) |
| 188 | exitAtLeast(1) |
| 189 | return |
| 190 | } |
| 191 | |
| 192 | // Don't print the diagnostics, |
| 193 | // but apply all fixes from the root actions. |
| 194 | if analysisflags.Fix { |
| 195 | fixActions := make([]driverutil.FixAction, len(graph.Roots)) |
| 196 | for i, act := range graph.Roots { |
| 197 | if pass := internal.ActionPass(act); pass != nil { |
| 198 | fixActions[i] = driverutil.FixAction{ |
| 199 | Name: act.String(), |
| 200 | Pkg: act.Package.Types, |
| 201 | Files: act.Package.Syntax, |
| 202 | FileSet: act.Package.Fset, |
| 203 | ReadFileFunc: pass.ReadFile, |
| 204 | Diagnostics: act.Diagnostics, |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | write := func(filename string, content []byte) error { |
| 209 | return os.WriteFile(filename, content, 0644) |
| 210 | } |
| 211 | if err := driverutil.ApplyFixes(fixActions, write, analysisflags.Diff, dbg('v')); err != nil { |
| 212 | // Fail when applying fixes failed. |
| 213 | log.Print(err) |
| 214 | exitAtLeast(1) |
| 215 | return |
| 216 | } |
| 217 | // Don't proceed to print text/JSON, |
| 218 | // and don't report an error |
| 219 | // just because there were diagnostics. |
| 220 | return |
| 221 | } |
| 222 | |
| 223 | // Print the results. If !RunDespiteErrors and there |
| 224 | // are errors in the packages, this will have 0 exit |
| 225 | // code. Otherwise, we prefer to return exit code |
| 226 | // indicating diagnostics. |
| 227 | exitAtLeast(printDiagnostics(graph)) |
| 228 | |
| 229 | return |
| 230 | } |
| 231 | |
| 232 | // printDiagnostics prints diagnostics in text or JSON form |
| 233 | // and returns the appropriate exit code. |
| 234 | func printDiagnostics(graph *checker.Graph) (exitcode int) { |
| 235 | // Keep consistent with analogous logic in |
| 236 | // processResults in ../../unitchecker/unitchecker.go. |
| 237 | |
| 238 | // Print the results. |
| 239 | // With -json, the exit code is always zero. |
| 240 | if analysisflags.JSON { |
| 241 | if err := graph.PrintJSON(os.Stdout); err != nil { |
| 242 | return 1 |
| 243 | } |
| 244 | } else { |
| 245 | if err := graph.PrintText(os.Stderr, analysisflags.Context); err != nil { |
| 246 | return 1 |
| 247 | } |
| 248 | |
| 249 | // Compute the exit code. |
| 250 | var numErrors, rootDiags int |
| 251 | for act := range graph.All() { |
| 252 | if act.Err != nil { |
| 253 | numErrors++ |
| 254 | } else if act.IsRoot { |
| 255 | rootDiags += len(act.Diagnostics) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | if numErrors > 0 { |
| 260 | exitcode = 1 // analysis failed, at least partially |
| 261 | } else if rootDiags > 0 { |
| 262 | exitcode = 3 // successfully produced diagnostics |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | // Print timing info. |
| 267 | if dbg('t') { |
| 268 | if !dbg('p') { |
| 269 | log.Println("Warning: times are mostly GC/scheduler noise; use -debug=tp to disable parallelism") |
| 270 | } |
| 271 | |
| 272 | var list []*checker.Action |
| 273 | var total time.Duration |
| 274 | for act := range graph.All() { |
| 275 | list = append(list, act) |
| 276 | total += act.Duration |
| 277 | } |
| 278 | |
| 279 | // Print actions accounting for 90% of the total. |
| 280 | sort.Slice(list, func(i, j int) bool { |
| 281 | return list[i].Duration > list[j].Duration |
| 282 | }) |
| 283 | var sum time.Duration |
| 284 | for _, act := range list { |
| 285 | fmt.Fprintf(os.Stderr, "%s\t%s\n", act.Duration, act) |
| 286 | sum += act.Duration |
| 287 | if sum >= total*9/10 { |
| 288 | break |
| 289 | } |
| 290 | } |
| 291 | if total > sum { |
| 292 | fmt.Fprintf(os.Stderr, "%s\tall others\n", total-sum) |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | return exitcode |
| 297 | } |
| 298 | |
| 299 | // load loads the initial packages. Returns only top-level loading |
| 300 | // errors. Does not consider errors in packages. |
| 301 | func load(patterns []string, allSyntax bool) ([]*packages.Package, error) { |
| 302 | mode := packages.LoadSyntax |
| 303 | if allSyntax { |
| 304 | mode = packages.LoadAllSyntax |
| 305 | } |
| 306 | mode |= packages.NeedModule |
| 307 | conf := packages.Config{ |
| 308 | Mode: mode, |
| 309 | // Ensure that child process inherits correct alias of PWD. |
| 310 | // (See discussion at Dir field of [exec.Command].) |
| 311 | // However, this currently breaks some tests. |
| 312 | // TODO(adonovan): Investigate. |
| 313 | // |
| 314 | // Dir: os.Getenv("PWD"), |
| 315 | Tests: IncludeTests, |
| 316 | } |
| 317 | initial, err := packages.Load(&conf, patterns...) |
| 318 | if err == nil && len(initial) == 0 { |
| 319 | err = fmt.Errorf("%s matched no packages", strings.Join(patterns, " ")) |
| 320 | } |
| 321 | return initial, err |
| 322 | } |
| 323 | |
| 324 | // needFacts reports whether any analysis required by the specified set |
| 325 | // needs facts. If so, we must load the entire program from source. |
| 326 | func needFacts(analyzers []*analysis.Analyzer) bool { |
| 327 | seen := make(map[*analysis.Analyzer]bool) |
| 328 | var q []*analysis.Analyzer // for BFS |
| 329 | q = append(q, analyzers...) |
| 330 | for len(q) > 0 { |
| 331 | a := q[0] |
| 332 | q = q[1:] |
| 333 | if !seen[a] { |
| 334 | seen[a] = true |
| 335 | if len(a.FactTypes) > 0 { |
| 336 | return true |
| 337 | } |
| 338 | q = append(q, a.Requires...) |
| 339 | } |
| 340 | } |
| 341 | return false |
| 342 | } |
| 343 | |
| 344 | func dbg(b byte) bool { return strings.IndexByte(Debug, b) >= 0 } |