Debian Codegraph @

staticcheck/sa5011/sa5011.go

raw
1 package sa5011
2
3 import (
4 "go/types"
5
6 "honnef.co/go/tools/analysis/lint"
7 "honnef.co/go/tools/analysis/report"
8 "honnef.co/go/tools/go/ir"
9 "honnef.co/go/tools/go/types/typeutil"
10 "honnef.co/go/tools/internal/passes/buildir"
11
12 "golang.org/x/tools/go/analysis"
13 )
14
15 var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
16 Analyzer: &analysis.Analyzer{
17 Name: "SA5011",
18 Run: run,
19 Requires: []*analysis.Analyzer{buildir.Analyzer},
20 },
21 Doc: &lint.RawDocumentation{
22 Title: `Possible nil pointer dereference`,
23
24 Text: `A pointer is being dereferenced unconditionally, while
25 also being checked against nil in another place. This suggests that
26 the pointer may be nil and dereferencing it may panic. This is
27 commonly a result of improperly ordered code or missing return
28 statements. Consider the following examples:
29
30 func fn(x *int) {
31 fmt.Println(*x)
32
33 // This nil check is equally important for the previous dereference
34 if x != nil {
35 foo(*x)
36 }
37 }
38
39 func TestFoo(t *testing.T) {
40 x := compute()
41 if x == nil {
42 t.Errorf("nil pointer received")
43 }
44
45 // t.Errorf does not abort the test, so if x is nil, the next line will panic.
46 foo(*x)
47 }
48
49 Staticcheck tries to deduce which functions abort control flow.
50 For example, it is aware that a function will not continue
51 execution after a call to \'panic\' or \'log.Fatal\'. However, sometimes
52 this detection fails, in particular in the presence of
53 conditionals. Consider the following example:
54
55 func Log(msg string, level int) {
56 fmt.Println(msg)
57 if level == levelFatal {
58 os.Exit(1)
59 }
60 }
61
62 func Fatal(msg string) {
63 Log(msg, levelFatal)
64 }
65
66 func fn(x *int) {
67 if x == nil {
68 Fatal("unexpected nil pointer")
69 }
70 fmt.Println(*x)
71 }
72
73 Staticcheck will flag the dereference of \'x\', even though it is perfectly
74 safe. Staticcheck is not able to deduce that a call to
75 Fatal will exit the program. For the time being, the easiest
76 workaround is to modify the definition of Fatal like so:
77
78 func Fatal(msg string) {
79 Log(msg, levelFatal)
80 panic("unreachable")
81 }
82
83 We also hard-code functions from common logging packages such as
84 logrus. Please file an issue if we're missing support for a
85 popular package.`,
86 Since: "2020.1",
87 Severity: lint.SeverityWarning,
88 MergeIf: lint.MergeIfAny,
89 },
90 })
91
92 var Analyzer = SCAnalyzer.Analyzer
93
94 func run(pass *analysis.Pass) (any, error) {
95 if true { // branch to shut up go vet's unreachable code detection.
96 panic("SA5011 is broken and should not be used")
97 }
98
99 // This is an extremely trivial check that doesn't try to reason
100 // about control flow. That is, phis and sigmas do not propagate
101 // any information. As such, we can flag this:
102 //
103 // _ = *x
104 // if x == nil { return }
105 //
106 // but we cannot flag this:
107 //
108 // if x == nil { println(x) }
109 // _ = *x
110 //
111 // but we can flag this, because the if's body doesn't use x:
112 //
113 // if x == nil { println("this is bad") }
114 // _ = *x
115 //
116 // nor many other variations of conditional uses of or assignments to x.
117 //
118 // However, even this trivial implementation finds plenty of
119 // real-world bugs, such as dereference before nil pointer check,
120 // or using t.Error instead of t.Fatal when encountering nil
121 // pointers.
122 //
123 // On the flip side, our naive implementation avoids false positives in branches, such as
124 //
125 // if x != nil { _ = *x }
126 //
127 // due to the same lack of propagating information through sigma
128 // nodes. x inside the branch will be independent of the x in the
129 // nil pointer check.
130 //
131 //
132 // We could implement a more powerful check, but then we'd be
133 // getting false positives instead of false negatives because
134 // we're incapable of deducing relationships between variables.
135 // For example, a function might return a pointer and an error,
136 // and the error being nil guarantees that the pointer is not nil.
137 // Depending on the surrounding code, the pointer may still end up
138 // being checked against nil in one place, and guarded by a check
139 // on the error in another, which would lead to us marking some
140 // loads as unsafe.
141 //
142 // Unfortunately, simply hard-coding the relationship between
143 // return values wouldn't eliminate all false positives, either.
144 // Many other more subtle relationships exist. An abridged example
145 // from real code:
146 //
147 // if a == nil && b == nil { return }
148 // c := fn(a)
149 // if c != "" { _ = *a }
150 //
151 // where `fn` is guaranteed to return a non-empty string if a
152 // isn't nil.
153 //
154 // We choose to err on the side of false negatives.
155
156 isNilConst := func(v ir.Value) bool {
157 if typeutil.MaybePointerLike(v.Type()) {
158 if k, ok := v.(*ir.Const); ok {
159 return k.IsNil()
160 }
161 }
162 return false
163 }
164
165 for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs {
166 maybeNil := map[ir.Value]ir.Instruction{}
167 for _, b := range fn.Blocks {
168 for _, instr := range b.Instrs {
169 // Originally we looked at all ir.BinOp, but that would lead to calls like 'assert(x != nil)' causing false positives.
170 // Restrict ourselves to actual if statements, as these are more likely to affect control flow in a way we can observe.
171 if instr, ok := instr.(*ir.If); ok {
172 if cond, ok := instr.Cond.(*ir.BinOp); ok {
173 if isNilConst(cond.X) {
174 maybeNil[cond.Y] = cond
175 }
176 if isNilConst(cond.Y) {
177 maybeNil[cond.X] = cond
178 }
179 }
180 }
181 }
182 }
183
184 for _, b := range fn.Blocks {
185 for _, instr := range b.Instrs {
186 var ptr ir.Value
187 switch instr := instr.(type) {
188 case *ir.Load:
189 ptr = instr.X
190 case *ir.Store:
191 ptr = instr.Addr
192 case *ir.IndexAddr:
193 ptr = instr.X
194 if typeutil.All(ptr.Type(), func(term *types.Term) bool {
195 if _, ok := term.Type().Underlying().(*types.Slice); ok {
196 return true
197 }
198 return false
199 }) {
200 // indexing a nil slice does not cause a nil pointer panic
201 //
202 // Note: This also works around the bad lowering of range loops over slices
203 // (https://github.com/dominikh/go-tools/issues/1053)
204 continue
205 }
206 case *ir.FieldAddr:
207 ptr = instr.X
208 }
209 if ptr != nil {
210 switch ptr.(type) {
211 case *ir.Alloc, *ir.FieldAddr, *ir.IndexAddr:
212 // these cannot be nil
213 continue
214 }
215 if r, ok := maybeNil[ptr]; ok {
216 report.Report(pass, instr, "possible nil pointer dereference",
217 report.Related(r, "this check suggests that the pointer can be nil"))
218 }
219 }
220 }
221 }
222 }
223
224 return nil, nil
225 }