Debian Codegraph @

go/analysis/passes/unsafeptr/unsafeptr.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 // Package unsafeptr defines an Analyzer that checks for invalid
6 // conversions of uintptr to unsafe.Pointer.
7 package unsafeptr
8
9 import (
10 _ "embed"
11 "go/ast"
12 "go/token"
13 "go/types"
14
15 "golang.org/x/tools/go/analysis"
16 "golang.org/x/tools/go/analysis/passes/inspect"
17 "golang.org/x/tools/go/ast/inspector"
18 "golang.org/x/tools/internal/analysis/analyzerutil"
19 "golang.org/x/tools/internal/typesinternal"
20 )
21
22 //go:embed doc.go
23 var doc string
24
25 var Analyzer = &analysis.Analyzer{
26 Name: "unsafeptr",
27 Doc: analyzerutil.MustExtractDoc(doc, "unsafeptr"),
28 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unsafeptr",
29 Requires: []*analysis.Analyzer{inspect.Analyzer},
30 Run: run,
31 }
32
33 func run(pass *analysis.Pass) (any, error) {
34 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
35
36 nodeFilter := []ast.Node{
37 (*ast.CallExpr)(nil),
38 (*ast.StarExpr)(nil),
39 (*ast.UnaryExpr)(nil),
40 }
41 inspect.Preorder(nodeFilter, func(n ast.Node) {
42 switch x := n.(type) {
43 case *ast.CallExpr:
44 if len(x.Args) == 1 &&
45 hasBasicType(pass.TypesInfo, x.Fun, types.UnsafePointer) &&
46 hasBasicType(pass.TypesInfo, x.Args[0], types.Uintptr) &&
47 !isSafeUintptr(pass.TypesInfo, x.Args[0]) {
48 pass.ReportRangef(x, "possible misuse of unsafe.Pointer")
49 }
50 case *ast.StarExpr:
51 if t := pass.TypesInfo.Types[x].Type; isReflectHeader(t) {
52 pass.ReportRangef(x, "possible misuse of %s", t)
53 }
54 case *ast.UnaryExpr:
55 if x.Op != token.AND {
56 return
57 }
58 if t := pass.TypesInfo.Types[x.X].Type; isReflectHeader(t) {
59 pass.ReportRangef(x, "possible misuse of %s", t)
60 }
61 }
62 })
63 return nil, nil
64 }
65
66 // isSafeUintptr reports whether x - already known to be a uintptr -
67 // is safe to convert to unsafe.Pointer.
68 func isSafeUintptr(info *types.Info, x ast.Expr) bool {
69 // Check unsafe.Pointer safety rules according to
70 // https://golang.org/pkg/unsafe/#Pointer.
71
72 switch x := ast.Unparen(x).(type) {
73 case *ast.SelectorExpr:
74 // "(6) Conversion of a reflect.SliceHeader or
75 // reflect.StringHeader Data field to or from Pointer."
76 if x.Sel.Name != "Data" {
77 break
78 }
79 // reflect.SliceHeader and reflect.StringHeader are okay,
80 // but only if they are pointing at a real slice or string.
81 // It's not okay to do:
82 // var x SliceHeader
83 // x.Data = uintptr(unsafe.Pointer(...))
84 // ... use x ...
85 // p := unsafe.Pointer(x.Data)
86 // because in the middle the garbage collector doesn't
87 // see x.Data as a pointer and so x.Data may be dangling
88 // by the time we get to the conversion at the end.
89 // For now approximate by saying that *Header is okay
90 // but Header is not.
91 pt, ok := types.Unalias(info.Types[x.X].Type).(*types.Pointer)
92 if ok && isReflectHeader(pt.Elem()) {
93 return true
94 }
95
96 case *ast.CallExpr:
97 // "(5) Conversion of the result of reflect.Value.Pointer or
98 // reflect.Value.UnsafeAddr from uintptr to Pointer."
99 if len(x.Args) != 0 {
100 break
101 }
102 sel, ok := x.Fun.(*ast.SelectorExpr)
103 if !ok {
104 break
105 }
106 switch sel.Sel.Name {
107 case "Pointer", "UnsafeAddr":
108 if typesinternal.IsTypeNamed(info.Types[sel.X].Type, "reflect", "Value") {
109 return true
110 }
111 }
112 }
113
114 // "(3) Conversion of a Pointer to a uintptr and back, with arithmetic."
115 return isSafeArith(info, x)
116 }
117
118 // isSafeArith reports whether x is a pointer arithmetic expression that is safe
119 // to convert to unsafe.Pointer.
120 func isSafeArith(info *types.Info, x ast.Expr) bool {
121 switch x := ast.Unparen(x).(type) {
122 case *ast.CallExpr:
123 // Base case: initial conversion from unsafe.Pointer to uintptr.
124 return len(x.Args) == 1 &&
125 hasBasicType(info, x.Fun, types.Uintptr) &&
126 hasBasicType(info, x.Args[0], types.UnsafePointer)
127
128 case *ast.BinaryExpr:
129 // "It is valid both to add and to subtract offsets from a
130 // pointer in this way. It is also valid to use &^ to round
131 // pointers, usually for alignment."
132 switch x.Op {
133 case token.ADD, token.SUB, token.AND_NOT:
134 // TODO(mdempsky): Match compiler
135 // semantics. ADD allows a pointer on either
136 // side; SUB and AND_NOT don't care about RHS.
137 return isSafeArith(info, x.X) && !isSafeArith(info, x.Y)
138 }
139 }
140
141 return false
142 }
143
144 // hasBasicType reports whether x's type is a types.Basic with the given kind.
145 func hasBasicType(info *types.Info, x ast.Expr, kind types.BasicKind) bool {
146 t := info.Types[x].Type
147 if t != nil {
148 t = t.Underlying()
149 }
150 b, ok := t.(*types.Basic)
151 return ok && b.Kind() == kind
152 }
153
154 // isReflectHeader reports whether t is reflect.SliceHeader or reflect.StringHeader.
155 func isReflectHeader(t types.Type) bool {
156 return typesinternal.IsTypeNamed(t, "reflect", "SliceHeader", "StringHeader")
157 }