| 1 |
package instrumentor |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"go/ast" |
| 6 |
"go/parser" |
| 7 |
"go/token" |
| 8 |
"os" |
| 9 |
"strings" |
| 10 |
|
| 11 |
"github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/common" |
| 12 |
"github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/scanners/coverage/symboltable" |
| 13 |
) |
| 14 |
|
| 15 |
// SourceEditingInstrumentor *is* the Antithesis Go source-code instrumentor. |
| 16 |
type SourceEditingInstrumentor struct { |
| 17 |
fset *token.FileSet |
| 18 |
symbolTable *symboltable.SymbolTable |
| 19 |
fullName string |
| 20 |
shortName string |
| 21 |
basePath string |
| 22 |
shimPkg string |
| 23 |
// the identifier the emitted calls are made on |
| 24 |
callbackName string |
| 25 |
funcStack Stack |
| 26 |
nodeStack Stack |
| 27 |
CurrentEdge int |
| 28 |
src []byte |
| 29 |
buf *editBuffer |
| 30 |
} |
| 31 |
|
| 32 |
// CreateSourceEditingInstrumentor is the factory method. |
| 33 |
func CreateSourceEditingInstrumentor(basePath string, shimPkg string, table *symboltable.SymbolTable) *SourceEditingInstrumentor { |
| 34 |
if len(basePath) > 0 && !strings.HasSuffix(basePath, "/") { |
| 35 |
basePath = basePath + "/" |
| 36 |
} |
| 37 |
return &SourceEditingInstrumentor{ |
| 38 |
basePath: basePath, |
| 39 |
fset: token.NewFileSet(), |
| 40 |
shimPkg: shimPkg, |
| 41 |
symbolTable: table, |
| 42 |
callbackName: InstrumentationPackageAlias, |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
func (instrumentor *SourceEditingInstrumentor) SetCallbackName(name string) { |
| 47 |
instrumentor.callbackName = name |
| 48 |
} |
| 49 |
|
| 50 |
// Edges returns the number of coverage edges recorded so far (across every file |
| 51 |
// instrumented by this instance). It exposes CurrentEdge through the interface |
| 52 |
// the coverage package selects implementations on. |
| 53 |
func (instrumentor *SourceEditingInstrumentor) Edges() int { |
| 54 |
return instrumentor.CurrentEdge |
| 55 |
} |
| 56 |
|
| 57 |
// Instrument inserts calls to the Golang bridge to the Antithesis fuzzer. |
| 58 |
// Errors should be logged, but are generally not fatal, since the input |
| 59 |
// file can simply be copied to the output uninstrumented. If a file contains |
| 60 |
// no executable code (i.e. contains only variable declarations, exports, |
| 61 |
// or imports, an empty string is returned, so that the caller can simply |
| 62 |
// copy the input file. |
| 63 |
// TODO Return a * to a string, rather that returning the empty string to |
| 64 |
// signal "I didn't instrument this input." |
| 65 |
func (instrumentor *SourceEditingInstrumentor) Instrument(path string) (string, error) { |
| 66 |
bytes, e := os.ReadFile(path) |
| 67 |
if e != nil { |
| 68 |
return "", e |
| 69 |
} |
| 70 |
|
| 71 |
instrumentor.fullName = path |
| 72 |
instrumentor.shortName = strings.TrimPrefix(path, instrumentor.basePath) |
| 73 |
startingEdge := instrumentor.CurrentEdge |
| 74 |
|
| 75 |
f, e := parser.ParseFile(instrumentor.fset, path, bytes, parser.ParseComments) |
| 76 |
if e != nil { |
| 77 |
return "", e |
| 78 |
} |
| 79 |
|
| 80 |
if ExportsFunctions(f, instrumentor.fset) { |
| 81 |
common.Logger.Printf(common.Normal, "File %s exports functions, and will not be instrumented", path) |
| 82 |
return "", nil |
| 83 |
} |
| 84 |
|
| 85 |
if HasLinkname(f, instrumentor.fset) { |
| 86 |
common.Logger.Printf(common.Normal, "File %s exports linknames, and will not be instrumented", path) |
| 87 |
return "", nil |
| 88 |
} |
| 89 |
|
| 90 |
instrumentor.src = bytes |
| 91 |
instrumentor.buf = &editBuffer{src: bytes} |
| 92 |
ast.Walk(instrumentor, f) |
| 93 |
|
| 94 |
if instrumentor.CurrentEdge == startingEdge { |
| 95 |
common.Logger.Printf(common.Info, "File %s has no code to be instrumented, and will simply be copied", path) |
| 96 |
return "", nil |
| 97 |
} |
| 98 |
|
| 99 |
// Pull in the notifier shim inline (no extra line) so nothing shifts. An |
| 100 |
// empty shimPkg means the caller supplies the callback itself |
| 101 |
if instrumentor.shimPkg != "" { |
| 102 |
instrumentor.buf.insert(instrumentor.offAt(f.Name.End()), |
| 103 |
fmt.Sprintf("; import %s %q", instrumentor.callbackName, instrumentor.shimPkg)) |
| 104 |
} |
| 105 |
|
| 106 |
// Prepend one //line directive (as cmd/cover does) because compilation will happen in a temporary directory |
| 107 |
if IsLineDirectiveCompatible(f, instrumentor.fset) { |
| 108 |
instrumentor.buf.insert(0, fmt.Sprintf("//line %s:1:1\n", instrumentor.shortName)) |
| 109 |
} else { |
| 110 |
common.Logger.Printf(common.Normal, "File %s has functions which are incompatible with //line directives. Will be instrumented but not //line-annotated.", path) |
| 111 |
} |
| 112 |
return string(instrumentor.buf.bytes()), nil |
| 113 |
} |
| 114 |
|
| 115 |
func (instrumentor *SourceEditingInstrumentor) Visit(node ast.Node) ast.Visitor { |
| 116 |
if node == nil { |
| 117 |
if top, _ := instrumentor.nodeStack.Pop(); isFuncDecl(top) { |
| 118 |
instrumentor.funcStack.Pop() |
| 119 |
} |
| 120 |
return instrumentor |
| 121 |
} |
| 122 |
|
| 123 |
switch n := node.(type) { |
| 124 |
case *ast.FuncDecl: |
| 125 |
if n.Name.String() == "init" { |
| 126 |
// init runs regardless of what we do, so instrumenting it is noise. |
| 127 |
return nil |
| 128 |
} |
| 129 |
case *ast.GenDecl: |
| 130 |
if n.Tok != token.VAR { |
| 131 |
return nil // constants and types are not interesting |
| 132 |
} |
| 133 |
|
| 134 |
case *ast.BlockStmt: |
| 135 |
// If it's a switch or select, the body is a list of case clauses; don't tag the block itself. |
| 136 |
switch { |
| 137 |
case len(n.List) > 0 && isCaseClause(n.List[0]): // switch |
| 138 |
for _, s := range n.List { |
| 139 |
clause := s.(*ast.CaseClause) |
| 140 |
// span starts at the `case`/`default` keyword; Notify is inserted after the colon. |
| 141 |
instrumentor.instrumentEdge(clause.Pos(), clause.Colon, clause.End(), clause.Body, false) |
| 142 |
} |
| 143 |
case len(n.List) > 0 && isCommClause(n.List[0]): // select |
| 144 |
for _, s := range n.List { |
| 145 |
clause := s.(*ast.CommClause) |
| 146 |
instrumentor.instrumentEdge(clause.Pos(), clause.Colon, clause.End(), clause.Body, false) |
| 147 |
} |
| 148 |
default: |
| 149 |
instrumentor.instrumentEdge(n.Lbrace, n.Lbrace, n.Rbrace+1, n.List, true) // +1 to step past closing brace. |
| 150 |
} |
| 151 |
case *ast.IfStmt: |
| 152 |
if n.Init != nil { |
| 153 |
ast.Walk(instrumentor, n.Init) |
| 154 |
} |
| 155 |
if n.Cond != nil { |
| 156 |
ast.Walk(instrumentor, n.Cond) |
| 157 |
} |
| 158 |
ast.Walk(instrumentor, n.Body) |
| 159 |
switch els := n.Else.(type) { |
| 160 |
case nil: |
| 161 |
// Add else because we want coverage for "not taken". |
| 162 |
edge := instrumentor.recordEdge(n.Body.End(), n.Body.End()+1) |
| 163 |
instrumentor.buf.insert(instrumentor.offAt(n.Body.End()), " else {"+instrumentor.notifyCall(edge)+"}") |
| 164 |
case *ast.BlockStmt: |
| 165 |
// Start at end of the "if" block so the covered part looks like it starts at the "else". |
| 166 |
instrumentor.instrumentEdge(n.Body.End(), els.Lbrace, els.Rbrace+1, els.List, true) |
| 167 |
for _, s := range els.List { |
| 168 |
ast.Walk(instrumentor, s) |
| 169 |
} |
| 170 |
case *ast.IfStmt: |
| 171 |
// Start at end of the "if" block so the covered part looks like it starts at the "else". |
| 172 |
edge := instrumentor.recordEdge(n.Body.End(), instrumentor.statementBoundary(els)) |
| 173 |
instrumentor.buf.insert(instrumentor.offAt(els.Pos()), "{"+instrumentor.notifyCall(edge)+"; ") |
| 174 |
// Walk before closing the wrapper: if the else-if has no trailing |
| 175 |
// else, walking synthesizes one at els.End(); the wrapper's closing |
| 176 |
// brace must be inserted AFTER that (same offset, so later insertion |
| 177 |
// wins the tie) or the synthesized else detaches from its if. |
| 178 |
ast.Walk(instrumentor, els) |
| 179 |
instrumentor.buf.insert(instrumentor.offAt(els.End()), "}") |
| 180 |
default: |
| 181 |
common.Logger.Fatalf("Unexpected node type in else: %v (%T)", n.Else, n.Else) |
| 182 |
} |
| 183 |
return nil |
| 184 |
case *ast.ForStmt: |
| 185 |
// TODO: handle increment statement |
| 186 |
case *ast.SelectStmt: |
| 187 |
// Don't annotate an empty select - creates a syntax error. |
| 188 |
if n.Body == nil || len(n.Body.List) == 0 { |
| 189 |
return nil |
| 190 |
} |
| 191 |
case *ast.SwitchStmt: |
| 192 |
// Don't annotate an empty switch - creates a syntax error. |
| 193 |
if n.Body == nil || len(n.Body.List) == 0 { |
| 194 |
return nil |
| 195 |
} |
| 196 |
// Walk the switch's own parts first so the real case clauses claim their |
| 197 |
// edge ids before the synthesized default. |
| 198 |
if n.Init != nil { |
| 199 |
ast.Walk(instrumentor, n.Init) |
| 200 |
} |
| 201 |
if n.Tag != nil { |
| 202 |
ast.Walk(instrumentor, n.Tag) |
| 203 |
} |
| 204 |
ast.Walk(instrumentor, n.Body) |
| 205 |
hasDefault := false |
| 206 |
for _, s := range n.Body.List { |
| 207 |
if cas, ok := s.(*ast.CaseClause); ok && cas.List == nil { |
| 208 |
hasDefault = true |
| 209 |
break |
| 210 |
} |
| 211 |
} |
| 212 |
if !hasDefault { |
| 213 |
// Synthesize a default case so "no case matched" is covered. |
| 214 |
edge := instrumentor.recordEdge(n.Body.Rbrace, n.Body.Rbrace+1) |
| 215 |
rbrace := instrumentor.offAt(n.Body.Rbrace) |
| 216 |
sep := "" |
| 217 |
if instrumentor.sameLineCodePrecedes(rbrace) { |
| 218 |
sep = "; " |
| 219 |
} |
| 220 |
instrumentor.buf.insert(rbrace, sep+"default: "+instrumentor.notifyCall(edge)+";") |
| 221 |
} |
| 222 |
return nil |
| 223 |
case *ast.TypeSwitchStmt: |
| 224 |
// TODO: add default case |
| 225 |
if n.Body == nil || len(n.Body.List) == 0 { |
| 226 |
return nil // annotating an empty type switch would be a syntax error |
| 227 |
} |
| 228 |
case *ast.BinaryExpr: |
| 229 |
if n.Op == token.LAND || n.Op == token.LOR { |
| 230 |
// Replace the whole (possibly nested) short-circuit expression in one |
| 231 |
// edit and prune the walk, so no other edit lands inside the span. |
| 232 |
instrumentor.instrumentShortCircuit(n) |
| 233 |
return nil |
| 234 |
} |
| 235 |
case *ast.BadExpr: |
| 236 |
common.Logger.Fatalf("Invalid input: %v (%T)", node, node) |
| 237 |
case *ast.BadDecl: |
| 238 |
common.Logger.Fatalf("Invalid input: %v (%T)", node, node) |
| 239 |
} |
| 240 |
|
| 241 |
// Returning a non-nil visitor lets ast.Walk descend into this node's |
| 242 |
// children; push it so the matching nil visit can unwind funcStack. |
| 243 |
if isFuncDecl(node) { |
| 244 |
instrumentor.funcStack.Push(node) |
| 245 |
} |
| 246 |
instrumentor.nodeStack.Push(node) |
| 247 |
return instrumentor |
| 248 |
} |
| 249 |
|
| 250 |
func isFuncDecl(n ast.Node) bool { |
| 251 |
_, ok := n.(*ast.FuncDecl) |
| 252 |
return ok |
| 253 |
} |
| 254 |
|
| 255 |
func isCaseClause(n ast.Node) bool { |
| 256 |
_, ok := n.(*ast.CaseClause) |
| 257 |
return ok |
| 258 |
} |
| 259 |
|
| 260 |
func isCommClause(n ast.Node) bool { |
| 261 |
_, ok := n.(*ast.CommClause) |
| 262 |
return ok |
| 263 |
} |
| 264 |
|
| 265 |
func (instrumentor *SourceEditingInstrumentor) statementBoundary(s ast.Stmt) token.Pos { |
| 266 |
// Control flow statements are easy. |
| 267 |
switch s := s.(type) { |
| 268 |
case *ast.BlockStmt: |
| 269 |
// Treat blocks like basic blocks to avoid overlapping counters. |
| 270 |
return s.Lbrace |
| 271 |
case *ast.IfStmt: |
| 272 |
found, pos := hasFuncLiteral(s.Init) |
| 273 |
if found { |
| 274 |
return pos |
| 275 |
} |
| 276 |
found, pos = hasFuncLiteral(s.Cond) |
| 277 |
if found { |
| 278 |
return pos |
| 279 |
} |
| 280 |
return s.Body.Lbrace |
| 281 |
case *ast.ForStmt: |
| 282 |
found, pos := hasFuncLiteral(s.Init) |
| 283 |
if found { |
| 284 |
return pos |
| 285 |
} |
| 286 |
found, pos = hasFuncLiteral(s.Cond) |
| 287 |
if found { |
| 288 |
return pos |
| 289 |
} |
| 290 |
found, pos = hasFuncLiteral(s.Post) |
| 291 |
if found { |
| 292 |
return pos |
| 293 |
} |
| 294 |
return s.Body.Lbrace |
| 295 |
case *ast.LabeledStmt: |
| 296 |
return instrumentor.statementBoundary(s.Stmt) |
| 297 |
case *ast.RangeStmt: |
| 298 |
found, pos := hasFuncLiteral(s.X) |
| 299 |
if found { |
| 300 |
return pos |
| 301 |
} |
| 302 |
return s.Body.Lbrace |
| 303 |
case *ast.SwitchStmt: |
| 304 |
found, pos := hasFuncLiteral(s.Init) |
| 305 |
if found { |
| 306 |
return pos |
| 307 |
} |
| 308 |
found, pos = hasFuncLiteral(s.Tag) |
| 309 |
if found { |
| 310 |
return pos |
| 311 |
} |
| 312 |
return s.Body.Lbrace |
| 313 |
case *ast.SelectStmt: |
| 314 |
return s.Body.Lbrace |
| 315 |
case *ast.TypeSwitchStmt: |
| 316 |
found, pos := hasFuncLiteral(s.Init) |
| 317 |
if found { |
| 318 |
return pos |
| 319 |
} |
| 320 |
return s.Body.Lbrace |
| 321 |
} |
| 322 |
found, pos := hasFuncLiteral(s) |
| 323 |
if found { |
| 324 |
return pos |
| 325 |
} |
| 326 |
return s.End() |
| 327 |
} |
| 328 |
|
| 329 |
func (instrumentor *SourceEditingInstrumentor) instrumentEdge(spanStart, lbrace, blockEnd token.Pos, list []ast.Stmt, extendToClosingBrace bool) { |
| 330 |
// Special case: cover an empty block by sitting just inside the braces. A |
| 331 |
// separator is still needed when real code follows on the same line. |
| 332 |
if len(list) == 0 { |
| 333 |
off := instrumentor.offAfter(lbrace) |
| 334 |
instrumentor.insertEdge(off, instrumentor.firstBlockSep(off), spanStart, blockEnd) |
| 335 |
return |
| 336 |
} |
| 337 |
// A statement list may hold several basic blocks due to statements that |
| 338 |
// affect the flow of control. |
| 339 |
pos := spanStart |
| 340 |
firstBlock := true |
| 341 |
for { |
| 342 |
// Find first statement that affects flow of control (break, continue, if, etc.). |
| 343 |
// It will be the last statement of this basic block. |
| 344 |
var last int |
| 345 |
end := blockEnd |
| 346 |
for last = 0; last < len(list); last++ { |
| 347 |
end = instrumentor.statementBoundary(list[last]) |
| 348 |
if instrumentor.endsBasicSourceBlock(list[last]) { |
| 349 |
extendToClosingBrace = false // Block is broken up now. |
| 350 |
last++ |
| 351 |
break |
| 352 |
} |
| 353 |
} |
| 354 |
if extendToClosingBrace { |
| 355 |
end = blockEnd |
| 356 |
} |
| 357 |
if pos != end { // Can have no source to cover if e.g. blocks abut. |
| 358 |
if firstBlock { |
| 359 |
// Just past the '{' / ':'. A ';' is added only when real code |
| 360 |
// follows on the same line (e.g. `func() { x() }`); otherwise a |
| 361 |
// newline or // comment lets auto-semicolon insertion do the job. |
| 362 |
off := instrumentor.offAfter(lbrace) |
| 363 |
instrumentor.insertEdge(off, instrumentor.firstBlockSep(off), pos, end) |
| 364 |
} else { |
| 365 |
// Inline, directly before this basic block's leading statement. |
| 366 |
instrumentor.insertEdge(instrumentor.offAt(list[0].Pos()), "; ", pos, end) |
| 367 |
} |
| 368 |
} |
| 369 |
list = list[last:] |
| 370 |
if len(list) == 0 { |
| 371 |
break |
| 372 |
} |
| 373 |
firstBlock = false |
| 374 |
pos = list[0].Pos() |
| 375 |
} |
| 376 |
} |
| 377 |
|
| 378 |
func (instrumentor *SourceEditingInstrumentor) endsBasicSourceBlock(s ast.Stmt) bool { |
| 379 |
switch s := s.(type) { |
| 380 |
case *ast.BlockStmt: |
| 381 |
// Treat blocks like basic blocks to avoid overlapping counters. |
| 382 |
return true |
| 383 |
case *ast.BranchStmt: |
| 384 |
return true |
| 385 |
case *ast.ForStmt: |
| 386 |
return true |
| 387 |
case *ast.IfStmt: |
| 388 |
return true |
| 389 |
case *ast.LabeledStmt: |
| 390 |
return instrumentor.endsBasicSourceBlock(s.Stmt) |
| 391 |
case *ast.RangeStmt: |
| 392 |
return true |
| 393 |
case *ast.SwitchStmt: |
| 394 |
return true |
| 395 |
case *ast.SelectStmt: |
| 396 |
return true |
| 397 |
case *ast.TypeSwitchStmt: |
| 398 |
return true |
| 399 |
case *ast.ExprStmt: |
| 400 |
// Calls to panic change the flow. |
| 401 |
// We really should verify that "panic" is the predefined function, |
| 402 |
// but without type checking we can't and the likelihood of it being |
| 403 |
// an actual problem is vanishingly small. |
| 404 |
if call, ok := s.X.(*ast.CallExpr); ok { |
| 405 |
if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" && len(call.Args) == 1 { |
| 406 |
return true |
| 407 |
} |
| 408 |
} |
| 409 |
} |
| 410 |
found, _ := hasFuncLiteral(s) |
| 411 |
return found |
| 412 |
} |