github.com/likebike/go--@v0.0.0-20190911215757-0bd925d16e96/go/src/cmd/vet/testdata/unsafeptr.go (about)

     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 testdata
     6  
     7  import (
     8  	"reflect"
     9  	"unsafe"
    10  )
    11  
    12  func f() {
    13  	var x unsafe.Pointer
    14  	var y uintptr
    15  	x = unsafe.Pointer(y) // ERROR "possible misuse of unsafe.Pointer"
    16  	y = uintptr(x)
    17  
    18  	// only allowed pointer arithmetic is ptr +/-/&^ num.
    19  	// num+ptr is technically okay but still flagged: write ptr+num instead.
    20  	x = unsafe.Pointer(uintptr(x) + 1)
    21  	x = unsafe.Pointer(1 + uintptr(x))          // ERROR "possible misuse of unsafe.Pointer"
    22  	x = unsafe.Pointer(uintptr(x) + uintptr(x)) // ERROR "possible misuse of unsafe.Pointer"
    23  	x = unsafe.Pointer(uintptr(x) - 1)
    24  	x = unsafe.Pointer(1 - uintptr(x)) // ERROR "possible misuse of unsafe.Pointer"
    25  	x = unsafe.Pointer(uintptr(x) &^ 3)
    26  	x = unsafe.Pointer(1 &^ uintptr(x)) // ERROR "possible misuse of unsafe.Pointer"
    27  
    28  	// certain uses of reflect are okay
    29  	var v reflect.Value
    30  	x = unsafe.Pointer(v.Pointer())
    31  	x = unsafe.Pointer(v.UnsafeAddr())
    32  	var s1 *reflect.StringHeader
    33  	x = unsafe.Pointer(s1.Data)
    34  	var s2 *reflect.SliceHeader
    35  	x = unsafe.Pointer(s2.Data)
    36  	var s3 reflect.StringHeader
    37  	x = unsafe.Pointer(s3.Data) // ERROR "possible misuse of unsafe.Pointer"
    38  	var s4 reflect.SliceHeader
    39  	x = unsafe.Pointer(s4.Data) // ERROR "possible misuse of unsafe.Pointer"
    40  
    41  	// but only in reflect
    42  	var vv V
    43  	x = unsafe.Pointer(vv.Pointer())    // ERROR "possible misuse of unsafe.Pointer"
    44  	x = unsafe.Pointer(vv.UnsafeAddr()) // ERROR "possible misuse of unsafe.Pointer"
    45  	var ss1 *StringHeader
    46  	x = unsafe.Pointer(ss1.Data) // ERROR "possible misuse of unsafe.Pointer"
    47  	var ss2 *SliceHeader
    48  	x = unsafe.Pointer(ss2.Data) // ERROR "possible misuse of unsafe.Pointer"
    49  
    50  }
    51  
    52  type V interface {
    53  	Pointer() uintptr
    54  	UnsafeAddr() uintptr
    55  }
    56  
    57  type StringHeader struct {
    58  	Data uintptr
    59  }
    60  
    61  type SliceHeader struct {
    62  	Data uintptr
    63  }