Debian Codegraph @

tools/antithesis-go-instrumentor/scanners/coverage/instrumentor/instrumentor.go

raw
1 package instrumentor
2
3 import (
4 "fmt"
5 "go/ast"
6 "go/format"
7 "go/parser"
8 "go/token"
9 "os"
10 "regexp"
11 "sort"
12 "strconv"
13 "strings"
14
15 "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/common"
16 "github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/scanners/coverage/symboltable"
17 "golang.org/x/tools/go/ast/astutil"
18 )
19
20 // InstrumentationPackageAlias will be used to prevent any collisions
21 // between possible other packages named "instrumentation". Underscore
22 // characters are considered bad style, which is why I'm using them:
23 // a collision is less likely.
24 const InstrumentationPackageAlias = "__antithesis_instrumentation__"
25
26 // AntithesisCallbackFunction is the name of the instrumentor-generated
27 // callback function that delegates to wrapper.Notify() with the correct
28 // arguments. Multiple definitions of this function will lead to a (desirable)
29 // compile-time error.
30 const AntithesisCallbackFunction = "Notify"
31
32 var compilationRelevantCommentRegex, _ = regexp.Compile(`(?sm)^\s*(go:|\+build)`)
33
34 // IsFunctionExported checks the comments preceding a function declaration
35 // for all known formats of export directive.
36 func IsFunctionExported(group *ast.CommentGroup, name string) bool {
37 if group == nil {
38 return false
39 }
40 // No characters may precede or follow the directive.
41 exportDeclaration := "//export " + name
42 for _, comment := range group.List {
43 if comment.Text == exportDeclaration {
44 return true
45 }
46 }
47 return false
48 }
49
50 // ExportsFunctions warns the caller that the the .go file includes
51 // export directives in comments, which AST-rewriting may damage.
52 func ExportsFunctions(file *ast.File, fset *token.FileSet) bool {
53 foundExport := false
54 finder := func(cursor *astutil.Cursor) bool {
55 n := cursor.Node()
56 switch n := n.(type) {
57 case *ast.FuncDecl:
58 if IsFunctionExported(n.Doc, n.Name.Name) {
59 foundExport = true
60 // Stop recursion.
61 return false
62 }
63 }
64 // By default, continue recursing.
65 return true
66 }
67
68 astutil.Apply(file, finder, nil)
69 return foundExport
70 }
71
72 // HasLinkname lets us exclude .go files that interact with other
73 // languages.
74 func HasLinkname(file *ast.File, fset *token.FileSet) bool {
75 foundLinkname := false
76 finder := func(cursor *astutil.Cursor) bool {
77 n := cursor.Node()
78 switch n := n.(type) {
79 case *ast.FuncDecl:
80 if n.Doc != nil {
81 for _, comment := range n.Doc.List {
82 if strings.Contains(comment.Text, "go:linkname") {
83 foundLinkname = true
84 return false
85 }
86 }
87 }
88 }
89 return true
90 }
91
92 astutil.Apply(file, finder, nil)
93 return foundLinkname
94 }
95
96 // Check to see if this particular node represents a something which requires
97 // runtime-generated file names. If this is the case, we can't instrument this
98 // because we have to statically set the path in the comments, and there's no way
99 // to simultaneously:
100 //
101 // 1) Use //line directives to set the line numbers; and
102 // 2) Let the runtime set the absolute/relative file path.
103 //
104 // The primary offenders are the runtime.(Caller|Callers) functions. See
105 // https://github.com/golang/go/issues/26207
106 // for more details.
107 func RequiresFileNameOrLineNumber(n ast.Node, fset *token.FileSet) bool {
108 if n == nil {
109 return false
110 }
111 call, callOk := n.(*ast.CallExpr)
112 if !callOk {
113 return false
114 }
115 if call.Fun == nil {
116 return false
117 }
118 sel, selOk := call.Fun.(*ast.SelectorExpr)
119 if !selOk {
120 return false
121 }
122 if sel.X == nil || sel.Sel == nil {
123 return false
124 }
125 x, xOk := sel.X.(*ast.Ident)
126 if !xOk {
127 return false
128 }
129 return x.Name == "runtime" && strings.Contains(sel.Sel.Name, "Caller")
130 }
131
132 func IsLineDirectiveCompatible(file *ast.File, fset *token.FileSet) bool {
133 requiresFileNameOrLineNumber := false
134 finder := func(cursor *astutil.Cursor) bool {
135 n := cursor.Node()
136 if RequiresFileNameOrLineNumber(n, fset) {
137 requiresFileNameOrLineNumber = true
138 return false
139 }
140 return true
141 }
142
143 astutil.Apply(file, finder, nil)
144 return !requiresFileNameOrLineNumber
145 }
146
147 // The parser will strip compiler directives from CommentGroup.Text(),
148 // so we need a separate loop to look for them.
149 func commentContainsDirective(group *ast.CommentGroup) bool {
150 for _, comment := range group.List {
151 c := comment.Text
152 //-style comment (no newline at the end)
153 if c[1] == '/' {
154 c = c[2:]
155 if isDirective(c) {
156 return true
157 }
158 }
159 }
160 // TODO It's possible that the above code suffices, but we can't know
161 // that without more investigation.
162 return compilationRelevantCommentRegex.MatchString(group.Text())
163 }
164
165 func runeInclusive(r, from, to rune) bool {
166 if r < from || r > to {
167 return false
168 }
169 return true
170 }
171
172 // From go/ast/ast.go
173 func isDirective(c string) bool {
174 // TODO: Not sure if line directives may affect instrumentation so excluding
175 // such comments for now
176 if strings.HasPrefix(c, "line ") {
177 return false
178 }
179
180 // "//line " is a line directive.
181 // "//extern " is for gccgo.
182 // "//export " is for cgo.
183 // (The // has been removed.)
184 if strings.HasPrefix(c, "line ") || strings.HasPrefix(c, "extern ") || strings.HasPrefix(c, "export ") {
185 return true
186 }
187
188 // "//[a-z0-9]+:[a-z0-9]"
189 // (The // has been removed.)
190 colon := strings.Index(c, ":")
191 if colon <= 0 || colon+1 >= len(c) {
192 return false
193 }
194 for i := 0; i <= colon+1; i++ {
195 if i == colon {
196 continue
197 }
198 b := c[i]
199
200 isValidRune := runeInclusive(rune(b), 'a', 'z') || runeInclusive(rune(b), '0', '9')
201 if !isValidRune {
202 return false
203 }
204 }
205 return true
206 }
207
208 // Create a //line directive that the caller can add to the comments for the file/maybe associated with the Node.
209 // Note that we can insert these even between go:embed directives and the variables into which Go will embed
210 // the resource: https://pkg.go.dev/embed#hdr-Directives
211 // "Only blank lines and ‘//’ line comments are permitted between the directive and the declaration."
212 func (instrumentor *Instrumentor) createLineDirective(lineNumber int, node *ast.Node) *ast.CommentGroup {
213 file := instrumentor.fset.File((*node).Pos())
214 p := instrumentor.fset.Position((*node).Pos())
215 currLine := p.Line
216 if currLine == 1 {
217 common.Logger.Printf(common.Normal, "Skipping inserting line position comment at very start of file")
218 return nil
219 }
220 lineStartPos := file.LineStart(p.Line)
221 common.Logger.Printf(common.Debug, "Creating comment for node @ %v start of line %d at %v", (*node).Pos(), p.Line, lineStartPos)
222 if (*node).Pos() == lineStartPos {
223 // This node is actually at the start of the line, so move the position back one to make sure there's no conflict.
224 // Also, set the original lineStartPos to true in the map just to make sure we don't have another item on the same
225 // line just re-create the problem.
226 instrumentor.posLines[lineStartPos] = true
227 lineStartPos--
228 }
229 if _, ok := instrumentor.posLines[lineStartPos]; ok {
230 // If we've already dropped a //line directive at this position in the file, don't create another one.
231 return nil
232 }
233 // Tag that we've created a //line directive for this spot in the file.
234 instrumentor.posLines[lineStartPos] = true
235 newComment := ast.Comment{Text: fmt.Sprintf("\n//line %s:%d", instrumentor.shortName, int(lineNumber)), Slash: lineStartPos}
236 commentGroup := ast.CommentGroup{List: []*ast.Comment{&newComment}}
237 return &commentGroup
238 }
239
240 // TrimComments uses the CommentMap structure to discard
241 // all comments not relevant to compilation.
242 func (instrumentor *Instrumentor) TrimComments(path string, file *ast.File) {
243 var commentGroups []*ast.CommentGroup
244 commentMap := ast.NewCommentMap(instrumentor.fset, file, file.Comments)
245 // We can't iterate over this hash map, because we need to
246 // encounter the comments in file order. So we'll walk the
247 // AST once.
248 stripper := func(cursor *astutil.Cursor) bool {
249 node := cursor.Node()
250 groups := commentMap[node]
251
252 switch n := node.(type) {
253 // Node types with no comments can be skipped.
254 // Only a few node types may retain their comments,
255 // in case they have go: or CGO directives.
256 case *ast.AssignStmt:
257 case *ast.BasicLit:
258 case *ast.Comment:
259 case *ast.CommentGroup:
260 case *ast.DeclStmt:
261 case *ast.Field:
262 n.Doc = nil
263 n.Comment = nil
264 case *ast.ExprStmt:
265 case *ast.File:
266 // This applies to +build directives.
267 // See https://golang.org/cmd/go/#hdr-Build_constraints
268 // Package documentation appears in the Doc field *and*
269 // in the Comments field.
270 for _, group := range groups {
271 if commentContainsDirective(group) {
272 commentGroups = append(commentGroups, group)
273 }
274 }
275 case *ast.ForStmt:
276 case *ast.FuncDecl:
277 text := n.Doc.Text()
278 if strings.Contains(text, "go:") {
279 p := instrumentor.fset.Position(n.Pos())
280 common.Logger.Printf(common.Normal, "Warning: Function %s, file %s, line %d uses a go: directive. This file may have to be excluded from instrumentation.", n.Name.Name, path, p.Line)
281 }
282 n.Doc = nil
283 case *ast.GenDecl:
284 if n.Tok == token.IMPORT && n.Doc != nil && len(n.Specs) == 1 {
285 // import "C" will have len(Specs) == 1
286 spec := n.Specs[0].(*ast.ImportSpec)
287 if spec.Path.Value == "\"C\"" {
288 p := instrumentor.fset.Position(spec.Pos())
289 common.Logger.Printf(common.Normal, "Warning: File %s, line %d imports a C declaration. This file may have to be excluded from instrumentation.", path, p.Line)
290 commentGroups = append(commentGroups, n.Doc)
291 }
292 } else {
293 n.Doc = nil
294 // This code exists for the sake of go:embed.
295 for _, group := range groups {
296 if commentContainsDirective(group) {
297 commentGroups = append(commentGroups, group)
298 }
299 }
300 }
301 case *ast.Ident:
302 case *ast.IfStmt:
303 case *ast.ImportSpec:
304 n.Doc = nil
305 n.Comment = nil
306 case *ast.LabeledStmt:
307 case *ast.RangeStmt:
308 case *ast.ReturnStmt:
309 case *ast.ValueSpec:
310 // This code exists for the sake of go:embed.
311 for _, group := range groups {
312 if commentContainsDirective(group) {
313 commentGroups = append(commentGroups, group)
314 }
315 }
316 default:
317 common.Logger.Printf(common.Debug, "No comment revision for AST node of type %T\n", node)
318 }
319 return true
320 }
321 // We don't need to output; we simply mutated the input AST's comments.
322 astutil.Apply(file, stripper, nil)
323 file.Comments = commentGroups
324 }
325
326 type functionLiteralFinder token.Pos
327
328 func (f *functionLiteralFinder) Visit(node ast.Node) (w ast.Visitor) {
329 if f.found() {
330 return nil // Prune search.
331 }
332 switch n := node.(type) {
333 case *ast.FuncLit:
334 *f = functionLiteralFinder(n.Body.Lbrace)
335 return nil // Prune search.
336 }
337 return f
338 }
339
340 func (f *functionLiteralFinder) found() bool {
341 return token.Pos(*f) != token.NoPos
342 }
343
344 func hasFuncLiteral(n ast.Node) (bool, token.Pos) {
345 if n == nil {
346 return false, 0
347 }
348 var literal functionLiteralFinder
349 ast.Walk(&literal, n)
350 return literal.found(), token.Pos(literal)
351 }
352
353 // Instrumentor *is* the Antithesis Go source-code instrumentor.
354 type Instrumentor struct {
355 nodeLines map[string]int
356 posLines map[token.Pos]bool
357 fset *token.FileSet
358 symbolTable *symboltable.SymbolTable
359 typeCounts map[string]int
360 fullName string
361 pkg string
362 shortName string
363 basePath string
364 shimPkg string
365 funcStack Stack
366 currPos []string
367 comments []*ast.CommentGroup
368 nodeStack Stack
369 CurrentEdge int
370 addLines bool
371 }
372
373 // CreateInstrumentor is the factory method.
374 func CreateInstrumentor(basePath string, shimPkg string, table *symboltable.SymbolTable) *Instrumentor {
375 if len(basePath) > 0 {
376 basePath = basePath + "/"
377 }
378 result := &Instrumentor{
379 basePath: basePath,
380 fset: token.NewFileSet(),
381 shimPkg: shimPkg,
382 symbolTable: table,
383 typeCounts: map[string]int{},
384 nodeLines: map[string]int{},
385 currPos: make([]string, 0),
386 posLines: map[token.Pos]bool{},
387 }
388 return result
389 }
390
391 // TODO: (justin.moore) See if we can get away with just re-parsing the file in-memory.
392 func (instrumentor *Instrumentor) writeSource(source, path string) error {
393 // Any errors here are fatal anyway, so I'm not checking.
394 f, e := os.Create(path)
395 if e != nil {
396 common.Logger.Printf(common.Normal, "Warning: Could not create %s", path)
397 return e
398 }
399 defer f.Close()
400 _, e = f.WriteString(source)
401 if e != nil {
402 common.Logger.Printf(common.Normal, "Warning: Could not write instrumented source to %s", path)
403 return e
404 }
405 common.Logger.Printf(common.Info, "Wrote instrumented output to %s", path)
406 return nil
407 }
408
409 // Instrument inserts calls to the Golang bridge to the Antithesis fuzzer.
410 // Errors should be logged, but are generally not fatal, since the input
411 // file can simply be copied to the output uninstrumented. If a file contains
412 // no executable code (i.e. contains only variable declarations, exports,
413 // or imports, an empty string is returned, so that the caller can simply
414 // copy the input file.
415 // TODO Return a * to a string, rather that returning the empty string to
416 // signal "I didn't instrument this input."
417 func (instrumentor *Instrumentor) Instrument(path string) (string, error) {
418 var bytes []byte
419 var e error
420 var f *ast.File
421 if bytes, e = os.ReadFile(path); e != nil {
422 return "", e
423 }
424
425 instrumentor.fullName = path
426 instrumentor.shortName = strings.TrimPrefix(path, instrumentor.basePath)
427 startingEdge := instrumentor.CurrentEdge
428
429 sourceCode := string(bytes)
430 if f, e = parser.ParseFile(instrumentor.fset, path, sourceCode, parser.ParseComments); e != nil {
431 return "", e
432 }
433
434 if ExportsFunctions(f, instrumentor.fset) {
435 common.Logger.Printf(common.Normal, "File %s exports functions, and will not be instrumented", path)
436 return "", nil
437 }
438
439 if HasLinkname(f, instrumentor.fset) {
440 common.Logger.Printf(common.Normal, "File %s exports linknames, and will not be instrumented", path)
441 return "", nil
442 }
443
444 instrumentor.TrimComments(path, f)
445
446 // The first pass over the code. We're not adding lines, we're inserting the instrumentation callbacks and
447 // taking note of where the various ast.Node objects are in the file.
448 instrumentor.addLines = false
449 instrumentor.comments = f.Comments
450 instrumentor.resetTypeCounts(true)
451 ast.Walk(instrumentor, f)
452 f.Comments = instrumentor.comments
453
454 if instrumentor.CurrentEdge == startingEdge {
455 common.Logger.Printf(common.Info, "File %s has no code to be instrumented, and will simply be copied", path)
456 return "", nil
457 }
458
459 // If there's something in here which requires either file names or line directives to be set
460 // at runtime (or otherwise is incompatible with static file/line directives), instrument but
461 // do not add line annotations.
462 if !IsLineDirectiveCompatible(f, instrumentor.fset) {
463 common.Logger.Printf(common.Normal, "File %s has functions which are incompatible with //line directives. Will be instrumented but not //line-annotated.", path)
464 // Note that we actually insert the instrumentation callback here.
465 if sourceCode, e = instrumentor.formatInstrumentedAst(path, f, true); e != nil {
466 return "", e
467 }
468 return sourceCode, nil
469 }
470
471 // Write the new AST out to a temp file on disk. This means that when we re-parse the file, it will
472 // look like a completely new file and we don't have to worry about any state carrying through from
473 // one parse to another. However, do not add in the import shim (the final 'false' parameter).
474 iPath := path + ".instrumented-only.go"
475 if sourceCode, e = instrumentor.formatInstrumentedAst(iPath, f, false); e != nil {
476 return "", e
477 }
478 instrumentor.writeSource(sourceCode, iPath)
479 if f, e = parser.ParseFile(instrumentor.fset, iPath, sourceCode, parser.ParseComments); e != nil {
480 os.Remove(iPath)
481 return "", e
482 }
483
484 // The second pass through the file. Add in the line directives. Reset the type counts, since we've
485 // cached the mapping of node identifiers to the line on which they were originally placed.
486 instrumentor.addLines = true
487 instrumentor.comments = f.Comments
488 instrumentor.resetTypeCounts(false)
489 ast.Walk(instrumentor, f)
490 sortComments(instrumentor.comments)
491 f.Comments = instrumentor.comments
492
493 // Create a string version of the final AST, and add in the shim (the final 'true' param).
494 if sourceCode, e := instrumentor.formatInstrumentedAst(path, f, true); e == nil {
495 os.Remove(iPath)
496 return sourceCode, nil
497 }
498 // TODO What are we doing with the error value above?
499 os.Remove(iPath)
500 return "", nil
501 }
502
503 func (instrumentor *Instrumentor) resetTypeCounts(full bool) {
504 instrumentor.typeCounts = map[string]int{}
505 instrumentor.currPos = make([]string, 0)
506 if full {
507 // Clear out any state from any previous files.
508 instrumentor.nodeLines = map[string]int{}
509 }
510 }
511
512 func (instrumentor *Instrumentor) pushType(node ast.Node) {
513 t := fmt.Sprintf("%T", node)
514 count, ok := instrumentor.typeCounts[t]
515 if !ok {
516 count = 0
517 }
518 // This will create an identifier of the form ${nodeType}@${index}, indicating the type of the node
519 // and the number of other nodes in the AST which have had this type. E.g.,
520 // - *ast.AssignStmt@3 (the 4th assignment statement)
521 // - *ast.Ident@24 (the 25th identifier)
522 ts := fmt.Sprintf("%s@%d", t, count)
523 // Append to the depth-first list of nodes we've traversed to get here.
524 instrumentor.currPos = append(instrumentor.currPos, ts)
525 instrumentor.typeCounts[t] = count + 1
526 }
527
528 func (instrumentor *Instrumentor) popType() {
529 if len(instrumentor.currPos) == 0 {
530 return
531 }
532 instrumentor.currPos = instrumentor.currPos[:len(instrumentor.currPos)-1]
533 }
534
535 // Get a string representing the current position in the AST, using the node identifiers defined above. E.g.,
536 //
537 // - *ast.File@0|*ast.FuncDecl@0|*ast.BlockStmt@0|*ast.AssignStmt@3
538 // this file | 1st function | 1st fn block | 4th assignment statement in the file
539 //
540 // This allows us to uniquely identify any node in the AST based on a deterministic depth-first search going
541 // from the top of the file to the bottom.
542 func (instrumentor *Instrumentor) currentPath() string {
543 if len(instrumentor.currPos) == 0 {
544 return ""
545 }
546 return strings.Join(instrumentor.currPos, "|")
547 }
548
549 // Stash the original line number associated with this particular node. We do that by mapping a unique
550 // node identifier -- where it is in the AST, per our deterministic depth-first search -- to the line
551 // number of that node in the original version of the file.
552 func (instrumentor *Instrumentor) collectLine(node ast.Node) {
553 path := instrumentor.currentPath()
554 if len(path) == 0 {
555 return
556 }
557 // The first Ident will pretty much always be the package name. Don't add a //line directive
558 // since we'll likely get that in the wrong place, due to the "Package" object being
559 // disconnected in the AST from the package name.
560 if path == "*ast.File@0|*ast.Ident@0" {
561 common.Logger.Printf(common.Debug, "Skipping package name path %s for node (%T:%v)", path, node, node)
562 return
563 }
564 // For certain types of nodes we will not create line directives, therefore we can
565 // just not collect the lines associated with those nodes.
566 switch n := node.(type) {
567 case *ast.File:
568 return
569 case *ast.CommentGroup, *ast.Comment:
570 return
571 case *ast.GenDecl:
572 if n.Tok == token.IMPORT {
573 // Don't annotate import statements
574 return
575 }
576 }
577 // Get where this node is in the original version of the file.
578 p := instrumentor.fset.Position(node.Pos())
579 // Map the node to the original line number.
580 common.Logger.Printf(common.Trace, "collectLine(%T:%v:%s) => %d", node, node, path, p.Line)
581 instrumentor.nodeLines[path] = p.Line
582 }
583
584 // Given our current position in the AST, on which line number was this node located
585 // in the original version of the file? If we don't know (e.g., path is empty, or we
586 // didn't record the position for whatever reason) return -1.
587 func (instrumentor *Instrumentor) getOriginalLine() int {
588 path := instrumentor.currentPath()
589 if len(path) == 0 {
590 return -1
591 }
592 if line, ok := instrumentor.nodeLines[path]; ok {
593 return line
594 }
595 return -1
596 }
597
598 func (instrumentor *Instrumentor) VisitAndInstrument(node ast.Node) ast.Visitor {
599 if node == nil {
600 instrumentor.popType()
601 top, _ := instrumentor.nodeStack.Pop()
602 if decl, isDecl := top.(*ast.FuncDecl); isDecl {
603 common.Logger.Printf(common.Debug, "AddCallbacks Popping function %s", decl.Name.Name)
604 instrumentor.funcStack.Pop()
605 } else {
606 common.Logger.Printf(common.Debug, "AddCallbacks Popping node: %v (%T)", top, top)
607 }
608 return instrumentor
609 }
610
611 if isInstrumentationCallback(node) {
612 // It is possible for us to start traversing nodes that we've inserted ahead of ourselves,
613 // so skip over those since we're not going to instrument the instrumentation, AND it will
614 // throw off our accounting needed for collecting line numbers.
615 return nil
616 }
617
618 instrumentor.pushType(node)
619 instrumentor.collectLine(node)
620
621 switch n := node.(type) {
622 case *ast.FuncDecl:
623 if n.Name.String() == "init" {
624 // Don't instrument init functions.
625 // They run regardless of what we do, so it is just noise.
626 instrumentor.popType()
627 return nil
628 }
629 case *ast.GenDecl:
630 if n.Tok != token.VAR {
631 instrumentor.popType()
632 return nil // constants and types are not interesting
633 }
634
635 case *ast.BlockStmt:
636 // If it's a switch or select, the body is a list of case clauses; don't tag the block itself.
637 if len(n.List) > 0 {
638 switch n.List[0].(type) {
639 case *ast.CaseClause: // switch
640 for _, n := range n.List {
641 clause := n.(*ast.CaseClause)
642 clause.Body = instrumentor.instrumentEdge(clause.Pos(), clause.End(), clause.Body, false)
643 }
644 return instrumentor
645 case *ast.CommClause: // select
646 for _, n := range n.List {
647 clause := n.(*ast.CommClause)
648 clause.Body = instrumentor.instrumentEdge(clause.Pos(), clause.End(), clause.Body, false)
649 }
650 return instrumentor
651 }
652 }
653 n.List = instrumentor.instrumentEdge(n.Lbrace, n.Rbrace+1, n.List, true) // +1 to step past closing brace.
654 case *ast.IfStmt:
655 if n.Init != nil {
656 ast.Walk(instrumentor, n.Init)
657 }
658 if n.Cond != nil {
659 ast.Walk(instrumentor, n.Cond)
660 }
661 ast.Walk(instrumentor, n.Body)
662 if n.Else == nil {
663 // Add else because we want coverage for "not taken".
664 n.Else = &ast.BlockStmt{
665 Lbrace: n.Body.End(),
666 Rbrace: n.Body.End(),
667 }
668 }
669 switch stmt := n.Else.(type) {
670 case *ast.IfStmt:
671 block := &ast.BlockStmt{
672 Lbrace: n.Body.End(), // Start at end of the "if" block so the covered part looks like it starts at the "else".
673 List: []ast.Stmt{stmt},
674 Rbrace: stmt.End(),
675 }
676 n.Else = block
677 case *ast.BlockStmt:
678 stmt.Lbrace = n.Body.End() // Start at end of the "if" block so the covered part looks like it starts at the "else".
679 default:
680 common.Logger.Fatalf("Unexpected node type in if : %v (%T)", n, n)
681 }
682 ast.Walk(instrumentor, n.Else)
683 instrumentor.popType()
684 return nil
685 case *ast.ForStmt:
686 // TODO: handle increment statement
687 case *ast.SelectStmt:
688 // Don't annotate an empty select - creates a syntax error.
689 if n.Body == nil || len(n.Body.List) == 0 {
690 instrumentor.popType()
691 return nil
692 }
693 case *ast.SwitchStmt:
694 hasDefault := false
695 if n.Body == nil {
696 n.Body = new(ast.BlockStmt)
697 }
698 for _, s := range n.Body.List {
699 if cas, ok := s.(*ast.CaseClause); ok && cas.List == nil {
700 hasDefault = true
701 break
702 }
703 }
704 if !hasDefault {
705 // Add default case to get additional coverage.
706 n.Body.List = append(n.Body.List, &ast.CaseClause{Case: n.Body.Rbrace, Colon: n.Body.Rbrace})
707 }
708
709 // Don't annotate an empty switch - creates a syntax error.
710 if n.Body == nil || len(n.Body.List) == 0 {
711 instrumentor.popType()
712 return nil
713 }
714 case *ast.TypeSwitchStmt:
715 // Don't annotate an empty type switch - creates a syntax error.
716 // TODO: add default case
717 if n.Body == nil || len(n.Body.List) == 0 {
718 instrumentor.popType()
719 return nil
720 }
721 case *ast.BinaryExpr:
722 if n.Op == token.LAND || n.Op == token.LOR {
723 // Expand the right expression to a comparison with the intrinsic "true". Copy its position to these new nodes.
724 compareYToTrue := &ast.BinaryExpr{X: n.Y, OpPos: n.Y.End(), Op: token.EQL, Y: ast.NewIdent("true")}
725 // Wrap this comparison in a closure.
726 closureWithInstrumentation := &ast.FuncLit{
727 Type: &ast.FuncType{Results: &ast.FieldList{List: []*ast.Field{{Type: ast.NewIdent("bool")}}}},
728 Body: &ast.BlockStmt{Lbrace: n.Y.Pos(), List: []ast.Stmt{&ast.ReturnStmt{Results: []ast.Expr{compareYToTrue}}}, Rbrace: n.Y.End() - 1},
729 }
730 closureCallExpression := &ast.CallExpr{
731 Lparen: n.Y.End(),
732 Fun: closureWithInstrumentation,
733 Rparen: n.Y.End(),
734 }
735 // We have seen cases in which the value of this logical expression cannot be passed to a function
736 // that takes a specialized Boolean type, and so the instrumented code cannot be compiled. This
737 // comparison to "true" gets us around this oddity of the Go type system (or a bug in the compiler).
738 compareClosureInvocationToTrue := &ast.BinaryExpr{X: closureCallExpression, OpPos: n.Y.End(), Op: token.EQL, Y: ast.NewIdent("true")}
739 n.Y = compareClosureInvocationToTrue
740 }
741 case *ast.BadExpr:
742 common.Logger.Fatalf("Invalid input: %v (%T)", node, node)
743 case *ast.BadDecl:
744 common.Logger.Fatalf("Invalid input: %v (%T)", node, node)
745 }
746 // If nil is returned, the children of the current node will not be visited. Now push the node so we can pop it later.
747 if decl, isDecl := node.(*ast.FuncDecl); isDecl {
748 common.Logger.Printf(common.Debug, "AddCallbacks Entering function %s", decl.Name.Name)
749 instrumentor.funcStack.Push(node)
750 } else {
751 common.Logger.Printf(common.Debug, "AddCallbacks Pushing node: %v (%T)", node, node)
752 }
753 instrumentor.nodeStack.Push(node)
754 return instrumentor
755 }
756
757 func (instrumentor *Instrumentor) VisitAndAddLines(node ast.Node) ast.Visitor {
758 if node == nil {
759 instrumentor.popType()
760 top, _ := instrumentor.nodeStack.Pop()
761 if decl, isDecl := top.(*ast.FuncDecl); isDecl {
762 common.Logger.Printf(common.Debug, "AddLines Popping function %s", decl.Name.Name)
763 instrumentor.funcStack.Pop()
764 } else {
765 common.Logger.Printf(common.Debug, "AddLines Popping node: %v (%T)", top, top)
766 }
767 return instrumentor
768 }
769
770 if isInstrumentationCallback(node) {
771 return nil
772 }
773 instrumentor.pushType(node)
774 lineNum := instrumentor.getOriginalLine()
775 if lineNum > 0 {
776 comment := instrumentor.createLineDirective(lineNum, &node)
777 if comment != nil {
778 common.Logger.Printf(common.Trace, "Created line directive for %s line %d", instrumentor.currentPath(), lineNum)
779 instrumentor.comments = append(instrumentor.comments, comment)
780 } else {
781 common.Logger.Printf(common.Trace, "Not creating line directive for line %d path %s", lineNum, instrumentor.currentPath())
782 }
783 } else {
784 common.Logger.Printf(common.Trace, "No line number available for %v=%v", node, instrumentor.currentPath())
785 }
786
787 switch n := node.(type) {
788 case *ast.ExprStmt:
789 case *ast.Ident:
790 case *ast.FuncDecl:
791 if n.Name.String() == "init" {
792 instrumentor.popType()
793 return nil
794 }
795 case *ast.GenDecl:
796 if n.Tok != token.VAR {
797 instrumentor.popType()
798 return nil // constants and types have nothing under them not interesting
799 }
800 case *ast.IfStmt:
801 if n.Init != nil {
802 ast.Walk(instrumentor, n.Init)
803 }
804 if n.Cond != nil {
805 ast.Walk(instrumentor, n.Cond)
806 }
807 ast.Walk(instrumentor, n.Body)
808 if n.Else != nil {
809 ast.Walk(instrumentor, n.Else)
810 }
811 instrumentor.popType()
812 return nil
813 case *ast.SelectStmt:
814 // Don't visit an empty select
815 if n.Body == nil || len(n.Body.List) == 0 {
816 instrumentor.popType()
817 return nil
818 }
819 case *ast.SwitchStmt:
820 // Don't visit an empty switch
821 if n.Body == nil || len(n.Body.List) == 0 {
822 instrumentor.popType()
823 return nil
824 }
825 case *ast.TypeSwitchStmt:
826 // Don't visit an empty type switch
827 if n.Body == nil || len(n.Body.List) == 0 {
828 instrumentor.popType()
829 return nil
830 }
831 }
832 // If nil is returned, the children of the current node will not be visited. Now push the node so we can pop it later.
833 if decl, isDecl := node.(*ast.FuncDecl); isDecl {
834 common.Logger.Printf(common.Debug, "AddLines Entering function %s", decl.Name.Name)
835 instrumentor.funcStack.Push(node)
836 } else {
837 common.Logger.Printf(common.Debug, "AddLines Pushing node: %v (%T)", node, node)
838 }
839 instrumentor.nodeStack.Push(node)
840 return instrumentor
841 }
842
843 // Visit is part of the FileWalker interface.
844 // TODO: (justin.moore) See how difficult it would be to merge the Visit sub-functions back into a
845 // single Visit() function, and just switch on control flow based on the addLines boolean, rather
846 // than duplicating most of the switch statement in each function.
847 func (instrumentor *Instrumentor) Visit(node ast.Node) ast.Visitor {
848 common.Logger.Printf(common.Debug, "Visit(%v, %T:%v => %T:%v)", instrumentor.addLines, &node, &node, node, node)
849 if instrumentor.addLines {
850 return instrumentor.VisitAndAddLines(node)
851 } else {
852 return instrumentor.VisitAndInstrument(node)
853 }
854 }
855
856 func (instrumentor *Instrumentor) statementBoundary(s ast.Stmt) token.Pos {
857 // Control flow statements are easy.
858 switch s := s.(type) {
859 case *ast.BlockStmt:
860 // Treat blocks like basic blocks to avoid overlapping counters.
861 return s.Lbrace
862 case *ast.IfStmt:
863 found, pos := hasFuncLiteral(s.Init)
864 if found {
865 return pos
866 }
867 found, pos = hasFuncLiteral(s.Cond)
868 if found {
869 return pos
870 }
871 return s.Body.Lbrace
872 case *ast.ForStmt:
873 found, pos := hasFuncLiteral(s.Init)
874 if found {
875 return pos
876 }
877 found, pos = hasFuncLiteral(s.Cond)
878 if found {
879 return pos
880 }
881 found, pos = hasFuncLiteral(s.Post)
882 if found {
883 return pos
884 }
885 return s.Body.Lbrace
886 case *ast.LabeledStmt:
887 return instrumentor.statementBoundary(s.Stmt)
888 case *ast.RangeStmt:
889 found, pos := hasFuncLiteral(s.X)
890 if found {
891 return pos
892 }
893 return s.Body.Lbrace
894 case *ast.SwitchStmt:
895 found, pos := hasFuncLiteral(s.Init)
896 if found {
897 return pos
898 }
899 found, pos = hasFuncLiteral(s.Tag)
900 if found {
901 return pos
902 }
903 return s.Body.Lbrace
904 case *ast.SelectStmt:
905 return s.Body.Lbrace
906 case *ast.TypeSwitchStmt:
907 found, pos := hasFuncLiteral(s.Init)
908 if found {
909 return pos
910 }
911 return s.Body.Lbrace
912 }
913 found, pos := hasFuncLiteral(s)
914 if found {
915 return pos
916 }
917 return s.End()
918 }
919
920 func (instrumentor *Instrumentor) instrumentEdge(pos, blockEnd token.Pos, list []ast.Stmt, extendToClosingBrace bool) []ast.Stmt {
921 // Special case: make sure we add a counter to an empty block. Can't do this below
922 // or we will add a counter to an empty statement list after, say, a return statement.
923 if len(list) == 0 {
924 return []ast.Stmt{instrumentor.newEdge(pos, blockEnd)}
925 }
926 // We have a block (statement list), but it may have several basic blocks due to the
927 // appearance of statements that affect the flow of control.
928 var newList []ast.Stmt
929 for {
930 // Find first statement that affects flow of control (break, continue, if, etc.).
931 // It will be the last statement of this basic block.
932 var last int
933 end := blockEnd
934 for last = 0; last < len(list); last++ {
935 end = instrumentor.statementBoundary(list[last])
936 if instrumentor.endsBasicSourceBlock(list[last]) {
937 extendToClosingBrace = false // Block is broken up now.
938 last++
939 break
940 }
941 }
942 if extendToClosingBrace {
943 end = blockEnd
944 }
945 if pos != end { // Can have no source to cover if e.g. blocks abut.
946 newList = append(newList, instrumentor.newEdge(pos, end))
947 }
948 newList = append(newList, list[0:last]...)
949 list = list[last:]
950 if len(list) == 0 {
951 break
952 }
953 pos = list[0].Pos()
954 }
955 return newList
956 }
957
958 func (instrumentor *Instrumentor) endsBasicSourceBlock(s ast.Stmt) bool {
959 switch s := s.(type) {
960 case *ast.BlockStmt:
961 // Treat blocks like basic blocks to avoid overlapping counters.
962 return true
963 case *ast.BranchStmt:
964 return true
965 case *ast.ForStmt:
966 return true
967 case *ast.IfStmt:
968 return true
969 case *ast.LabeledStmt:
970 return instrumentor.endsBasicSourceBlock(s.Stmt)
971 case *ast.RangeStmt:
972 return true
973 case *ast.SwitchStmt:
974 return true
975 case *ast.SelectStmt:
976 return true
977 case *ast.TypeSwitchStmt:
978 return true
979 case *ast.ExprStmt:
980 // Calls to panic change the flow.
981 // We really should verify that "panic" is the predefined function,
982 // but without type checking we can't and the likelihood of it being
983 // an actual problem is vanishingly small.
984 if call, ok := s.X.(*ast.CallExpr); ok {
985 if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" && len(call.Args) == 1 {
986 return true
987 }
988 }
989 }
990 found, _ := hasFuncLiteral(s)
991 return found
992 }
993
994 func (instrumentor *Instrumentor) newEdge(start, end token.Pos) ast.Stmt {
995 instrumentor.CurrentEdge++
996
997 s := instrumentor.fset.Position(start)
998 e := instrumentor.fset.Position(end)
999 maybe_decl, _ := instrumentor.funcStack.Peek()
1000 decl, isDecl := maybe_decl.(*ast.FuncDecl)
1001 fname := ""
1002 if isDecl {
1003 fname = decl.Name.Name
1004 }
1005
1006 err := instrumentor.symbolTable.WritePosition(symboltable.SymbolTablePosition{
1007 Path: instrumentor.fullName,
1008 Function: fname,
1009 StartLine: s.Line,
1010 StartColumn: s.Column,
1011 EndLine: e.Line,
1012 EndColumn: e.Column,
1013 Edge: instrumentor.CurrentEdge,
1014 })
1015 if err != nil {
1016 common.Logger.Fatalf("Could not write symbol table line: %s", err.Error())
1017 }
1018
1019 idx := &ast.BasicLit{
1020 Kind: token.INT,
1021 Value: strconv.Itoa(instrumentor.CurrentEdge),
1022 }
1023 caller := &ast.SelectorExpr{
1024 X: ast.NewIdent(InstrumentationPackageAlias),
1025 Sel: ast.NewIdent(AntithesisCallbackFunction),
1026 }
1027 return &ast.ExprStmt{
1028 X: &ast.CallExpr{
1029 Fun: caller,
1030 Args: []ast.Expr{idx},
1031 },
1032 }
1033 }
1034
1035 // In the AST we'll see a SelectExpr which will have:
1036 // - a package equal to InstrumentationPackageAlias
1037 // - a function name equal to AntithesisCallbackFunction
1038 //
1039 // After those the next thing we see should be an integer literal. I.e.,
1040 //
1041 // __antithesis_instrumentation__.Notify(6)
1042 // | Package name | Fn |^~ Integer literal
1043 //
1044 // In the AST that will be: *ast.SelectorExpr:&{__antithesis_instrumentation__ Notify})
1045 // - Selector{X=(*ast.Ident:__antithesis_instrumentation__), Sel=(*ast.Ident:Notify)}
1046 // Followed by: *ast.BasicLit:&{18366 INT 1})
1047 // - BasicLit{Kind=(token.Token:INT), Value=(string:1)}
1048 func isInstrumentationCallback(n ast.Node) bool {
1049 node, isExp := n.(*ast.ExprStmt)
1050 if !isExp {
1051 return false
1052 }
1053 if node.X == nil {
1054 return false
1055 }
1056 call, callOk := node.X.(*ast.CallExpr)
1057 if !callOk {
1058 return false
1059 }
1060 if call.Fun == nil || call.Args == nil {
1061 return false
1062 }
1063 sel, selOk := call.Fun.(*ast.SelectorExpr)
1064 if !selOk {
1065 return false
1066 }
1067 if sel.X == nil || sel.Sel == nil {
1068 return false
1069 }
1070 x, xOk := sel.X.(*ast.Ident)
1071 if !xOk {
1072 return false
1073 }
1074 return x.Name == InstrumentationPackageAlias && sel.Sel.Name == AntithesisCallbackFunction
1075 }
1076
1077 func (instrumentor *Instrumentor) formatInstrumentedAst(inputPath string, astFile *ast.File, addShim bool) (string, error) {
1078 if addShim {
1079 astutil.AddNamedImport(instrumentor.fset, astFile, InstrumentationPackageAlias, instrumentor.shimPkg)
1080 }
1081 writer := strings.Builder{}
1082 formatError := format.Node(&writer, instrumentor.fset, astFile)
1083 if formatError != nil {
1084 common.Logger.Printf(common.Normal, "Error: Could not write instrumented AST from %s: %v", inputPath, formatError)
1085 return "", formatError
1086 }
1087
1088 source := writer.String()
1089 if _, parseError := parser.ParseFile(&token.FileSet{}, inputPath, source, parser.ParseComments); parseError != nil {
1090 common.Logger.Printf(common.Normal, "Error: Instrumented source for %s could not be parsed; simply copying original: %s", inputPath, parseError)
1091 return "", parseError
1092 }
1093
1094 return source, nil
1095 }
1096
1097 func sortComments(comments []*ast.CommentGroup) {
1098 sort.Slice(comments, func(i, j int) bool {
1099 // Get the position of the first comment in each.
1100 // Based on the documentation of the Golang AST package, we can assume that
1101 // the List element will have non-zero length:
1102 // https://pkg.go.dev/go/ast#CommentGroup
1103 iFirst := comments[i].List[0]
1104 jFirst := comments[j].List[0]
1105 // The Slash member is the position of "/" starting the comment:
1106 // https://pkg.go.dev/go/ast#Comment
1107 return iFirst.Slash < jFirst.Slash
1108 })
1109 }