This repository has been archived by the owner on Nov 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
494 lines (462 loc) · 10.8 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
package main
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/constant"
"go/printer"
"go/token"
"go/types"
"io/ioutil"
"log"
"os"
"reflect"
"golang.org/x/tools/go/loader"
"golang.org/x/tools/go/ssa"
"golang.org/x/tools/go/ssa/ssautil"
)
var debug bool
func init() {
log.SetFlags(0)
log.SetOutput(ioutil.Discard)
flag.Usage = usage
flag.BoolVar(&debug, "debug", false, "print debugging information")
}
func main() {
flag.Parse()
if flag.NArg() == 0 {
flag.Usage()
}
if debug {
log.SetOutput(os.Stderr)
}
traces, err := check(flag.Args())
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(2)
}
for _, tr := range traces {
for i, instr := range tr {
if i != 0 {
fmt.Print("\t")
}
fmt.Printf("%s: possible nil pointer dereference: %s\n", instr.pos(), instr.src())
}
}
if len(traces) != 0 {
os.Exit(1)
}
}
func usage() {
fmt.Fprintf(os.Stderr, "Usage: %s [options] <args>\n", os.Args[0])
fmt.Fprintln(os.Stderr, loader.FromArgsUsage)
fmt.Fprintln(os.Stderr, "Options:")
flag.PrintDefaults()
os.Exit(2)
}
func check(args []string) ([]trace, error) {
var conf loader.Config
_, err := conf.FromArgs(args, false)
if err != nil {
return nil, err
}
lprog, err := conf.Load()
if err != nil {
return nil, err
}
prog := ssautil.CreateProgram(lprog, ssa.BuilderMode(0))
prog.Build()
c := &checker{lprog: lprog}
fr := &frame{checker: c}
for fn := range ssautil.AllFunctions(prog) {
_ = fr.symEvalFunc(nil, fn, nil, 0)
}
return c.npds, nil
}
type checker struct {
lprog *loader.Program
npds []trace
}
func (c *checker) report(instr ssa.Instruction, fr *frame) {
c.npds = append(c.npds, append(fr.tr, &instruction{instr, c.lprog}))
}
type instruction struct {
ssa.Instruction
lprog *loader.Program
}
func (instr *instruction) pos() token.Position {
return instr.lprog.Fset.Position(instr.Pos())
}
func (instr *instruction) src() string {
_, path, _ := instr.lprog.PathEnclosingInterval(instr.Pos(), instr.Pos())
var node ast.Node
switch instr.Instruction.(type) {
case *ssa.FieldAddr:
node = findSelectorExpr(path)
default:
node = path[0]
}
var buf bytes.Buffer
printer.Fprint(&buf, instr.lprog.Fset, node)
return buf.String()
}
type trace []*instruction
type value struct {
val ssa.Value
zero bool
toZero bool
}
func newValue(val ssa.Value, zero bool) *value {
return &value{val: val, zero: zero}
}
type phi []*value
type frame struct {
fn *ssa.Function
args []ssa.Value
tr trace
checker *checker
env map[ssa.Value]phi
lvl int
}
func (fr *frame) report(instr ssa.Instruction) {
fr.checker.report(instr, fr)
}
func (fr *frame) get(v *value) phi {
if edges, ok := fr.env[v.val]; ok {
return edges
}
return fr.symEval(v)
}
func (fr *frame) symEval(v *value) phi {
var ret phi
switch val := v.val.(type) {
case *ssa.Alloc:
ret = []*value{{val: val, zero: false, toZero: true}}
case *ssa.BinOp:
xx, yy := fr.get(&value{val: val.X}), fr.get(&value{val: val.Y})
for i, x := range xx {
y := yy[i]
c := ssa.NewConst(nil, val.Type())
switch val.Op {
case token.ADD, token.SUB:
addEdge(&ret, c, x.zero && y.zero)
case token.MUL:
addEdge(&ret, c, x.zero || y.zero)
case token.QUO, token.REM:
addEdge(&ret, c, x.zero)
case token.AND, token.OR, token.XOR, token.AND_NOT:
addEdge(&ret, c, x.zero && y.zero)
case token.SHL, token.SHR:
addEdge(&ret, c, x.zero)
case token.EQL, token.LEQ, token.GEQ:
switch {
case x.zero && y.zero:
ret = append(ret, newValue(c, false))
case x.zero != y.zero:
ret = append(ret, newValue(c, true))
default: // !x.zero && !y.zero
ret = append(ret, newValue(c, false))
ret = append(ret, newValue(c, true))
}
case token.NEQ:
switch {
case x.zero && y.zero:
ret = append(ret, newValue(c, true))
case x.zero != y.zero:
ret = append(ret, newValue(c, false))
default: // !x.zero && !y.zero
ret = append(ret, newValue(c, false))
ret = append(ret, newValue(c, true))
}
case token.LSS, token.GTR:
// TODO: we can be more accurate here;
// strings come to mind.
ret = append(ret, newValue(c, false))
ret = append(ret, newValue(c, true))
}
}
case *ssa.Call:
ret = fr.symEvalCall(val, 0)
case *ssa.Const:
if val.IsNil() {
ret = []*value{newValue(val, true)}
break
}
var zero bool
switch val.Value.Kind() {
case constant.Bool:
zero = !constant.BoolVal(val.Value)
case constant.Complex:
zero = val.Complex128() == 0
case constant.Float:
zero = val.Float64() == 0
case constant.Int:
zero = val.Uint64() == 0
case constant.String:
zero = constant.StringVal(val.Value) == ""
}
ret = []*value{{zero: zero}}
case *ssa.Extract:
ret = fr.symEvalExtract(val)
case *ssa.FieldAddr:
xx := fr.get(&value{val: val.X})
if xx == nil {
return nil
}
for _, x := range xx {
if x.zero {
fr.report(val)
continue
}
c := ssa.NewConst(nil, val.Type())
ret = append(ret, &value{val: c, toZero: true})
if !x.toZero {
ret = append(ret, &value{val: c, toZero: false})
}
}
case *ssa.Global:
return nil
case *ssa.Lookup:
// val.CommaOk == false
xx := fr.get(&value{val: val.X})
if xx == nil {
return nil
}
if _, ok := xx[0].val.Type().(*types.Map); !ok {
// Possible index out of range error
// (guaranteed if x.zero)
return nil
}
for _, x := range xx {
c := ssa.NewConst(nil, x.val.Type().(*types.Map).Elem())
ret = append(ret, newValue(c, true))
if !x.zero {
ret = append(ret, newValue(c, false))
}
}
case *ssa.Next, *ssa.TypeAssert:
panic("unreachable") // handled by symEvalExtract
case *ssa.Parameter:
if fr.args == nil {
return nil
}
var arg ssa.Value
for i, p := range fr.fn.Params {
if p == val {
arg = fr.args[i]
break
}
}
ret = fr.get(&value{val: arg})
case *ssa.UnOp:
xx := fr.get(&value{val: val.X})
if xx == nil {
return nil
}
switch val.Op {
case token.MUL:
for _, x := range xx {
if x.zero {
fr.report(val)
continue
}
c := ssa.NewConst(nil, val.Type())
ret = append(ret, &value{val: c, zero: true})
if !x.toZero {
ret = append(ret, &value{val: c, zero: true})
}
}
default:
return nil // TODO
}
}
fr.env[v.val] = ret
return ret
}
func (fr *frame) symEvalExtract(t *ssa.Extract) phi {
switch val := t.Tuple.(type) {
case *ssa.Call:
return fr.symEvalCall(val, t.Index)
case *ssa.Lookup:
// val.X is a map
xx := fr.symEval(&value{val: val.X})
if xx == nil {
return nil
}
edges := make(phi, 0, len(xx))
for _, x := range xx {
// If x.zero, x[k] is zero;
// otherwise it can also be non-zero.
var typ types.Type
if t.Index == 0 { // x[k]
typ = x.val.Type().(*types.Map).Elem()
edges = append(edges, newValue(ssa.NewConst(nil, typ), true))
} else { // ,ok
typ = types.Typ[types.Bool]
edges = append(edges, newValue(ssa.NewConst(nil, typ), true))
}
if !x.zero {
edges = append(edges, newValue(ssa.NewConst(nil, typ), false))
}
}
return edges
default:
// TODO?
return nil
}
}
func (fr *frame) symEvalCall(call ssa.CallInstruction, res int) phi {
if call.Common().IsInvoke() {
return nil // call to an interface method
}
switch f := call.Common().Value.(type) {
case *ssa.Function:
return fr.symEvalFunc(call, f, call.Common().Args, res)
case *ssa.MakeClosure:
return fr.symEvalFunc(call, f.Fn.(*ssa.Function), f.Bindings, res)
default:
return fr.symEval(&value{val: f})
}
}
func (fr *frame) symEvalFunc(call ssa.CallInstruction, fn *ssa.Function, args []ssa.Value, res int) phi {
if fn.Blocks == nil {
return nil // external function: no source code available
}
tr := fr.tr
if call != nil {
tr = append(tr, &instruction{call, fr.checker.lprog})
}
if debug {
fmt.Printf("func %s:\n", fn.Name())
}
newfr := &frame{fn, args, tr, fr.checker, make(map[ssa.Value]phi), fr.lvl + 1}
eval := newfr.symEvalBlock(fn.Blocks[0], res)
if debug {
fmt.Println()
}
return eval
}
func (fr *frame) symEvalBlock(block *ssa.BasicBlock, res int) phi {
if len(block.Instrs) == 0 {
return nil // block is unreachable
}
fr.debugf("%d:\n", block.Index)
for _, instr := range block.Instrs {
var val ssa.Value
if v, ok := instr.(ssa.Value); ok {
val = v
switch v := v.(type) {
case *ssa.FieldAddr:
_ = fr.symEval(&value{val: v})
case *ssa.Call:
// XXX: only check calls where we're passing pointers?
var f *ssa.Function
var args []ssa.Value
switch call := v.Call.Value.(type) {
case *ssa.Function:
f = call
args = v.Call.Args
case *ssa.MakeClosure:
f = call.Fn.(*ssa.Function)
args = call.Bindings
}
if f != nil {
_ = fr.symEvalFunc(v, f, args, 0)
}
}
}
fr.debugf("\t; %s\n", reflect.TypeOf(instr))
if val != nil {
edges := fr.symEval(&value{val: val})
var edge *value
if len(edges) != 0 {
edge = edges[0]
fr.debugf("\t; val:%v zero:%v toZero:%v\n", edge.val, edge.zero, edge.toZero)
} else {
fr.debugf("\t; couldn't eval\n")
}
}
fr.debugf("\t")
if val != nil {
fr.debugf("%s = ", val.Name())
}
fr.debugf("%s\n", instr)
fr.debugf("\n")
}
switch ctrl := block.Instrs[len(block.Instrs)-1].(type) {
case *ssa.If:
cond := fr.symEval(&value{val: ctrl.Cond})
if cond == nil {
return nil
}
edges := make(phi, 0, len(cond))
tru, fals := false, false
for _, c := range cond {
if c.zero {
fals = true
} else {
tru = true
}
}
if tru {
edges = append(edges, fr.symEvalBlock(block.Succs[0], res)...)
}
if fals {
edges = append(edges, fr.symEvalBlock(block.Succs[1], res)...)
}
return edges
case *ssa.Jump:
return fr.symEvalBlock(block.Succs[0], res)
case *ssa.Panic:
return nil
case *ssa.Return:
if len(ctrl.Results) == 0 {
return nil
}
return fr.symEval(&value{val: ctrl.Results[res]})
default:
panic("unreachable")
}
}
func (fr *frame) debugf(format string, a ...interface{}) {
if debug && fr.lvl == 1 {
fmt.Printf(format, a...)
}
}
func addEdge(edges *phi, v ssa.Value, guaranteedZero bool) {
if !guaranteedZero {
*edges = append(*edges, newValue(v, false))
}
*edges = append(*edges, newValue(v, true))
}
func named(typ types.Type) types.Type {
if _, ok := typ.(*types.Named); ok {
return named(typ.Underlying())
}
return typ
}
func goType(typ types.Type) types.Type {
if _, ok := typ.(*types.Named); ok {
return goType(typ.Underlying())
}
if p, ok := typ.Underlying().(*types.Pointer); ok {
return goType(p.Elem())
}
return typ
}
func findSelectorExpr(path []ast.Node) *ast.SelectorExpr {
for _, n := range path {
if sexpr, ok := n.(*ast.SelectorExpr); ok {
return sexpr
}
}
return nil
}
func nodeToString(n interface{}, fset *token.FileSet) string {
var buf bytes.Buffer
if err := printer.Fprint(&buf, fset, n); err != nil {
panic(err)
}
return buf.String()
}