You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

195 lines
5.2 KiB

  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. package main
  5. import (
  6. "fmt"
  7. "go/token"
  8. "go/types"
  9. "golang.org/x/tools/cmd/guru/serial"
  10. "golang.org/x/tools/go/callgraph"
  11. "golang.org/x/tools/go/loader"
  12. "golang.org/x/tools/go/ssa"
  13. "golang.org/x/tools/go/ssa/ssautil"
  14. )
  15. // Callers reports the possible callers of the function
  16. // immediately enclosing the specified source location.
  17. //
  18. func callers(q *Query) error {
  19. lconf := loader.Config{Build: q.Build}
  20. if err := setPTAScope(&lconf, q.Scope); err != nil {
  21. return err
  22. }
  23. // Load/parse/type-check the program.
  24. lprog, err := loadWithSoftErrors(&lconf)
  25. if err != nil {
  26. return err
  27. }
  28. qpos, err := parseQueryPos(lprog, q.Pos, false)
  29. if err != nil {
  30. return err
  31. }
  32. prog := ssautil.CreateProgram(lprog, 0)
  33. ptaConfig, err := setupPTA(prog, lprog, q.PTALog, q.Reflection)
  34. if err != nil {
  35. return err
  36. }
  37. pkg := prog.Package(qpos.info.Pkg)
  38. if pkg == nil {
  39. return fmt.Errorf("no SSA package")
  40. }
  41. if !ssa.HasEnclosingFunction(pkg, qpos.path) {
  42. return fmt.Errorf("this position is not inside a function")
  43. }
  44. // Defer SSA construction till after errors are reported.
  45. prog.Build()
  46. target := ssa.EnclosingFunction(pkg, qpos.path)
  47. if target == nil {
  48. return fmt.Errorf("no SSA function built for this location (dead code?)")
  49. }
  50. // If the function is never address-taken, all calls are direct
  51. // and can be found quickly by inspecting the whole SSA program.
  52. cg := directCallsTo(target, entryPoints(ptaConfig.Mains))
  53. if cg == nil {
  54. // Run the pointer analysis, recording each
  55. // call found to originate from target.
  56. // (Pointer analysis may return fewer results than
  57. // directCallsTo because it ignores dead code.)
  58. ptaConfig.BuildCallGraph = true
  59. cg = ptrAnalysis(ptaConfig).CallGraph
  60. }
  61. cg.DeleteSyntheticNodes()
  62. edges := cg.CreateNode(target).In
  63. // TODO(adonovan): sort + dedup calls to ensure test determinism.
  64. q.Output(lprog.Fset, &callersResult{
  65. target: target,
  66. callgraph: cg,
  67. edges: edges,
  68. })
  69. return nil
  70. }
  71. // directCallsTo inspects the whole program and returns a callgraph
  72. // containing edges for all direct calls to the target function.
  73. // directCallsTo returns nil if the function is ever address-taken.
  74. func directCallsTo(target *ssa.Function, entrypoints []*ssa.Function) *callgraph.Graph {
  75. cg := callgraph.New(nil) // use nil as root *Function
  76. targetNode := cg.CreateNode(target)
  77. // Is the function a program entry point?
  78. // If so, add edge from callgraph root.
  79. for _, f := range entrypoints {
  80. if f == target {
  81. callgraph.AddEdge(cg.Root, nil, targetNode)
  82. }
  83. }
  84. // Find receiver type (for methods).
  85. var recvType types.Type
  86. if recv := target.Signature.Recv(); recv != nil {
  87. recvType = recv.Type()
  88. }
  89. // Find all direct calls to function,
  90. // or a place where its address is taken.
  91. var space [32]*ssa.Value // preallocate
  92. for fn := range ssautil.AllFunctions(target.Prog) {
  93. for _, b := range fn.Blocks {
  94. for _, instr := range b.Instrs {
  95. // Is this a method (T).f of a concrete type T
  96. // whose runtime type descriptor is address-taken?
  97. // (To be fully sound, we would have to check that
  98. // the type doesn't make it to reflection as a
  99. // subelement of some other address-taken type.)
  100. if recvType != nil {
  101. if mi, ok := instr.(*ssa.MakeInterface); ok {
  102. if types.Identical(mi.X.Type(), recvType) {
  103. return nil // T is address-taken
  104. }
  105. if ptr, ok := mi.X.Type().(*types.Pointer); ok &&
  106. types.Identical(ptr.Elem(), recvType) {
  107. return nil // *T is address-taken
  108. }
  109. }
  110. }
  111. // Direct call to target?
  112. rands := instr.Operands(space[:0])
  113. if site, ok := instr.(ssa.CallInstruction); ok &&
  114. site.Common().Value == target {
  115. callgraph.AddEdge(cg.CreateNode(fn), site, targetNode)
  116. rands = rands[1:] // skip .Value (rands[0])
  117. }
  118. // Address-taken?
  119. for _, rand := range rands {
  120. if rand != nil && *rand == target {
  121. return nil
  122. }
  123. }
  124. }
  125. }
  126. }
  127. return cg
  128. }
  129. func entryPoints(mains []*ssa.Package) []*ssa.Function {
  130. var entrypoints []*ssa.Function
  131. for _, pkg := range mains {
  132. entrypoints = append(entrypoints, pkg.Func("init"))
  133. if main := pkg.Func("main"); main != nil && pkg.Pkg.Name() == "main" {
  134. entrypoints = append(entrypoints, main)
  135. }
  136. }
  137. return entrypoints
  138. }
  139. type callersResult struct {
  140. target *ssa.Function
  141. callgraph *callgraph.Graph
  142. edges []*callgraph.Edge
  143. }
  144. func (r *callersResult) PrintPlain(printf printfFunc) {
  145. root := r.callgraph.Root
  146. if r.edges == nil {
  147. printf(r.target, "%s is not reachable in this program.", r.target)
  148. } else {
  149. printf(r.target, "%s is called from these %d sites:", r.target, len(r.edges))
  150. for _, edge := range r.edges {
  151. if edge.Caller == root {
  152. printf(r.target, "the root of the call graph")
  153. } else {
  154. printf(edge, "\t%s from %s", edge.Description(), edge.Caller.Func)
  155. }
  156. }
  157. }
  158. }
  159. func (r *callersResult) JSON(fset *token.FileSet) []byte {
  160. var callers []serial.Caller
  161. for _, edge := range r.edges {
  162. callers = append(callers, serial.Caller{
  163. Caller: edge.Caller.Func.String(),
  164. Pos: fset.Position(edge.Pos()).String(),
  165. Desc: edge.Description(),
  166. })
  167. }
  168. return toJSON(callers)
  169. }