Debian Codegraph @

cmd/callgraph/main.go

raw symbols SCIP
1 // Copyright 2014 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 // callgraph: a tool for reporting the call graph of a Go program.
6 // See Usage for details, or run with -help.
7 package main // import "golang.org/x/tools/cmd/callgraph"
8
9 // TODO(adonovan):
10 //
11 // Features:
12 // - restrict graph to a single package
13 // - output
14 // - functions reachable from root (use digraph tool?)
15 // - unreachable functions (use digraph tool?)
16 // - dynamic (runtime) types
17 // - indexed output (numbered nodes)
18 // - JSON output
19 // - additional template fields:
20 // callee file/line/col
21
22 import (
23 "bytes"
24 "flag"
25 "fmt"
26 "go/token"
27 "io"
28 "os"
29 "runtime"
30 "text/template"
31
32 "golang.org/x/tools/go/callgraph"
33 "golang.org/x/tools/go/callgraph/cha"
34 "golang.org/x/tools/go/callgraph/rta"
35 "golang.org/x/tools/go/callgraph/static"
36 "golang.org/x/tools/go/callgraph/vta"
37 "golang.org/x/tools/go/packages"
38 "golang.org/x/tools/go/ssa"
39 "golang.org/x/tools/go/ssa/ssautil"
40 )
41
42 // flags
43 var (
44 algoFlag = flag.String("algo", "rta",
45 `Call graph construction algorithm (static, cha, rta, vta)`)
46
47 testFlag = flag.Bool("test", false,
48 "Loads test code (*_test.go) for imported packages")
49
50 formatFlag = flag.String("format",
51 "{{.Caller}}\t--{{.Dynamic}}-{{.Line}}:{{.Column}}-->\t{{.Callee}}",
52 "A template expression specifying how to format an edge")
53
54 tagsFlag = flag.String("tags", "", "comma-separated list of extra build tags (see: go help buildconstraint)")
55 )
56
57 const Usage = `callgraph: display the call graph of a Go program.
58
59 Usage:
60
61 callgraph [-algo=static|cha|rta|vta] [-test] [-format=...] package...
62
63 Flags:
64
65 -algo Specifies the call-graph construction algorithm, one of:
66
67 static static calls only (unsound)
68 cha Class Hierarchy Analysis
69 rta Rapid Type Analysis
70 vta Variable Type Analysis
71
72 The algorithms are ordered by increasing precision in their
73 treatment of dynamic calls (and thus also computational cost).
74 RTA requires a whole program (main or test), and
75 include only functions reachable from main.
76
77 -test Include the package's tests in the analysis.
78
79 -format Specifies the format in which each call graph edge is displayed.
80 One of:
81
82 digraph output suitable for input to
83 golang.org/x/tools/cmd/digraph.
84 graphviz output in AT&T GraphViz (.dot) format.
85
86 All other values are interpreted using text/template syntax.
87 The default value is:
88
89 {{.Caller}}\t--{{.Dynamic}}-{{.Line}}:{{.Column}}-->\t{{.Callee}}
90
91 The structure passed to the template is (effectively):
92
93 type Edge struct {
94 Caller *ssa.Function // calling function
95 Callee *ssa.Function // called function
96
97 // Call site:
98 Filename string // containing file
99 Offset int // offset within file of '('
100 Line int // line number
101 Column int // column number of call
102 Dynamic string // "static" or "dynamic"
103 Description string // e.g. "static method call"
104 }
105
106 Caller and Callee are *ssa.Function values, which print as
107 "(*sync/atomic.Mutex).Lock", but other attributes may be
108 derived from them. For example:
109
110 - {{.Caller.Pkg.Pkg.Path}} yields the import path of the
111 enclosing package; and
112
113 - {{(.Caller.Prog.Fset.Position .Caller.Pos).Filename}}
114 yields the name of the file that declares the caller.
115
116 - The 'posn' template function returns the token.Position
117 of an ssa.Function, so the previous example can be
118 reduced to {{(posn .Caller).Filename}}.
119
120 Consult the documentation for go/token, text/template, and
121 golang.org/x/tools/go/ssa for more detail.
122
123 Examples:
124
125 Show the call graph of the trivial web server application:
126
127 callgraph -format digraph $GOROOT/src/net/http/triv.go
128
129 Same, but show only the packages of each function:
130
131 callgraph -format '{{.Caller.Pkg.Pkg.Path}} -> {{.Callee.Pkg.Pkg.Path}}' \
132 $GOROOT/src/net/http/triv.go | sort | uniq
133
134 Show functions that make dynamic calls into the 'fmt' test package,
135 using the Rapid Type Analysis algorithm:
136
137 callgraph -format='{{.Caller}} -{{.Dynamic}}-> {{.Callee}}' -test -algo=rta fmt |
138 sed -ne 's/-dynamic-/--/p' |
139 sed -ne 's/-->.*fmt_test.*$//p' | sort | uniq
140
141 Show all functions directly called by the callgraph tool's main function:
142
143 callgraph -format=digraph golang.org/x/tools/cmd/callgraph |
144 digraph succs golang.org/x/tools/cmd/callgraph.main
145 `
146
147 func init() {
148 // If $GOMAXPROCS isn't set, use the full capacity of the machine.
149 // For small machines, use at least 4 threads.
150 if os.Getenv("GOMAXPROCS") == "" {
151 n := max(runtime.NumCPU(), 4)
152 runtime.GOMAXPROCS(n)
153 }
154 }
155
156 func main() {
157 flag.Parse()
158 if err := doCallgraph("", "", *algoFlag, *formatFlag, *testFlag, flag.Args()); err != nil {
159 fmt.Fprintf(os.Stderr, "callgraph: %s\n", err)
160 os.Exit(1)
161 }
162 }
163
164 var stdout io.Writer = os.Stdout
165
166 func doCallgraph(dir, gopath, algo, format string, tests bool, args []string) error {
167 if len(args) == 0 {
168 fmt.Fprint(os.Stderr, Usage)
169 return nil
170 }
171
172 cfg := &packages.Config{
173 Mode: packages.LoadAllSyntax,
174 BuildFlags: []string{"-tags=" + *tagsFlag},
175 Tests: tests,
176 Dir: dir,
177 }
178 if gopath != "" {
179 cfg.Env = append(os.Environ(), "GOPATH="+gopath) // to enable testing
180 }
181 initial, err := packages.Load(cfg, args...)
182 if err != nil {
183 return err
184 }
185 if packages.PrintErrors(initial) > 0 {
186 return fmt.Errorf("packages contain errors")
187 }
188
189 // Create and build SSA-form program representation.
190 mode := ssa.InstantiateGenerics // instantiate generics by default for soundness
191 prog, pkgs := ssautil.AllPackages(initial, mode)
192 prog.Build()
193
194 // -- call graph construction ------------------------------------------
195
196 var cg *callgraph.Graph
197
198 switch algo {
199 case "static":
200 cg = static.CallGraph(prog)
201
202 case "cha":
203 cg = cha.CallGraph(prog)
204
205 case "pta":
206 return fmt.Errorf("pointer analysis is no longer supported (see Go issue #59676)")
207
208 case "rta":
209 mains, err := mainPackages(pkgs)
210 if err != nil {
211 return err
212 }
213 var roots []*ssa.Function
214 for _, main := range mains {
215 roots = append(roots, main.Func("init"), main.Func("main"))
216 }
217 rtares := rta.Analyze(roots, true)
218 cg = rtares.CallGraph
219
220 // NB: RTA gives us Reachable and RuntimeTypes too.
221
222 case "vta":
223 cg = vta.CallGraph(ssautil.AllFunctions(prog), nil)
224
225 default:
226 return fmt.Errorf("unknown algorithm: %s", algo)
227 }
228
229 cg.DeleteSyntheticNodes()
230
231 // -- output------------------------------------------------------------
232
233 var before, after string
234
235 // Pre-canned formats.
236 switch format {
237 case "digraph":
238 format = `{{printf "%q %q" .Caller .Callee}}`
239
240 case "graphviz":
241 before = "digraph callgraph {\n"
242 after = "}\n"
243 format = ` {{printf "%q" .Caller}} -> {{printf "%q" .Callee}}`
244 }
245
246 funcMap := template.FuncMap{
247 "posn": func(f *ssa.Function) token.Position {
248 return f.Prog.Fset.Position(f.Pos())
249 },
250 }
251 tmpl, err := template.New("-format").Funcs(funcMap).Parse(format)
252 if err != nil {
253 return fmt.Errorf("invalid -format template: %v", err)
254 }
255
256 // Allocate these once, outside the traversal.
257 var buf bytes.Buffer
258 data := Edge{fset: prog.Fset}
259
260 fmt.Fprint(stdout, before)
261 if err := callgraph.GraphVisitEdges(cg, func(edge *callgraph.Edge) error {
262 data.position.Offset = -1
263 data.edge = edge
264 data.Caller = edge.Caller.Func
265 data.Callee = edge.Callee.Func
266
267 buf.Reset()
268 if err := tmpl.Execute(&buf, &data); err != nil {
269 return err
270 }
271 stdout.Write(buf.Bytes())
272 if len := buf.Len(); len == 0 || buf.Bytes()[len-1] != '\n' {
273 fmt.Fprintln(stdout)
274 }
275 return nil
276 }); err != nil {
277 return err
278 }
279 fmt.Fprint(stdout, after)
280 return nil
281 }
282
283 // mainPackages returns the main packages to analyze.
284 // Each resulting package is named "main" and has a main function.
285 func mainPackages(pkgs []*ssa.Package) ([]*ssa.Package, error) {
286 var mains []*ssa.Package
287 for _, p := range pkgs {
288 if p != nil && p.Pkg.Name() == "main" && p.Func("main") != nil {
289 mains = append(mains, p)
290 }
291 }
292 if len(mains) == 0 {
293 return nil, fmt.Errorf("no main packages")
294 }
295 return mains, nil
296 }
297
298 type Edge struct {
299 Caller *ssa.Function
300 Callee *ssa.Function
301
302 edge *callgraph.Edge
303 fset *token.FileSet
304 position token.Position // initialized lazily
305 }
306
307 func (e *Edge) pos() *token.Position {
308 if e.position.Offset == -1 {
309 e.position = e.fset.Position(e.edge.Pos()) // called lazily
310 }
311 return &e.position
312 }
313
314 func (e *Edge) Filename() string { return e.pos().Filename }
315 func (e *Edge) Column() int { return e.pos().Column }
316 func (e *Edge) Line() int { return e.pos().Line }
317 func (e *Edge) Offset() int { return e.pos().Offset }
318
319 func (e *Edge) Dynamic() string {
320 if e.edge.Site != nil && e.edge.Site.Common().StaticCallee() == nil {
321 return "dynamic"
322 }
323 return "static"
324 }
325
326 func (e *Edge) Description() string { return e.edge.Description() }