1 // Copyright 2018 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.
5 // The unmarshal package defines an Analyzer that checks for passing
6 // non-pointer or non-interface types to unmarshal and decode functions.
13 "golang.org/x/tools/go/analysis"
14 "golang.org/x/tools/go/analysis/passes/inspect"
15 "golang.org/x/tools/go/ast/inspector"
16 "golang.org/x/tools/go/types/typeutil"
19 const Doc = `report passing non-pointer or non-interface values to unmarshal
21 The unmarshal analysis reports calls to functions such as json.Unmarshal
22 in which the argument type is not a pointer or an interface.`
24 var Analyzer = &analysis.Analyzer{
27 Requires: []*analysis.Analyzer{inspect.Analyzer},
31 func run(pass *analysis.Pass) (interface{}, error) {
32 switch pass.Pkg.Path() {
33 case "encoding/gob", "encoding/json", "encoding/xml", "encoding/asn1":
34 // These packages know how to use their own APIs.
35 // Sometimes they are testing what happens to incorrect programs.
39 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
41 nodeFilter := []ast.Node{
44 inspect.Preorder(nodeFilter, func(n ast.Node) {
45 call := n.(*ast.CallExpr)
46 fn := typeutil.StaticCallee(pass.TypesInfo, call)
48 return // not a static call
51 // Classify the callee (without allocating memory).
53 recv := fn.Type().(*types.Signature).Recv()
54 if fn.Name() == "Unmarshal" && recv == nil {
55 // "encoding/json".Unmarshal
56 // "encoding/xml".Unmarshal
57 // "encoding/asn1".Unmarshal
58 switch fn.Pkg().Path() {
59 case "encoding/json", "encoding/xml", "encoding/asn1":
60 argidx = 1 // func([]byte, interface{})
62 } else if fn.Name() == "Decode" && recv != nil {
63 // (*"encoding/json".Decoder).Decode
64 // (* "encoding/gob".Decoder).Decode
65 // (* "encoding/xml".Decoder).Decode
67 if ptr, ok := t.(*types.Pointer); ok {
70 tname := t.(*types.Named).Obj()
71 if tname.Name() == "Decoder" {
72 switch tname.Pkg().Path() {
73 case "encoding/json", "encoding/xml", "encoding/gob":
74 argidx = 0 // func(interface{})
79 return // not a function we are interested in
82 if len(call.Args) < argidx+1 {
83 return // not enough arguments, e.g. called with return values of another function
86 t := pass.TypesInfo.Types[call.Args[argidx]].Type
87 switch t.Underlying().(type) {
88 case *types.Pointer, *types.Interface:
94 pass.Reportf(call.Lparen, "call of %s passes non-pointer", fn.Name())
96 pass.Reportf(call.Lparen, "call of %s passes non-pointer as second argument", fn.Name())