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