Debian Codegraph @

cmd/ssadump/main.go

raw symbols SCIP
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 // ssadump: a tool for displaying and interpreting the SSA form of Go programs.
6 package main // import "golang.org/x/tools/cmd/ssadump"
7
8 import (
9 "flag"
10 "fmt"
11 "go/build"
12 "go/types"
13 "os"
14 "runtime"
15 "runtime/pprof"
16
17 "golang.org/x/tools/go/packages"
18 "golang.org/x/tools/go/ssa"
19 "golang.org/x/tools/go/ssa/interp"
20 "golang.org/x/tools/go/ssa/ssautil"
21 )
22
23 // flags
24 var (
25 mode = ssa.BuilderMode(0)
26
27 testFlag = flag.Bool("test", false, "include implicit test packages and executables")
28
29 runFlag = flag.Bool("run", false, "interpret the SSA program")
30
31 interpFlag = flag.String("interp", "", `Options controlling the SSA test interpreter.
32 The value is a sequence of zero or more more of these letters:
33 R disable [R]ecover() from panic; show interpreter crash instead.
34 T [T]race execution of the program. Best for single-threaded programs!
35 `)
36
37 cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
38
39 args stringListValue
40
41 tagsFlag = flag.String("tags", "", "comma-separated list of extra build tags (see: go help buildconstraint)")
42 )
43
44 func init() {
45 flag.Var(&mode, "build", ssa.BuilderModeDoc)
46 flag.Var(&args, "arg", "add argument to interpreted program")
47 }
48
49 const usage = `SSA builder and interpreter.
50 Usage: ssadump [-build=[DBCSNFLG]] [-test] [-run] [-interp=[TR]] [-arg=...] package...
51 Use -help flag to display options.
52
53 Examples:
54 % ssadump -build=F hello.go # dump SSA form of a single package
55 % ssadump -build=F -test fmt # dump SSA form of a package and its tests
56 % ssadump -run -interp=T hello.go # interpret a program, with tracing
57
58 The -run flag causes ssadump to build the code in a runnable form and run the first
59 package named main.
60
61 Interpretation of the standard "testing" package is no longer supported.
62 `
63
64 func main() {
65 if err := doMain(); err != nil {
66 fmt.Fprintf(os.Stderr, "ssadump: %s\n", err)
67 os.Exit(1)
68 }
69 }
70
71 func doMain() error {
72 flag.Parse()
73 if len(flag.Args()) == 0 {
74 fmt.Fprint(os.Stderr, usage)
75 os.Exit(1)
76 }
77
78 cfg := &packages.Config{
79 BuildFlags: []string{"-tags=" + *tagsFlag},
80 Mode: packages.LoadSyntax,
81 Tests: *testFlag,
82 }
83
84 // Choose types.Sizes from conf.Build.
85 // TODO(adonovan): remove this when go/packages provides a better way.
86 var wordSize int64 = 8
87 switch build.Default.GOARCH {
88 case "386", "arm":
89 wordSize = 4
90 }
91 sizes := &types.StdSizes{
92 MaxAlign: 8,
93 WordSize: wordSize,
94 }
95
96 var interpMode interp.Mode
97 for _, c := range *interpFlag {
98 switch c {
99 case 'T':
100 interpMode |= interp.EnableTracing
101 case 'R':
102 interpMode |= interp.DisableRecover
103 default:
104 return fmt.Errorf("unknown -interp option: '%c'", c)
105 }
106 }
107
108 // Profiling support.
109 if *cpuprofile != "" {
110 f, err := os.Create(*cpuprofile)
111 if err != nil {
112 fmt.Fprintln(os.Stderr, err)
113 os.Exit(1)
114 }
115 pprof.StartCPUProfile(f)
116 defer pprof.StopCPUProfile()
117 }
118
119 // Load, parse and type-check the initial packages,
120 // and, if -run, their dependencies.
121 if *runFlag {
122 cfg.Mode = packages.LoadAllSyntax
123 }
124 initial, err := packages.Load(cfg, flag.Args()...)
125 if err != nil {
126 return err
127 }
128 if len(initial) == 0 {
129 return fmt.Errorf("no packages")
130 }
131 if packages.PrintErrors(initial) > 0 {
132 return fmt.Errorf("packages contain errors")
133 }
134
135 if !*runFlag {
136 // Create (and display) SSA only for initial packages and wrappers.
137 _, pkgs := ssautil.Packages(initial, mode)
138 for i, p := range pkgs {
139 if p == nil {
140 return fmt.Errorf("cannot build SSA for package %s", initial[i])
141 }
142 p.Build()
143 }
144
145 } else {
146 // Create SSA for initial packages and all dependencies, instantiating generics.
147 mode |= ssa.InstantiateGenerics
148
149 // TODO(adonovan): opt: use noreturn analysis over transitive
150 // dependencies to prune spurious control flow graph edges.
151
152 prog, pkgs := ssautil.AllPackages(initial, mode)
153 for i, p := range pkgs {
154 if p == nil {
155 return fmt.Errorf("cannot build SSA for package %s", initial[i])
156 }
157 }
158
159 // Run the interpreter.
160 // Build SSA for all packages.
161 prog.Build()
162
163 // Earlier versions of the interpreter needed the runtime
164 // package; however, interp cannot handle unsafe constructs
165 // used during runtime's package initialization at the moment.
166 // The key construct blocking support is:
167 // *((*T)(unsafe.Pointer(p)))
168 // Unfortunately, this means only trivial programs can be
169 // interpreted by ssadump.
170 if prog.ImportedPackage("runtime") != nil {
171 return fmt.Errorf("-run: program depends on runtime package (interpreter can run only trivial programs)")
172 }
173
174 if runtime.GOARCH != build.Default.GOARCH {
175 return fmt.Errorf("cross-interpretation is not supported (target has GOARCH %s, interpreter has %s)",
176 build.Default.GOARCH, runtime.GOARCH)
177 }
178
179 // Run first main package.
180 for _, main := range ssautil.MainPackages(pkgs) {
181 fmt.Fprintf(os.Stderr, "Running: %s\n", main.Pkg.Path())
182 os.Exit(interp.Interpret(main, interpMode, sizes, main.Pkg.Path(), args))
183 }
184 return fmt.Errorf("no main package")
185 }
186 return nil
187 }
188
189 // stringListValue is a flag.Value that accumulates strings.
190 // e.g. --flag=one --flag=two would produce []string{"one", "two"}.
191 type stringListValue []string
192
193 func (ss *stringListValue) Get() any { return []string(*ss) }
194
195 func (ss *stringListValue) String() string { return fmt.Sprintf("%q", *ss) }
196
197 func (ss *stringListValue) Set(s string) error { *ss = append(*ss, s); return nil }