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.

290 lines
8.1 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/ast"
  8. "go/token"
  9. "go/types"
  10. "sort"
  11. "golang.org/x/tools/cmd/guru/serial"
  12. "golang.org/x/tools/go/ast/astutil"
  13. "golang.org/x/tools/go/loader"
  14. "golang.org/x/tools/go/pointer"
  15. "golang.org/x/tools/go/ssa"
  16. "golang.org/x/tools/go/ssa/ssautil"
  17. )
  18. // pointsto runs the pointer analysis on the selected expression,
  19. // and reports its points-to set (for a pointer-like expression)
  20. // or its dynamic types (for an interface, reflect.Value, or
  21. // reflect.Type expression) and their points-to sets.
  22. //
  23. // All printed sets are sorted to ensure determinism.
  24. //
  25. func pointsto(q *Query) error {
  26. lconf := loader.Config{Build: q.Build}
  27. if err := setPTAScope(&lconf, q.Scope); err != nil {
  28. return err
  29. }
  30. // Load/parse/type-check the program.
  31. lprog, err := loadWithSoftErrors(&lconf)
  32. if err != nil {
  33. return err
  34. }
  35. qpos, err := parseQueryPos(lprog, q.Pos, true) // needs exact pos
  36. if err != nil {
  37. return err
  38. }
  39. prog := ssautil.CreateProgram(lprog, ssa.GlobalDebug)
  40. ptaConfig, err := setupPTA(prog, lprog, q.PTALog, q.Reflection)
  41. if err != nil {
  42. return err
  43. }
  44. path, action := findInterestingNode(qpos.info, qpos.path)
  45. if action != actionExpr {
  46. return fmt.Errorf("pointer analysis wants an expression; got %s",
  47. astutil.NodeDescription(qpos.path[0]))
  48. }
  49. var expr ast.Expr
  50. var obj types.Object
  51. switch n := path[0].(type) {
  52. case *ast.ValueSpec:
  53. // ambiguous ValueSpec containing multiple names
  54. return fmt.Errorf("multiple value specification")
  55. case *ast.Ident:
  56. obj = qpos.info.ObjectOf(n)
  57. expr = n
  58. case ast.Expr:
  59. expr = n
  60. default:
  61. // TODO(adonovan): is this reachable?
  62. return fmt.Errorf("unexpected AST for expr: %T", n)
  63. }
  64. // Reject non-pointerlike types (includes all constants---except nil).
  65. // TODO(adonovan): reject nil too.
  66. typ := qpos.info.TypeOf(expr)
  67. if !pointer.CanPoint(typ) {
  68. return fmt.Errorf("pointer analysis wants an expression of reference type; got %s", typ)
  69. }
  70. // Determine the ssa.Value for the expression.
  71. var value ssa.Value
  72. var isAddr bool
  73. if obj != nil {
  74. // def/ref of func/var object
  75. value, isAddr, err = ssaValueForIdent(prog, qpos.info, obj, path)
  76. } else {
  77. value, isAddr, err = ssaValueForExpr(prog, qpos.info, path)
  78. }
  79. if err != nil {
  80. return err // e.g. trivially dead code
  81. }
  82. // Defer SSA construction till after errors are reported.
  83. prog.Build()
  84. // Run the pointer analysis.
  85. ptrs, err := runPTA(ptaConfig, value, isAddr)
  86. if err != nil {
  87. return err // e.g. analytically unreachable
  88. }
  89. q.Output(lprog.Fset, &pointstoResult{
  90. qpos: qpos,
  91. typ: typ,
  92. ptrs: ptrs,
  93. })
  94. return nil
  95. }
  96. // ssaValueForIdent returns the ssa.Value for the ast.Ident whose path
  97. // to the root of the AST is path. isAddr reports whether the
  98. // ssa.Value is the address denoted by the ast.Ident, not its value.
  99. //
  100. func ssaValueForIdent(prog *ssa.Program, qinfo *loader.PackageInfo, obj types.Object, path []ast.Node) (value ssa.Value, isAddr bool, err error) {
  101. switch obj := obj.(type) {
  102. case *types.Var:
  103. pkg := prog.Package(qinfo.Pkg)
  104. pkg.Build()
  105. if v, addr := prog.VarValue(obj, pkg, path); v != nil {
  106. return v, addr, nil
  107. }
  108. return nil, false, fmt.Errorf("can't locate SSA Value for var %s", obj.Name())
  109. case *types.Func:
  110. fn := prog.FuncValue(obj)
  111. if fn == nil {
  112. return nil, false, fmt.Errorf("%s is an interface method", obj)
  113. }
  114. // TODO(adonovan): there's no point running PTA on a *Func ident.
  115. // Eliminate this feature.
  116. return fn, false, nil
  117. }
  118. panic(obj)
  119. }
  120. // ssaValueForExpr returns the ssa.Value of the non-ast.Ident
  121. // expression whose path to the root of the AST is path.
  122. //
  123. func ssaValueForExpr(prog *ssa.Program, qinfo *loader.PackageInfo, path []ast.Node) (value ssa.Value, isAddr bool, err error) {
  124. pkg := prog.Package(qinfo.Pkg)
  125. pkg.SetDebugMode(true)
  126. pkg.Build()
  127. fn := ssa.EnclosingFunction(pkg, path)
  128. if fn == nil {
  129. return nil, false, fmt.Errorf("no SSA function built for this location (dead code?)")
  130. }
  131. if v, addr := fn.ValueForExpr(path[0].(ast.Expr)); v != nil {
  132. return v, addr, nil
  133. }
  134. return nil, false, fmt.Errorf("can't locate SSA Value for expression in %s", fn)
  135. }
  136. // runPTA runs the pointer analysis of the selected SSA value or address.
  137. func runPTA(conf *pointer.Config, v ssa.Value, isAddr bool) (ptrs []pointerResult, err error) {
  138. T := v.Type()
  139. if isAddr {
  140. conf.AddIndirectQuery(v)
  141. T = deref(T)
  142. } else {
  143. conf.AddQuery(v)
  144. }
  145. ptares := ptrAnalysis(conf)
  146. var ptr pointer.Pointer
  147. if isAddr {
  148. ptr = ptares.IndirectQueries[v]
  149. } else {
  150. ptr = ptares.Queries[v]
  151. }
  152. if ptr == (pointer.Pointer{}) {
  153. return nil, fmt.Errorf("pointer analysis did not find expression (dead code?)")
  154. }
  155. pts := ptr.PointsTo()
  156. if pointer.CanHaveDynamicTypes(T) {
  157. // Show concrete types for interface/reflect.Value expression.
  158. if concs := pts.DynamicTypes(); concs.Len() > 0 {
  159. concs.Iterate(func(conc types.Type, pta interface{}) {
  160. labels := pta.(pointer.PointsToSet).Labels()
  161. sort.Sort(byPosAndString(labels)) // to ensure determinism
  162. ptrs = append(ptrs, pointerResult{conc, labels})
  163. })
  164. }
  165. } else {
  166. // Show labels for other expressions.
  167. labels := pts.Labels()
  168. sort.Sort(byPosAndString(labels)) // to ensure determinism
  169. ptrs = append(ptrs, pointerResult{T, labels})
  170. }
  171. sort.Sort(byTypeString(ptrs)) // to ensure determinism
  172. return ptrs, nil
  173. }
  174. type pointerResult struct {
  175. typ types.Type // type of the pointer (always concrete)
  176. labels []*pointer.Label // set of labels
  177. }
  178. type pointstoResult struct {
  179. qpos *queryPos
  180. typ types.Type // type of expression
  181. ptrs []pointerResult // pointer info (typ is concrete => len==1)
  182. }
  183. func (r *pointstoResult) PrintPlain(printf printfFunc) {
  184. if pointer.CanHaveDynamicTypes(r.typ) {
  185. // Show concrete types for interface, reflect.Type or
  186. // reflect.Value expression.
  187. if len(r.ptrs) > 0 {
  188. printf(r.qpos, "this %s may contain these dynamic types:", r.qpos.typeString(r.typ))
  189. for _, ptr := range r.ptrs {
  190. var obj types.Object
  191. if nt, ok := deref(ptr.typ).(*types.Named); ok {
  192. obj = nt.Obj()
  193. }
  194. if len(ptr.labels) > 0 {
  195. printf(obj, "\t%s, may point to:", r.qpos.typeString(ptr.typ))
  196. printLabels(printf, ptr.labels, "\t\t")
  197. } else {
  198. printf(obj, "\t%s", r.qpos.typeString(ptr.typ))
  199. }
  200. }
  201. } else {
  202. printf(r.qpos, "this %s cannot contain any dynamic types.", r.typ)
  203. }
  204. } else {
  205. // Show labels for other expressions.
  206. if ptr := r.ptrs[0]; len(ptr.labels) > 0 {
  207. printf(r.qpos, "this %s may point to these objects:",
  208. r.qpos.typeString(r.typ))
  209. printLabels(printf, ptr.labels, "\t")
  210. } else {
  211. printf(r.qpos, "this %s may not point to anything.",
  212. r.qpos.typeString(r.typ))
  213. }
  214. }
  215. }
  216. func (r *pointstoResult) JSON(fset *token.FileSet) []byte {
  217. var pts []serial.PointsTo
  218. for _, ptr := range r.ptrs {
  219. var namePos string
  220. if nt, ok := deref(ptr.typ).(*types.Named); ok {
  221. namePos = fset.Position(nt.Obj().Pos()).String()
  222. }
  223. var labels []serial.PointsToLabel
  224. for _, l := range ptr.labels {
  225. labels = append(labels, serial.PointsToLabel{
  226. Pos: fset.Position(l.Pos()).String(),
  227. Desc: l.String(),
  228. })
  229. }
  230. pts = append(pts, serial.PointsTo{
  231. Type: r.qpos.typeString(ptr.typ),
  232. NamePos: namePos,
  233. Labels: labels,
  234. })
  235. }
  236. return toJSON(pts)
  237. }
  238. type byTypeString []pointerResult
  239. func (a byTypeString) Len() int { return len(a) }
  240. func (a byTypeString) Less(i, j int) bool { return a[i].typ.String() < a[j].typ.String() }
  241. func (a byTypeString) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  242. type byPosAndString []*pointer.Label
  243. func (a byPosAndString) Len() int { return len(a) }
  244. func (a byPosAndString) Less(i, j int) bool {
  245. cmp := a[i].Pos() - a[j].Pos()
  246. return cmp < 0 || (cmp == 0 && a[i].String() < a[j].String())
  247. }
  248. func (a byPosAndString) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  249. func printLabels(printf printfFunc, labels []*pointer.Label, prefix string) {
  250. // TODO(adonovan): due to context-sensitivity, many of these
  251. // labels may differ only by context, which isn't apparent.
  252. for _, label := range labels {
  253. printf(label, "%s%s", prefix, label)
  254. }
  255. }