| 1 | // Copyright 2013 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package interp_test |
| 6 | |
| 7 | // This test runs the SSA interpreter over sample Go programs. |
| 8 | // Because the interpreter requires intrinsics for assembly |
| 9 | // functions and many low-level runtime routines, it is inherently |
| 10 | // not robust to evolutionary change in the standard library. |
| 11 | // Therefore the test cases are restricted to programs that |
| 12 | // use a fake standard library in testdata/src containing a tiny |
| 13 | // subset of simple functions useful for writing assertions. |
| 14 | // |
| 15 | // We no longer attempt to interpret any real standard packages such as |
| 16 | // fmt or testing, as it proved too fragile. |
| 17 | |
| 18 | import ( |
| 19 | "bytes" |
| 20 | "fmt" |
| 21 | "go/build" |
| 22 | "go/types" |
| 23 | "io" |
| 24 | "os" |
| 25 | "path/filepath" |
| 26 | "runtime" |
| 27 | "strings" |
| 28 | "testing" |
| 29 | "time" |
| 30 | "unsafe" |
| 31 | |
| 32 | "golang.org/x/tools/go/loader" |
| 33 | "golang.org/x/tools/go/ssa" |
| 34 | "golang.org/x/tools/go/ssa/interp" |
| 35 | "golang.org/x/tools/go/ssa/ssautil" |
| 36 | "golang.org/x/tools/internal/testenv" |
| 37 | ) |
| 38 | |
| 39 | // Each line contains a space-separated list of $GOROOT/test/ |
| 40 | // filenames comprising the main package of a program. |
| 41 | // They are ordered quickest-first, roughly. |
| 42 | // |
| 43 | // If a test in this list fails spuriously, remove it. |
| 44 | var gorootTestTests = []string{ |
| 45 | "235.go", |
| 46 | "alias1.go", |
| 47 | "func5.go", |
| 48 | "func6.go", |
| 49 | "func7.go", |
| 50 | "func8.go", |
| 51 | "helloworld.go", |
| 52 | "varinit.go", |
| 53 | "escape3.go", |
| 54 | "initcomma.go", |
| 55 | "cmp.go", |
| 56 | "compos.go", |
| 57 | "turing.go", |
| 58 | "indirect.go", |
| 59 | "complit.go", |
| 60 | "for.go", |
| 61 | "struct0.go", |
| 62 | "intcvt.go", |
| 63 | "printbig.go", |
| 64 | "deferprint.go", |
| 65 | "escape.go", |
| 66 | "range.go", |
| 67 | "const4.go", |
| 68 | "float_lit.go", |
| 69 | "bigalg.go", |
| 70 | "decl.go", |
| 71 | "if.go", |
| 72 | "named.go", |
| 73 | "bigmap.go", |
| 74 | "func.go", |
| 75 | "reorder2.go", |
| 76 | "gc.go", |
| 77 | "simassign.go", |
| 78 | "iota.go", |
| 79 | "nilptr2.go", |
| 80 | "utf.go", |
| 81 | "method.go", |
| 82 | "char_lit.go", |
| 83 | "env.go", |
| 84 | "int_lit.go", |
| 85 | "string_lit.go", |
| 86 | "defer.go", |
| 87 | "typeswitch.go", |
| 88 | "stringrange.go", |
| 89 | "reorder.go", |
| 90 | "method3.go", |
| 91 | "literal.go", |
| 92 | "nul1.go", // doesn't actually assert anything (errorcheckoutput) |
| 93 | "zerodivide.go", |
| 94 | "convert.go", |
| 95 | "convT2X.go", |
| 96 | "switch.go", |
| 97 | "ddd.go", |
| 98 | "blank.go", // partly disabled |
| 99 | "closedchan.go", |
| 100 | "divide.go", |
| 101 | "rename.go", |
| 102 | "nil.go", |
| 103 | "recover1.go", |
| 104 | "recover2.go", |
| 105 | "recover3.go", |
| 106 | "typeswitch1.go", |
| 107 | "floatcmp.go", |
| 108 | "crlf.go", // doesn't actually assert anything (runoutput) |
| 109 | } |
| 110 | |
| 111 | // These are files in testdata/. |
| 112 | var testdataTests = []string{ |
| 113 | "boundmeth.go", |
| 114 | "complit.go", |
| 115 | "convert.go", |
| 116 | "coverage.go", |
| 117 | "deepequal.go", |
| 118 | "defer.go", |
| 119 | "fieldprom.go", |
| 120 | "fixedbugs/issue52342.go", |
| 121 | "fixedbugs/issue52835.go", |
| 122 | "fixedbugs/issue55086.go", |
| 123 | "fixedbugs/issue55115.go", |
| 124 | "fixedbugs/issue66783.go", |
| 125 | "fixedbugs/issue69929.go", |
| 126 | "forvarlifetime_go122.go", |
| 127 | "forvarlifetime_old.go", |
| 128 | "ifaceconv.go", |
| 129 | "ifaceprom.go", |
| 130 | "initorder.go", |
| 131 | "methprom.go", |
| 132 | "minmax.go", |
| 133 | "mrvchain.go", |
| 134 | "newexpr_go126.go", |
| 135 | "range.go", |
| 136 | "rangeoverint.go", |
| 137 | "rangevarlifetime_go122.go", |
| 138 | "rangevarlifetime_old.go", |
| 139 | "recover.go", |
| 140 | "reflect.go", |
| 141 | "slice2array.go", |
| 142 | "slice2arrayptr.go", |
| 143 | "static.go", |
| 144 | "structlitpromoted_go127.go", |
| 145 | "typeassert.go", |
| 146 | "width32.go", |
| 147 | "zeros.go", |
| 148 | } |
| 149 | |
| 150 | func init() { |
| 151 | // GOROOT/test used to assume that GOOS and GOARCH were explicitly set in the |
| 152 | // environment, so do that here for TestGorootTest. |
| 153 | os.Setenv("GOOS", runtime.GOOS) |
| 154 | os.Setenv("GOARCH", runtime.GOARCH) |
| 155 | } |
| 156 | |
| 157 | // run runs a single test. On success it returns the captured std{out,err}. |
| 158 | func run(t *testing.T, input string, goroot string) string { |
| 159 | testenv.NeedsExec(t) // really we just need os.Pipe, but os/exec uses pipes |
| 160 | |
| 161 | t.Logf("Input: %s\n", input) |
| 162 | |
| 163 | start := time.Now() |
| 164 | |
| 165 | ctx := build.Default // copy |
| 166 | ctx.GOROOT = goroot |
| 167 | ctx.GOOS = runtime.GOOS |
| 168 | ctx.GOARCH = runtime.GOARCH |
| 169 | if filepath.Base(input) == "width32.go" && unsafe.Sizeof(int(0)) > 4 { |
| 170 | t.Skipf("skipping: width32.go checks behavior for a 32-bit int") |
| 171 | } |
| 172 | |
| 173 | gover := "" |
| 174 | if p := testenv.Go1Point(); p > 0 { |
| 175 | gover = fmt.Sprintf("go1.%d", p) |
| 176 | } |
| 177 | |
| 178 | // Check build tags, since FromArgs doesn't do this part. |
| 179 | // TODO(adonovan): use go/packages. |
| 180 | if match, err := ctx.MatchFile(filepath.Dir(input), filepath.Base(input)); err != nil { |
| 181 | t.Fatalf("MatchFile %v: %v", input, err) |
| 182 | } else if !match { |
| 183 | t.Skipf("file %s doesn't match this build configuration", input) |
| 184 | } |
| 185 | |
| 186 | conf := loader.Config{Build: &ctx, TypeChecker: types.Config{GoVersion: gover}} |
| 187 | if _, err := conf.FromArgs([]string{input}, true); err != nil { |
| 188 | t.Fatalf("FromArgs(%s) failed: %s", input, err) |
| 189 | } |
| 190 | |
| 191 | conf.Import("runtime") |
| 192 | |
| 193 | // Print a helpful hint if we don't make it to the end. |
| 194 | var hint string |
| 195 | defer func() { |
| 196 | t.Logf("Duration: %v", time.Since(start)) |
| 197 | if hint != "" { |
| 198 | t.Log("FAIL") |
| 199 | t.Log(hint) |
| 200 | } else { |
| 201 | t.Log("PASS") |
| 202 | } |
| 203 | }() |
| 204 | |
| 205 | hint = fmt.Sprintf("To dump SSA representation, run:\n%% go build golang.org/x/tools/cmd/ssadump && ./ssadump -test -build=CFP %s\n", input) |
| 206 | |
| 207 | iprog, err := conf.Load() |
| 208 | if err != nil { |
| 209 | t.Fatalf("conf.Load(%s) failed: %s", input, err) |
| 210 | } |
| 211 | |
| 212 | bmode := ssa.InstantiateGenerics | ssa.SanityCheckFunctions |
| 213 | // bmode |= ssa.PrintFunctions // enable for debugging |
| 214 | prog := ssautil.CreateProgram(iprog, bmode) |
| 215 | prog.Build() |
| 216 | |
| 217 | mainPkg := prog.Package(iprog.Created[0].Pkg) |
| 218 | if mainPkg == nil { |
| 219 | t.Fatalf("not a main package: %s", input) |
| 220 | } |
| 221 | |
| 222 | sizes := types.SizesFor("gc", ctx.GOARCH) |
| 223 | if sizes.Sizeof(types.Typ[types.Int]) < 4 { |
| 224 | panic("bogus SizesFor") |
| 225 | } |
| 226 | hint = fmt.Sprintf("To trace execution, run:\n%% go build golang.org/x/tools/cmd/ssadump && ./ssadump -build=C -test -run --interp=T %s\n", input) |
| 227 | |
| 228 | // Capture anything written by the interpreter to os.Std{out,err} |
| 229 | // by temporarily redirecting them to a buffer via a pipe. |
| 230 | // |
| 231 | // While capturing is in effect, we must not write any |
| 232 | // test-related stuff to stderr (including log.Print, t.Log, etc). |
| 233 | var restore func() string // restore files and log+return the mixed out/err. |
| 234 | { |
| 235 | // Connect std{out,err} to pipe. |
| 236 | r, w, err := os.Pipe() |
| 237 | if err != nil { |
| 238 | t.Fatalf("can't create pipe for stderr: %v", err) |
| 239 | } |
| 240 | savedStdout := os.Stdout |
| 241 | savedStderr := os.Stderr |
| 242 | os.Stdout = w |
| 243 | os.Stderr = w |
| 244 | |
| 245 | // Buffer what is written. |
| 246 | var buf strings.Builder |
| 247 | done := make(chan struct{}) |
| 248 | go func() { |
| 249 | if _, err := io.Copy(&buf, r); err != nil { |
| 250 | fmt.Fprintf(savedStderr, "io.Copy: %v", err) |
| 251 | } |
| 252 | close(done) |
| 253 | }() |
| 254 | |
| 255 | // Finally, restore the files and log what was captured. |
| 256 | restore = func() string { |
| 257 | os.Stdout = savedStdout |
| 258 | os.Stderr = savedStderr |
| 259 | w.Close() |
| 260 | <-done |
| 261 | captured := buf.String() |
| 262 | t.Logf("Interpreter's stdout+stderr:\n%s", captured) |
| 263 | return captured |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | var imode interp.Mode // default mode |
| 268 | // imode |= interp.DisableRecover // enable for debugging |
| 269 | // imode |= interp.EnableTracing // enable for debugging |
| 270 | exitCode := interp.Interpret(mainPkg, imode, sizes, input, []string{}) |
| 271 | capturedOutput := restore() |
| 272 | if exitCode != 0 { |
| 273 | t.Fatalf("interpreting %s: exit code was %d", input, exitCode) |
| 274 | } |
| 275 | // $GOROOT/test tests use this convention: |
| 276 | if strings.Contains(capturedOutput, "BUG") { |
| 277 | t.Fatalf("interpreting %s: exited zero but output contained 'BUG'", input) |
| 278 | } |
| 279 | |
| 280 | hint = "" // call off the hounds |
| 281 | |
| 282 | return capturedOutput |
| 283 | } |
| 284 | |
| 285 | // makeGoroot copies testdata/src into the "src" directory of a temporary |
| 286 | // location to mimic GOROOT/src, and adds a file "runtime/consts.go" containing |
| 287 | // declarations for GOOS and GOARCH that match the GOOS and GOARCH of this test. |
| 288 | // |
| 289 | // It returns the directory that should be used for GOROOT. |
| 290 | func makeGoroot(t *testing.T) string { |
| 291 | goroot := t.TempDir() |
| 292 | src := filepath.Join(goroot, "src") |
| 293 | |
| 294 | err := filepath.Walk("testdata/src", func(path string, info os.FileInfo, err error) error { |
| 295 | if err != nil { |
| 296 | return err |
| 297 | } |
| 298 | |
| 299 | rel, err := filepath.Rel("testdata/src", path) |
| 300 | if err != nil { |
| 301 | return err |
| 302 | } |
| 303 | targ := filepath.Join(src, rel) |
| 304 | |
| 305 | if info.IsDir() { |
| 306 | return os.Mkdir(targ, info.Mode().Perm()|0700) |
| 307 | } |
| 308 | |
| 309 | b, err := os.ReadFile(path) |
| 310 | if err != nil { |
| 311 | return err |
| 312 | } |
| 313 | return os.WriteFile(targ, b, info.Mode().Perm()) |
| 314 | }) |
| 315 | if err != nil { |
| 316 | t.Fatal(err) |
| 317 | } |
| 318 | |
| 319 | constsGo := fmt.Sprintf(`package runtime |
| 320 | const GOOS = %q |
| 321 | const GOARCH = %q |
| 322 | `, runtime.GOOS, runtime.GOARCH) |
| 323 | err = os.WriteFile(filepath.Join(src, "runtime/consts.go"), []byte(constsGo), 0644) |
| 324 | if err != nil { |
| 325 | t.Fatal(err) |
| 326 | } |
| 327 | |
| 328 | return goroot |
| 329 | } |
| 330 | |
| 331 | // TestTestdataFiles runs the interpreter on testdata/*.go. |
| 332 | func TestTestdataFiles(t *testing.T) { |
| 333 | goroot := makeGoroot(t) |
| 334 | for _, input := range testdataTests { |
| 335 | t.Run(input, func(t *testing.T) { |
| 336 | run(t, filepath.Join("testdata", input), goroot) |
| 337 | }) |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | // TestGorootTest runs the interpreter on $GOROOT/test/*.go. |
| 342 | func TestGorootTest(t *testing.T) { |
| 343 | testenv.NeedsGOROOTDir(t, "test") |
| 344 | |
| 345 | goroot := makeGoroot(t) |
| 346 | for _, input := range gorootTestTests { |
| 347 | t.Run(input, func(t *testing.T) { |
| 348 | run(t, filepath.Join(build.Default.GOROOT, "test", input), goroot) |
| 349 | }) |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | // TestTypeparamTest runs the interpreter on runnable examples |
| 354 | // in $GOROOT/test/typeparam/*.go. |
| 355 | |
| 356 | func TestTypeparamTest(t *testing.T) { |
| 357 | testenv.NeedsGOROOTDir(t, "test") |
| 358 | |
| 359 | if runtime.GOARCH == "wasm" { |
| 360 | // See ssa/TestTypeparamTest. |
| 361 | t.Skip("Consistent flakes on wasm (e.g. https://go.dev/issues/64726)") |
| 362 | } |
| 363 | |
| 364 | goroot := makeGoroot(t) |
| 365 | |
| 366 | // Skip known failures for the given reason. |
| 367 | // TODO(taking): Address these. |
| 368 | skip := map[string]string{ |
| 369 | "chans.go": "interp tests do not support runtime.SetFinalizer", |
| 370 | "issue23536.go": "unknown reason", |
| 371 | "issue48042.go": "interp tests do not handle reflect.Value.SetInt", |
| 372 | "issue47716.go": "interp tests do not handle unsafe.Sizeof", |
| 373 | "issue50419.go": "interp tests do not handle dispatch to String() correctly", |
| 374 | "issue51733.go": "interp does not handle unsafe casts", |
| 375 | "ordered.go": "math.NaN() comparisons not being handled correctly", |
| 376 | "orderedmap.go": "interp tests do not support runtime.SetFinalizer", |
| 377 | "stringer.go": "unknown reason", |
| 378 | "issue48317.go": "interp tests do not support encoding/json", |
| 379 | "issue48318.go": "interp tests do not support encoding/json", |
| 380 | "issue58513.go": "interp tests do not support runtime.Caller", |
| 381 | } |
| 382 | // Collect all of the .go files in dir that are runnable. |
| 383 | dir := filepath.Join(build.Default.GOROOT, "test", "typeparam") |
| 384 | list, err := os.ReadDir(dir) |
| 385 | if err != nil { |
| 386 | t.Fatal(err) |
| 387 | } |
| 388 | for _, entry := range list { |
| 389 | if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") { |
| 390 | continue // Consider standalone go files. |
| 391 | } |
| 392 | t.Run(entry.Name(), func(t *testing.T) { |
| 393 | input := filepath.Join(dir, entry.Name()) |
| 394 | src, err := os.ReadFile(input) |
| 395 | if err != nil { |
| 396 | t.Fatal(err) |
| 397 | } |
| 398 | |
| 399 | // Only build test files that can be compiled, or compiled and run. |
| 400 | if !bytes.HasPrefix(src, []byte("// run")) || bytes.HasPrefix(src, []byte("// rundir")) { |
| 401 | t.Logf("Not a `// run` file: %s", entry.Name()) |
| 402 | return |
| 403 | } |
| 404 | |
| 405 | if reason := skip[entry.Name()]; reason != "" { |
| 406 | t.Skipf("skipping: %s", reason) |
| 407 | } |
| 408 | |
| 409 | run(t, input, goroot) |
| 410 | }) |
| 411 | } |
| 412 | } |