Source file src/cmd/vendor/golang.org/x/tools/go/analysis/passes/unsafeptr/unsafeptr.go

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

View as plain text