Debian Codegraph @

tools/antithesis-go-toolexec/compile.go

raw
1 package main
2
3 import (
4 "fmt"
5 "go/parser"
6 "go/token"
7 "os"
8 "path/filepath"
9
10 "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/common"
11 "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/scanners/coverage/instrumentor"
12 "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/scanners/coverage/symboltable"
13 )
14
15 // registrationFile is the name given to the file we synthesise into the package
16 // being compiled. It never reaches the user's tree.
17 const registrationFile = "antithesis_module.go"
18
19 // rewriteCompile applies the enabled features to a compile invocation. Coverage
20 // instrumentation and assertion cataloguing are independent: either can be turned
21 // off without affecting the other.
22 //
23 // At most three edits are made, and every other argument -- -o, -p, -lang,
24 // -buildid, -trimpath, -complete, -embedcfg, -pack -- is passed through:
25 //
26 // 1. each source file path is replaced with an instrumented copy;
27 // 2. generated files are appended (a coverage registration, a catalog); and
28 // 3. -importcfg is replaced with a copy that can resolve the SDK.
29 //
30 // Nothing is written into the user's source tree, and nothing outlives the build
31 // except the package's symbol table.
32 //
33 // The returned cleanup function removes the generated files. It must not run
34 // until the compiler has finished reading them.
35 func rewriteCompile(cfg *Config, pkg *Package, args []string) ([]string, func(), error) {
36 work, err := os.MkdirTemp("", "antithesis-instr-")
37 if err != nil {
38 return nil, nil, err
39 }
40 cleanup := func() { os.RemoveAll(work) }
41 // Every failure below must release the work directory: the caller only gets
42 // the cleanup function on success.
43 fail := func(err error) ([]string, func(), error) {
44 cleanup()
45 return nil, nil, err
46 }
47
48 paths := make([]string, 0, len(pkg.GoFiles))
49 for _, file := range pkg.GoFiles {
50 paths = append(paths, file.Path)
51 }
52
53 // Cataloguing reads the original sources and the compiler's own importcfg, so
54 // it has to run before coverage rewrites either.
55 if cfg.Catalog {
56 catalog, err := catalogPackage(cfg, pkg, args, paths, work)
57 if err != nil {
58 return fail(err)
59 }
60 if catalog != "" {
61 args = append(args, catalog)
62 }
63 }
64
65 if cfg.Coverage {
66 if args, err = instrumentCoverage(cfg, pkg, args, paths, work); err != nil {
67 return fail(err)
68 }
69 }
70 return args, cleanup, nil
71 }
72
73 // instrumentCoverage adds coverage edges to the package being compiled: it
74 // rewrites the sources, writes the package's symbol table, and injects the
75 // registration that binds the two at run time.
76 func instrumentCoverage(cfg *Config, pkg *Package, args []string, paths []string, work string) ([]string, error) {
77 // The symbol table's name is derived from this package's own sources, so it is
78 // stable across builds and unaffected by changes elsewhere in the tree.
79 digest := common.HashFileContent(paths)
80 symbolBase := cfg.SymbolPrefix + common.SYMBOLS_FILE_HASH_PREFIX + "-" + digest
81 symbolName := symbolBase + common.SYMBOLS_FILE_SUFFIX
82
83 shardDir, err := shardDirectory()
84 if err != nil {
85 return nil, err
86 }
87 symbols, err := symboltable.CreateSymbolTableFile(filepath.Join(shardDir, symbolName), symbolBase)
88 if err != nil {
89 return nil, fmt.Errorf("creating symbol table: %w", err)
90 }
91
92 // basePath controls only the path in the //line directive the instrumentor
93 // emits; symbol table rows always record the absolute path. Pass the module
94 // root, as the whole-tree instrumentor does, so the two front ends agree on
95 // what //line says.
96 edges := instrumentor.CreateSourceEditingInstrumentor(moduleRoot(filepath.Dir(paths[0])), "", symbols)
97
98 // The call sites and the registration below must agree on the identifier, and
99 // it has to be one this package does not already use; see callback.go.
100 callbackName, err := resolveCallbackName(paths)
101 if err != nil {
102 return nil, err
103 }
104 if callbackName != instrumentor.InstrumentationPackageAlias {
105 common.Logger.Printf(common.Normal, "%s already declares %s; using %s instead",
106 pkg.ImportPath, instrumentor.InstrumentationPackageAlias, callbackName)
107 }
108 edges.SetCallbackName(callbackName)
109
110 instrumented := 0
111 for _, file := range pkg.GoFiles {
112 source, err := edges.Instrument(file.Path)
113 if err != nil {
114 // A file we cannot rewrite is still a file the package needs, so leave
115 // the original in place and carry on with the rest.
116 common.Logger.Printf(common.Normal, "Error: %s not instrumented (%s); using original", file.Path, err)
117 continue
118 }
119 if source == "" {
120 // The instrumentor declined this file: no edges, or it exports functions
121 // or declares linknames. Its original path stays in the argument list.
122 continue
123 }
124 rewritten := filepath.Join(work, fmt.Sprintf("%d_%s", file.Index, filepath.Base(file.Path)))
125 if err := common.WriteTextFile(source, rewritten); err != nil {
126 return nil, fmt.Errorf("writing %s: %w", rewritten, err)
127 }
128 args[file.Index] = rewritten // edit 1
129 instrumented++
130 }
131
132 edgeCount := edges.Edges()
133 if err := symbols.Close(); err != nil {
134 return nil, fmt.Errorf("closing symbol table: %w", err)
135 }
136 if edgeCount == 0 {
137 // Nothing was instrumented after all; drop the empty symbol table rather
138 // than leaving a header-only file to be collected into the image.
139 os.Remove(filepath.Join(shardDir, symbolName))
140 return args, nil
141 }
142
143 packageName, err := packageClause(pkg.GoFiles[0].Path)
144 if err != nil {
145 return nil, err
146 }
147 registration := filepath.Join(work, registrationFile)
148 if err := common.WriteTextFile(registrationSource(packageName, callbackName, symbolName, edgeCount), registration); err != nil {
149 return nil, fmt.Errorf("writing %s: %w", registration, err)
150 }
151 args = append(args, registration) // edit 2
152
153 if err := recordShard(shardDir, pkg.ImportPath, symbolName); err != nil {
154 return nil, err
155 }
156
157 // edit 3
158 if args, err = ensureSDKImportable(cfg, args, pkg.ImportCfg); err != nil {
159 return nil, err
160 }
161
162 common.Logger.Printf(common.Info, "Instrumented %s: %d %s in %d %s -> %s",
163 pkg.ImportPath, edgeCount, common.Pluralize(edgeCount, "edge"),
164 instrumented, common.Pluralize(instrumented, "file"), symbolName)
165 return args, nil
166 }
167
168 // registrationSource is the file we add to the package being compiled.
169 //
170 // The variable is named for the identifier the instrumentor's call sites use, so
171 // `<callbackName>.Notify(n)` resolves to a method on this handle exactly as it
172 // would have resolved to a function in a notifier package.
173 //
174 // Declaring it as a package-level variable orders initialization correctly.
175 // Go's dependency analysis ensures that the SDK and this variable are initialized
176 // before any variable in the package whose initializer calls instrumented code.
177 func registrationSource(packageName, callbackName, symbolName string, edgeCount int) string {
178 return fmt.Sprintf(`// Code generated by antithesis-go-toolexec. DO NOT EDIT.
179
180 package %s
181
182 import %s %q
183
184 var %s = %s.RegisterModule(%q, %d)
185 `,
186 packageName,
187 sdkImportAlias, sdkInstrumentationPackage,
188 callbackName, sdkImportAlias,
189 symbolName, edgeCount)
190 }
191
192 // sdkImportAlias keeps the SDK import from colliding with anything the package
193 // already imports under its own name.
194 const sdkImportAlias = "__antithesis_sdk__"
195
196 // packageClause reads just the package name, which the compile invocation does
197 // not tell us: -p carries the import path, and the two differ often enough
198 // (external test packages, packages named differently from their directory) that
199 // it cannot be guessed.
200 func packageClause(path string) (string, error) {
201 file, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.PackageClauseOnly)
202 if err != nil {
203 return "", fmt.Errorf("reading package clause from %s: %w", path, err)
204 }
205 return file.Name.Name, nil
206 }