Debian Codegraph @

tools/antithesis-go-toolexec/main.go

raw
1 // antithesis-go-toolexec instruments Go code for coverage and catalogs Antithesis assertions
2 // from inside the build as a `go build -toolexec` wrapper.
3 //
4 // Usage:
5 //
6 // go build -toolexec=antithesis-go-toolexec ./...
7 //
8 // or, so that no build command has to change:
9 //
10 // export GOFLAGS=-toolexec=antithesis-go-toolexec
11 //
12 // The go command runs this program in place of each toolchain program, passing
13 // the real program and its arguments. We pass almost everything through
14 // untouched; see compile.go for the three edits we make to a compile invocation.
15 package main
16
17 import (
18 "errors"
19 "fmt"
20 "os"
21 "os/exec"
22 "path/filepath"
23 "strings"
24
25 "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/common"
26 )
27
28 func main() { os.Exit(run()) }
29
30 // run does the work and returns an exit status, so that deferred cleanup runs.
31 func run() int {
32 if len(os.Args) < 2 {
33 fmt.Fprintln(os.Stderr, usage)
34 return 2
35 }
36 if os.Args[1] == "-h" || os.Args[1] == "-help" || os.Args[1] == "--help" {
37 fmt.Println(usage)
38 return 0
39 }
40
41 cfg, err := loadConfig()
42 if err != nil {
43 return errorf("%s", err)
44 }
45 // The shared instrumentor code logs at Normal, which prints at the default
46 // verbosity. Anything written to stderr while a compile action runs stops the
47 // go command from caching that action, so unless verbosity was actually asked
48 // for, sit below Normal and stay silent.
49 verbosity := cfg.Verbosity
50 if verbosity <= common.Normal {
51 verbosity = common.Normal - 1
52 }
53 common.NewLogWriter("", verbosity)
54
55 realTool, args := os.Args[1], os.Args[2:]
56 tool := toolName(realTool)
57
58 // The go command asks each tool to identify itself and folds the answer into
59 // the action cache key (cmd/go/internal/work/buildid.go). Appending to that
60 // line is what keeps instrumented objects in different cache entries from
61 // uninstrumented ones -- without it the build silently reuses stock objects.
62 if isVersionProbe(args) {
63 out, err := exec.Command(realTool, args...).Output()
64 if err != nil {
65 return exitStatus(err)
66 }
67 suffix, err := cfg.ToolIDSuffix()
68 if err != nil {
69 // Without a trustworthy identity the cache key would be wrong, and a
70 // wrong cache key is silent. Refuse instead.
71 return errorf("%s", err)
72 }
73 fmt.Printf("%s %s\n", strings.TrimSpace(string(out)), suffix)
74 return 0
75 }
76
77 switch tool {
78 case "compile":
79 if pkg, ok := selectedPackage(cfg, args); ok {
80 var cleanup func()
81 if args, cleanup, err = rewriteCompile(cfg, pkg, args); err != nil {
82 return errorf("instrumenting %s: %s", pkg.ImportPath, err)
83 }
84 // The generated files are needed only until the compiler has read
85 // them, and one build can compile thousands of packages.
86 defer cleanup()
87 }
88 case "link":
89 if args, err = prepareLink(cfg, args); err != nil {
90 return errorf("preparing link: %s", err)
91 }
92 }
93
94 cmd := exec.Command(realTool, args...)
95 cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
96 if err := cmd.Run(); err != nil {
97 return exitStatus(err)
98 }
99 return 0
100 }
101
102 // toolName reduces the program path the go command handed us to a bare tool
103 // name, so "/…/pkg/tool/linux_amd64/compile" becomes "compile". Anything we do
104 // not recognise (notably the C compiler during a cgo build, which is invoked as
105 // `clang -### -x c -c -`) falls through untouched.
106 func toolName(path string) string {
107 return strings.TrimSuffix(filepath.Base(path), ".exe")
108 }
109
110 // isVersionProbe reports whether this invocation is the go command asking the
111 // tool for its build ID rather than asking it to do work. The Go tools use
112 // -V=full; the C compiler is probed with -### instead, and that output is hashed
113 // rather than parsed, so we leave it alone.
114 func isVersionProbe(args []string) bool {
115 return len(args) > 0 && args[len(args)-1] == "-V=full"
116 }
117
118 // exitStatus reports the wrapped tool's own status. Collapsing every failure to 1
119 // would make the go command misreport which step failed and why.
120 func exitStatus(err error) int {
121 var exitErr *exec.ExitError
122 if errors.As(err, &exitErr) {
123 return exitErr.ExitCode()
124 }
125 return errorf("%s", err)
126 }
127
128 // errorf reports a failure of the wrapper itself. It goes to stderr rather than
129 // through common.Logger, because the shared logger prefixes its own file and line
130 // -- misleading in a build log -- and because these must be seen at any verbosity.
131 func errorf(format string, args ...any) int {
132 fmt.Fprintf(os.Stderr, toolName(os.Args[0])+": "+format+"\n", args...)
133 return 1
134 }
135
136 // progressf reports what the wrapper did, on the same terms as errorf.
137 func progressf(format string, args ...any) {
138 fmt.Fprintf(os.Stderr, toolName(os.Args[0])+": "+format+"\n", args...)
139 }
140
141 const usage = `antithesis-go-toolexec is a "go build -toolexec" wrapper that adds
142 Antithesis coverage instrumentation during the build.
143
144 go build -toolexec=antithesis-go-toolexec ./...
145 GOFLAGS=-toolexec=antithesis-go-toolexec go build ./...
146
147 It is configured by environment variables, because the go command controls its
148 argument list:
149
150 ANTITHESIS_INSTRUMENT comma-separated import path prefixes to instrument.
151 Defaults to the main module of the build.
152 ANTITHESIS_SYMBOLS_DIR where symbol tables are collected. Default /symbols.
153 ANTITHESIS_EXCLUDE path to an exclusions file, as accepted by
154 antithesis-go-instrumentor -exclude.
155 ANTITHESIS_SYMBOL_PREFIX prefix for symbol table file names.
156 ANTITHESIS_SDK_MODULE_DIR directory of an antithesis-sdk-go checkout, used to
157 supply the SDK when the module being built does not
158 depend on it.
159 ANTITHESIS_SKIP_TEST_FILES set to 1 to leave _test.go files uninstrumented.
160 ANTITHESIS_SKIP_CATALOG set to 1 to skip assertion cataloguing.
161 ANTITHESIS_SKIP_COVERAGE set to 1 to skip coverage instrumentation. With
162 cataloguing left on, this is the equivalent of
163 antithesis-go-instrumentor -assert_only.
164 ANTITHESIS_VERBOSE 0-3; logs to stderr during the build. Note that a
165 compile that writes to stderr is not cached, so
166 this effectively disables incremental builds.
167
168 Assertion catalogs are generated automatically, one per instrumented package, so
169 no separate antithesis-go-instrumentor pass is required.`