github.com/peggyl/go@v0.0.0-20151008231540-ae315999c2d5/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  
    26  	// certain uses of reflect are okay
    27  	var v reflect.Value
    28  	x = unsafe.Pointer(v.Pointer())
    29  	x = unsafe.Pointer(v.UnsafeAddr())
    30  	var s1 *reflect.StringHeader
    31  	x = unsafe.Pointer(s1.Data)
    32  	var s2 *reflect.SliceHeader
    33  	x = unsafe.Pointer(s2.Data)
    34  	var s3 reflect.StringHeader
    35  	x = unsafe.Pointer(s3.Data) // ERROR "possible misuse of unsafe.Pointer"
    36  	var s4 reflect.SliceHeader
    37  	x = unsafe.Pointer(s4.Data) // ERROR "possible misuse of unsafe.Pointer"
    38  
    39  	// but only in reflect
    40  	var vv V
    41  	x = unsafe.Pointer(vv.Pointer())    // ERROR "possible misuse of unsafe.Pointer"
    42  	x = unsafe.Pointer(vv.UnsafeAddr()) // ERROR "possible misuse of unsafe.Pointer"
    43  	var ss1 *StringHeader
    44  	x = unsafe.Pointer(ss1.Data) // ERROR "possible misuse of unsafe.Pointer"
    45  	var ss2 *SliceHeader
    46  	x = unsafe.Pointer(ss2.Data) // ERROR "possible misuse of unsafe.Pointer"
    47  
    48  }
    49  
    50  type V interface {
    51  	Pointer() uintptr
    52  	UnsafeAddr() uintptr
    53  }
    54  
    55  type StringHeader struct {
    56  	Data uintptr
    57  }
    58  
    59  type SliceHeader struct {
    60  	Data uintptr
    61  }