Debian Codegraph @

tools/antithesis-go-toolexec/sdk.go

raw
1 package main
2
3 import (
4 "bufio"
5 "errors"
6 "fmt"
7 "os"
8 "os/exec"
9 "slices"
10 "strings"
11
12 "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/common"
13 )
14
15 // packageEntry is one resolvable package: an import path and the compiled archive
16 // implementing it.
17 type packageEntry struct {
18 ImportPath string
19 ArchiveFile string
20 }
21
22 // recursionGuard stops the nested `go list` below from re-entering this wrapper.
23 // Without it, resolving the SDK would instrument the SDK, which would need the
24 // SDK resolved, and so on.
25 const recursionGuard = "ANTITHESIS_TOOLEXEC_RESOLVING"
26
27 // ensureSDKImportable makes the SDK's instrumentation package resolvable to the
28 // compile invocation, patching -importcfg only if it is not already listed.
29 func ensureSDKImportable(cfg *Config, args []string, importCfgIndex int) ([]string, error) {
30 existing, err := readImportCfg(args[importCfgIndex])
31 if err != nil {
32 return nil, err
33 }
34 if existing.Has(sdkInstrumentationPackage) {
35 return args, nil
36 }
37
38 entries, err := resolveSDK(cfg)
39 if err != nil {
40 return nil, err
41 }
42 return patchImportCfg(args, importCfgIndex, entries)
43 }
44
45 // prepareLink gives the linker the same entries. The linker resolves every import
46 // path in the binary, including ones only reachable through our generated
47 // registration files, and it runs on any build that has to produce a binary --
48 // even one where every package was a cache hit and this wrapper never instrumented
49 // anything.
50 func prepareLink(cfg *Config, args []string) ([]string, error) {
51 importCfgIndex := -1
52 for i, arg := range args {
53 if arg == "-importcfg" && i+1 < len(args) {
54 importCfgIndex = i + 1
55 }
56 }
57 if importCfgIndex < 0 {
58 return args, nil
59 }
60
61 // With coverage off there are no symbol tables to collect and nothing that
62 // references the instrumentation package, so the link needs no help. Catalogs
63 // call into the assert package, which any package containing an assertion
64 // already imports.
65 if !cfg.Coverage {
66 return args, nil
67 }
68
69 if err := collectShards(cfg); err != nil {
70 return nil, err
71 }
72
73 existing, err := readImportCfg(args[importCfgIndex])
74 if err != nil {
75 return nil, err
76 }
77 if existing.Has(sdkInstrumentationPackage) {
78 return args, nil
79 }
80 // Nothing in this binary references the SDK through the go command's own
81 // dependency graph. If we instrumented nothing, that is simply an
82 // uninstrumented build and there is nothing to add.
83 if !existing.hasAnyOf(instrumentedImportPaths(cfg)) {
84 return args, nil
85 }
86
87 entries, err := resolveSDK(cfg)
88 if err != nil {
89 return nil, err
90 }
91 return patchImportCfg(args, importCfgIndex, entries)
92 }
93
94 // hasAnyOf reports whether the importcfg lists any of these packages.
95 func (c *importCfg) hasAnyOf(importPaths []string) bool {
96 return slices.ContainsFunc(importPaths, c.Has)
97 }
98
99 // resolveSDK returns the SDK's instrumentation package and everything it needs,
100 // as packagefile entries.
101 //
102 // The archives come from `go list -deps -export`, which builds each package and
103 // reports where the build cache put it. Two sources are possible:
104 //
105 // - the module being built, when it already requires the SDK; or
106 // - a separate SDK checkout named by ANTITHESIS_SDK_MODULE_DIR, which lets a
107 // module with no Antithesis dependency at all be instrumented without editing
108 // its go.mod.
109 //
110 // The second case has a caveat worth understanding. Those archives are built
111 // outside the main build, so any setting affecting object compatibility --
112 // GOARCH, -race, the toolchain, the active GOEXPERIMENT set -- must match. We
113 // inherit the environment, which covers most of it, and a mismatch fails loudly
114 // at link time with a fingerprint error rather than producing a bad binary.
115 func resolveSDK(cfg *Config) ([]packageEntry, error) {
116 if os.Getenv(recursionGuard) != "" {
117 return nil, fmt.Errorf("refusing to resolve %s recursively", sdkInstrumentationPackage)
118 }
119
120 command := exec.Command("go", "list", "-deps", "-export", "-f",
121 "{{if .Export}}{{.ImportPath}}\t{{.Export}}{{end}}", sdkInstrumentationPackage)
122 command.Env = append(os.Environ(),
123 recursionGuard+"=1",
124 // Our own -toolexec must not apply to this build.
125 "GOFLAGS="+withoutToolexec(os.Getenv("GOFLAGS")),
126 )
127 if cfg.SDKModuleDir != "" {
128 command.Dir = cfg.SDKModuleDir
129 }
130
131 output, err := command.Output()
132 if err != nil {
133 return nil, sdkResolutionError(cfg, err)
134 }
135
136 var entries []packageEntry
137 scanner := bufio.NewScanner(strings.NewReader(string(output)))
138 for scanner.Scan() {
139 importPath, archive, found := strings.Cut(strings.TrimSpace(scanner.Text()), "\t")
140 if !found || importPath == "" || archive == "" {
141 continue
142 }
143 entries = append(entries, packageEntry{ImportPath: importPath, ArchiveFile: archive})
144 }
145 if err := scanner.Err(); err != nil {
146 return nil, err
147 }
148 if len(entries) == 0 {
149 return nil, fmt.Errorf("resolved no archives for %s", sdkInstrumentationPackage)
150 }
151 common.Logger.Printf(common.Debug, "Resolved %d SDK %s", len(entries), common.Pluralize(len(entries), "package"))
152 return entries, nil
153 }
154
155 func sdkResolutionError(cfg *Config, err error) error {
156 var stderr string
157 var exitErr *exec.ExitError
158 if errors.As(err, &exitErr) {
159 stderr = strings.TrimSpace(string(exitErr.Stderr))
160 }
161 if cfg.SDKModuleDir != "" {
162 return fmt.Errorf("could not build %s from ANTITHESIS_SDK_MODULE_DIR=%s: %w\n%s",
163 sdkInstrumentationPackage, cfg.SDKModuleDir, err, stderr)
164 }
165 return fmt.Errorf(`could not resolve %s: %w
166 %s
167 The module being built does not require the Antithesis SDK. Either add it:
168
169 go get %s
170
171 or point the wrapper at an SDK checkout:
172
173 export ANTITHESIS_SDK_MODULE_DIR=/path/to/antithesis-sdk-go`,
174 sdkInstrumentationPackage, err, stderr, common.ANTITHESIS_SDK_MODULE)
175 }
176
177 // withoutToolexec strips -toolexec from a GOFLAGS value so a nested go command
178 // does not re-enter this wrapper. Setting GOFLAGS explicitly is not enough on its
179 // own, because the value we inherit may well contain it.
180 func withoutToolexec(goflags string) string {
181 kept := make([]string, 0, 4)
182 for _, flag := range strings.Fields(goflags) {
183 if flag == "-toolexec" || strings.HasPrefix(flag, "-toolexec=") {
184 continue
185 }
186 kept = append(kept, flag)
187 }
188 return strings.Join(kept, " ")
189 }