1
0
mirror of https://github.com/golang/go synced 2024-10-01 12:48:33 -06:00
go/cmd/ssadump/main.go

187 lines
4.5 KiB
Go
Raw Normal View History

// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// ssadump: a tool for displaying and interpreting the SSA form of Go programs.
package main // import "golang.org/x/tools/cmd/ssadump"
import (
"flag"
"fmt"
"go/build"
"os"
"runtime"
"runtime/pprof"
"golang.org/x/tools/go/buildutil"
"golang.org/x/tools/go/loader"
"golang.org/x/tools/go/ssa"
"golang.org/x/tools/go/ssa/interp"
"golang.org/x/tools/go/ssa/ssautil"
"golang.org/x/tools/go/types"
)
var (
modeFlag = ssa.BuilderModeFlag(flag.CommandLine, "build", 0)
testFlag = flag.Bool("test", false, "Loads test code (*_test.go) for imported packages.")
runFlag = flag.Bool("run", false, "Invokes the SSA interpreter on the program.")
interpFlag = flag.String("interp", "", `Options controlling the SSA test interpreter.
The value is a sequence of zero or more more of these letters:
R disable [R]ecover() from panic; show interpreter crash instead.
T [T]race execution of the program. Best for single-threaded programs!
`)
)
const usage = `SSA builder and interpreter.
Usage: ssadump [<flag> ...] <args> ...
Use -help flag to display options.
Examples:
% ssadump -build=F hello.go # dump SSA form of a single package
% ssadump -run -interp=T hello.go # interpret a program, with tracing
% ssadump -run -test unicode -- -test.v # interpret the unicode package's tests, verbosely
` + loader.FromArgsUsage +
`
When -run is specified, ssadump will run the program.
The entry point depends on the -test flag:
if clear, it runs the first package named main.
if set, it runs the tests of each package.
`
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
func init() {
flag.Var((*buildutil.TagsFlag)(&build.Default.BuildTags), "tags", buildutil.TagsFlagDoc)
// If $GOMAXPROCS isn't set, use the full capacity of the machine.
// For small machines, use at least 4 threads.
if os.Getenv("GOMAXPROCS") == "" {
n := runtime.NumCPU()
if n < 4 {
n = 4
}
runtime.GOMAXPROCS(n)
}
}
func main() {
if err := doMain(); err != nil {
fmt.Fprintf(os.Stderr, "ssadump: %s\n", err)
os.Exit(1)
}
}
func doMain() error {
flag.Parse()
args := flag.Args()
conf := loader.Config{Build: &build.Default}
// Choose types.Sizes from conf.Build.
var wordSize int64 = 8
switch conf.Build.GOARCH {
case "386", "arm":
wordSize = 4
}
conf.TypeChecker.Sizes = &types.StdSizes{
MaxAlign: 8,
WordSize: wordSize,
}
var interpMode interp.Mode
for _, c := range *interpFlag {
switch c {
case 'T':
interpMode |= interp.EnableTracing
case 'R':
interpMode |= interp.DisableRecover
default:
return fmt.Errorf("unknown -interp option: '%c'", c)
}
}
if len(args) == 0 {
fmt.Fprint(os.Stderr, usage)
os.Exit(1)
}
// Profiling support.
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
// Use the initial packages from the command line.
args, err := conf.FromArgs(args, *testFlag)
if err != nil {
return err
}
go.tools/ssa: implement correct control flow for recovered panic. A function such as this: func one() (x int) { defer func() { recover() }() x = 1 panic("return") } that combines named return parameters (NRPs) with deferred calls that call recover, may return non-zero values despite the fact it doesn't even contain a return statement. (!) This requires a change to the SSA API: all functions' control-flow graphs now have a second entry point, called Recover, which is the block at which control flow resumes after a recovered panic. The Recover block simply loads the NRPs and returns them. As an optimization, most functions don't need a Recover block, so it is omitted. In fact it is only needed for functions that have NRPs and defer a call to another function that _may_ call recover. Dataflow analysis of SSA now requires extra work, since every may-panic instruction has an implicit control-flow edge to the Recover block. The only dataflow analysis so far implemented is SSA renaming, for which we make the following simplifying assumption: the Recover block only loads the NRPs and returns. This means we don't really need to analyze it, we can just skip the "lifting" of such NRPs. We also special-case the Recover block in the dominance computation. Rejected alternative approaches: - Specifying a Recover block for every defer instruction (like a traditional exception handler). This seemed like excessive generality, since Go programs only need the same degenerate form of Recover block. - Adding an instruction to set the Recover block immediately after the named return values are set up, so that dominance can be computed without special-casing. This didn't seem worth the effort. Interpreter: - This CL completely reimplements the panic/recover/ defer logic in the interpreter. It's clearer and simpler and closer to the model in the spec. - Some runtime panic messages have been changed to be closer to gc's, since tests depend on it. - The interpreter now requires that the runtime.runtimeError type be part of the SSA program. This requires that clients import this package prior to invoking the interpreter. This in turn requires (Importer).ImportPackage(path string), which this CL adds. - All $GOROOT/test/recover{,1,2,3}.go tests are now passing. NB, the bug described in coverage.go (defer/recover in a concatenated init function) remains. Will be fixed in a follow-up. Fixes golang/go#6381 R=gri CC=crawshaw, golang-dev https://golang.org/cl/13844043
2013-10-14 13:38:56 -06:00
// The interpreter needs the runtime package.
if *runFlag {
conf.Import("runtime")
go.tools/ssa: implement correct control flow for recovered panic. A function such as this: func one() (x int) { defer func() { recover() }() x = 1 panic("return") } that combines named return parameters (NRPs) with deferred calls that call recover, may return non-zero values despite the fact it doesn't even contain a return statement. (!) This requires a change to the SSA API: all functions' control-flow graphs now have a second entry point, called Recover, which is the block at which control flow resumes after a recovered panic. The Recover block simply loads the NRPs and returns them. As an optimization, most functions don't need a Recover block, so it is omitted. In fact it is only needed for functions that have NRPs and defer a call to another function that _may_ call recover. Dataflow analysis of SSA now requires extra work, since every may-panic instruction has an implicit control-flow edge to the Recover block. The only dataflow analysis so far implemented is SSA renaming, for which we make the following simplifying assumption: the Recover block only loads the NRPs and returns. This means we don't really need to analyze it, we can just skip the "lifting" of such NRPs. We also special-case the Recover block in the dominance computation. Rejected alternative approaches: - Specifying a Recover block for every defer instruction (like a traditional exception handler). This seemed like excessive generality, since Go programs only need the same degenerate form of Recover block. - Adding an instruction to set the Recover block immediately after the named return values are set up, so that dominance can be computed without special-casing. This didn't seem worth the effort. Interpreter: - This CL completely reimplements the panic/recover/ defer logic in the interpreter. It's clearer and simpler and closer to the model in the spec. - Some runtime panic messages have been changed to be closer to gc's, since tests depend on it. - The interpreter now requires that the runtime.runtimeError type be part of the SSA program. This requires that clients import this package prior to invoking the interpreter. This in turn requires (Importer).ImportPackage(path string), which this CL adds. - All $GOROOT/test/recover{,1,2,3}.go tests are now passing. NB, the bug described in coverage.go (defer/recover in a concatenated init function) remains. Will be fixed in a follow-up. Fixes golang/go#6381 R=gri CC=crawshaw, golang-dev https://golang.org/cl/13844043
2013-10-14 13:38:56 -06:00
}
// Load, parse and type-check the whole program.
iprog, err := conf.Load()
if err != nil {
return err
go.tools/importer: generalize command-line syntax. Motivation: pointer analysis tools (like the oracle) want the user to specify a set of initial packages, like 'go test'. This change enables the user to specify a set of packages on the command line using importer.LoadInitialPackages(args). Each argument is interpreted as either: - a comma-separated list of *.go source files together comprising one non-importable ad-hoc package. e.g. "src/pkg/net/http/triv.go" gives us [main]. - an import path, denoting both the imported package and its non-importable external test package, if any. e.g. "fmt" gives us [fmt, fmt_test]. Current type-checker limitations mean that only the first import path may contribute tests: multiple packages augmented by *_test.go files could create import cycles, which 'go test' avoids by building a separate executable for each one. That approach is less attractive for static analysis. Details: (many files touched, but importer.go is the crux) importer: - PackageInfo.Importable boolean indicates whether package is importable. - un-expose Importer.Packages; expose AllPackages() instead. - CreatePackageFromArgs has become LoadInitialPackages. - imports() moved to util.go, renamed importsOf(). - InitialPackagesUsage usage message exported to clients. - the package name for ad-hoc packages now comes from the 'package' decl, not "main". ssa.Program: - added CreatePackages() method - PackagesByPath un-exposed, renamed 'imported'. - expose AllPackages and ImportedPackage accessors. oracle: - describe: explain and workaround a go/types bug. Misc: - Removed various unnecessary error.Error() calls in Printf args. R=crawshaw CC=golang-dev https://golang.org/cl/13579043
2013-09-06 16:13:57 -06:00
}
// Create and build SSA-form program representation.
prog := ssautil.CreateProgram(iprog, *modeFlag)
// Build and display only the initial packages
// (and synthetic wrappers), unless -run is specified.
for _, info := range iprog.InitialPackages() {
prog.Package(info.Pkg).Build()
}
// Run the interpreter.
if *runFlag {
prog.BuildAll()
go.tools/importer: generalize command-line syntax. Motivation: pointer analysis tools (like the oracle) want the user to specify a set of initial packages, like 'go test'. This change enables the user to specify a set of packages on the command line using importer.LoadInitialPackages(args). Each argument is interpreted as either: - a comma-separated list of *.go source files together comprising one non-importable ad-hoc package. e.g. "src/pkg/net/http/triv.go" gives us [main]. - an import path, denoting both the imported package and its non-importable external test package, if any. e.g. "fmt" gives us [fmt, fmt_test]. Current type-checker limitations mean that only the first import path may contribute tests: multiple packages augmented by *_test.go files could create import cycles, which 'go test' avoids by building a separate executable for each one. That approach is less attractive for static analysis. Details: (many files touched, but importer.go is the crux) importer: - PackageInfo.Importable boolean indicates whether package is importable. - un-expose Importer.Packages; expose AllPackages() instead. - CreatePackageFromArgs has become LoadInitialPackages. - imports() moved to util.go, renamed importsOf(). - InitialPackagesUsage usage message exported to clients. - the package name for ad-hoc packages now comes from the 'package' decl, not "main". ssa.Program: - added CreatePackages() method - PackagesByPath un-exposed, renamed 'imported'. - expose AllPackages and ImportedPackage accessors. oracle: - describe: explain and workaround a go/types bug. Misc: - Removed various unnecessary error.Error() calls in Printf args. R=crawshaw CC=golang-dev https://golang.org/cl/13579043
2013-09-06 16:13:57 -06:00
var main *ssa.Package
pkgs := prog.AllPackages()
if *testFlag {
// If -test, run all packages' tests.
if len(pkgs) > 0 {
main = prog.CreateTestMainPackage(pkgs...)
}
if main == nil {
return fmt.Errorf("no tests")
}
} else {
// Otherwise, run main.main.
for _, pkg := range pkgs {
if pkg.Object.Name() == "main" {
main = pkg
if main.Func("main") == nil {
return fmt.Errorf("no func main() in main package")
}
break
}
}
if main == nil {
return fmt.Errorf("no main package")
go.tools/importer: generalize command-line syntax. Motivation: pointer analysis tools (like the oracle) want the user to specify a set of initial packages, like 'go test'. This change enables the user to specify a set of packages on the command line using importer.LoadInitialPackages(args). Each argument is interpreted as either: - a comma-separated list of *.go source files together comprising one non-importable ad-hoc package. e.g. "src/pkg/net/http/triv.go" gives us [main]. - an import path, denoting both the imported package and its non-importable external test package, if any. e.g. "fmt" gives us [fmt, fmt_test]. Current type-checker limitations mean that only the first import path may contribute tests: multiple packages augmented by *_test.go files could create import cycles, which 'go test' avoids by building a separate executable for each one. That approach is less attractive for static analysis. Details: (many files touched, but importer.go is the crux) importer: - PackageInfo.Importable boolean indicates whether package is importable. - un-expose Importer.Packages; expose AllPackages() instead. - CreatePackageFromArgs has become LoadInitialPackages. - imports() moved to util.go, renamed importsOf(). - InitialPackagesUsage usage message exported to clients. - the package name for ad-hoc packages now comes from the 'package' decl, not "main". ssa.Program: - added CreatePackages() method - PackagesByPath un-exposed, renamed 'imported'. - expose AllPackages and ImportedPackage accessors. oracle: - describe: explain and workaround a go/types bug. Misc: - Removed various unnecessary error.Error() calls in Printf args. R=crawshaw CC=golang-dev https://golang.org/cl/13579043
2013-09-06 16:13:57 -06:00
}
}
if runtime.GOARCH != build.Default.GOARCH {
return fmt.Errorf("cross-interpretation is not supported (target has GOARCH %s, interpreter has %s)",
build.Default.GOARCH, runtime.GOARCH)
}
interp.Interpret(main, interpMode, conf.TypeChecker.Sizes, main.Object.Path(), args)
}
return nil
}