Source file src/unsafe/unsafe.go

     1  // Copyright 2009 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  /*
     6  Package unsafe contains operations that step around the type safety of Go programs.
     7  
     8  Packages that import unsafe may be non-portable and are not protected by the
     9  Go 1 compatibility guidelines.
    10  */
    11  package unsafe
    12  
    13  // ArbitraryType is here for the purposes of documentation only and is not actually
    14  // part of the unsafe package. It represents the type of an arbitrary Go expression.
    15  type ArbitraryType int
    16  
    17  // IntegerType is here for the purposes of documentation only and is not actually
    18  // part of the unsafe package. It represents any arbitrary integer type.
    19  type IntegerType int
    20  
    21  // Pointer represents a pointer to an arbitrary type. There are four special operations
    22  // available for type Pointer that are not available for other types:
    23  //   - A pointer value of any type can be converted to a Pointer.
    24  //   - A Pointer can be converted to a pointer value of any type.
    25  //   - A uintptr can be converted to a Pointer.
    26  //   - A Pointer can be converted to a uintptr.
    27  //
    28  // Pointer therefore allows a program to defeat the type system and read and write
    29  // arbitrary memory. It should be used with extreme care.
    30  //
    31  // The following patterns involving Pointer are valid.
    32  // Code not using these patterns is likely to be invalid today
    33  // or to become invalid in the future.
    34  // Even the valid patterns below come with important caveats.
    35  //
    36  // Running "go vet" can help find uses of Pointer that do not conform to these patterns,
    37  // but silence from "go vet" is not a guarantee that the code is valid.
    38  //
    39  // (1) Conversion of a *T1 to Pointer to *T2.
    40  //
    41  // Provided that T2 is no larger than T1 and that the two share an equivalent
    42  // memory layout, this conversion allows reinterpreting data of one type as
    43  // data of another type. An example is the implementation of
    44  // math.Float64bits:
    45  //
    46  //	func Float64bits(f float64) uint64 {
    47  //		return *(*uint64)(unsafe.Pointer(&f))
    48  //	}
    49  //
    50  // (2) Conversion of a Pointer to a uintptr (but not back to Pointer).
    51  //
    52  // Converting a Pointer to a uintptr produces the memory address of the value
    53  // pointed at, as an integer. The usual use for such a uintptr is to print it.
    54  //
    55  // Conversion of a uintptr back to Pointer is not valid in general.
    56  //
    57  // A uintptr is an integer, not a reference.
    58  // Converting a Pointer to a uintptr creates an integer value
    59  // with no pointer semantics.
    60  // Even if a uintptr holds the address of some object,
    61  // the garbage collector will not update that uintptr's value
    62  // if the object moves, nor will that uintptr keep the object
    63  // from being reclaimed.
    64  //
    65  // The remaining patterns enumerate the only valid conversions
    66  // from uintptr to Pointer.
    67  //
    68  // (3) Conversion of a Pointer to a uintptr and back, with arithmetic.
    69  //
    70  // If p points into an allocated object, it can be advanced through the object
    71  // by conversion to uintptr, addition of an offset, and conversion back to Pointer.
    72  //
    73  //	p = unsafe.Pointer(uintptr(p) + offset)
    74  //
    75  // The most common use of this pattern is to access fields in a struct
    76  // or elements of an array:
    77  //
    78  //	// equivalent to f := unsafe.Pointer(&s.f)
    79  //	f := unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f))
    80  //
    81  //	// equivalent to e := unsafe.Pointer(&x[i])
    82  //	e := unsafe.Pointer(uintptr(unsafe.Pointer(&x[0])) + i*unsafe.Sizeof(x[0]))
    83  //
    84  // It is valid both to add and to subtract offsets from a pointer in this way.
    85  // It is also valid to use &^ to round pointers, usually for alignment.
    86  // In all cases, the result must continue to point into the original allocated object.
    87  //
    88  // Unlike in C, it is not valid to advance a pointer just beyond the end of
    89  // its original allocation:
    90  //
    91  //	// INVALID: end points outside allocated space.
    92  //	var s thing
    93  //	end = unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Sizeof(s))
    94  //
    95  //	// INVALID: end points outside allocated space.
    96  //	b := make([]byte, n)
    97  //	end = unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(n))
    98  //
    99  // Note that both conversions must appear in the same expression, with only
   100  // the intervening arithmetic between them:
   101  //
   102  //	// INVALID: uintptr cannot be stored in variable
   103  //	// before conversion back to Pointer.
   104  //	u := uintptr(p)
   105  //	p = unsafe.Pointer(u + offset)
   106  //
   107  // Note that the pointer must point into an allocated object, so it may not be nil.
   108  //
   109  //	// INVALID: conversion of nil pointer
   110  //	u := unsafe.Pointer(nil)
   111  //	p := unsafe.Pointer(uintptr(u) + offset)
   112  //
   113  // (4) Conversion of a Pointer to a uintptr when calling functions like [syscall.Syscall].
   114  //
   115  // The Syscall functions in package syscall pass their uintptr arguments directly
   116  // to the operating system, which then may, depending on the details of the call,
   117  // reinterpret some of them as pointers.
   118  // That is, the system call implementation is implicitly converting certain arguments
   119  // back from uintptr to pointer.
   120  //
   121  // If a pointer argument must be converted to uintptr for use as an argument,
   122  // that conversion must appear in the call expression itself:
   123  //
   124  //	syscall.Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(n))
   125  //
   126  // The compiler handles a Pointer converted to a uintptr in the argument list of
   127  // a call to a function implemented in assembly by arranging that the referenced
   128  // allocated object, if any, is retained and not moved until the call completes,
   129  // even though from the types alone it would appear that the object is no longer
   130  // needed during the call.
   131  //
   132  // For the compiler to recognize this pattern,
   133  // the conversion must appear in the argument list:
   134  //
   135  //	// INVALID: uintptr cannot be stored in variable
   136  //	// before implicit conversion back to Pointer during system call.
   137  //	u := uintptr(unsafe.Pointer(p))
   138  //	syscall.Syscall(SYS_READ, uintptr(fd), u, uintptr(n))
   139  //
   140  // (5) Conversion of the result of [reflect.Value.Pointer] or [reflect.Value.UnsafeAddr]
   141  // from uintptr to Pointer.
   142  //
   143  // Package reflect's Value methods named Pointer and UnsafeAddr return type uintptr
   144  // instead of unsafe.Pointer to keep callers from changing the result to an arbitrary
   145  // type without first importing "unsafe". However, this means that the result is
   146  // fragile and must be converted to Pointer immediately after making the call,
   147  // in the same expression:
   148  //
   149  //	p := (*int)(unsafe.Pointer(reflect.ValueOf(new(int)).Pointer()))
   150  //
   151  // As in the cases above, it is invalid to store the result before the conversion:
   152  //
   153  //	// INVALID: uintptr cannot be stored in variable
   154  //	// before conversion back to Pointer.
   155  //	u := reflect.ValueOf(new(int)).Pointer()
   156  //	p := (*int)(unsafe.Pointer(u))
   157  //
   158  // (6) Conversion of a [reflect.SliceHeader] or [reflect.StringHeader] Data field to or from Pointer.
   159  //
   160  // As in the previous case, the reflect data structures SliceHeader and StringHeader
   161  // declare the field Data as a uintptr to keep callers from changing the result to
   162  // an arbitrary type without first importing "unsafe". However, this means that
   163  // SliceHeader and StringHeader are only valid when interpreting the content
   164  // of an actual slice or string value.
   165  //
   166  //	var s string
   167  //	hdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) // case 1
   168  //	hdr.Data = uintptr(unsafe.Pointer(p))              // case 6 (this case)
   169  //	hdr.Len = n
   170  //
   171  // In this usage hdr.Data is really an alternate way to refer to the underlying
   172  // pointer in the string header, not a uintptr variable itself.
   173  //
   174  // In general, [reflect.SliceHeader] and [reflect.StringHeader] should be used
   175  // only as *reflect.SliceHeader and *reflect.StringHeader pointing at actual
   176  // slices or strings, never as plain structs.
   177  // A program should not declare or allocate variables of these struct types.
   178  //
   179  //	// INVALID: a directly-declared header will not hold Data as a reference.
   180  //	var hdr reflect.StringHeader
   181  //	hdr.Data = uintptr(unsafe.Pointer(p))
   182  //	hdr.Len = n
   183  //	s := *(*string)(unsafe.Pointer(&hdr)) // p possibly already lost
   184  type Pointer *ArbitraryType
   185  
   186  // Sizeof takes an expression x of any type and returns the size in bytes
   187  // of a hypothetical variable v as if v was declared via var v = x.
   188  // The size does not include any memory possibly referenced by x.
   189  // For instance, if x is a slice, Sizeof returns the size of the slice
   190  // descriptor, not the size of the memory referenced by the slice;
   191  // if x is an interface, Sizeof returns the size of the interface value itself,
   192  // not the size of the value stored in the interface.
   193  // For a struct, the size includes any padding introduced by field alignment.
   194  // The return value of Sizeof is a Go constant if the type of the argument x
   195  // does not have variable size.
   196  // (A type has variable size if it is a type parameter or if it is an array
   197  // or struct type with elements of variable size).
   198  func Sizeof(x ArbitraryType) uintptr
   199  
   200  // Offsetof returns the offset within the struct of the field represented by x,
   201  // which must be of the form structValue.field. In other words, it returns the
   202  // number of bytes between the start of the struct and the start of the field.
   203  // The return value of Offsetof is a Go constant if the type of the argument x
   204  // does not have variable size.
   205  // (See the description of [Sizeof] for a definition of variable sized types.)
   206  func Offsetof(x ArbitraryType) uintptr
   207  
   208  // Alignof takes an expression x of any type and returns the required alignment
   209  // of a hypothetical variable v as if v was declared via var v = x.
   210  // It is the largest value m such that the address of v is always zero mod m.
   211  // It is the same as the value returned by [reflect.TypeOf](x).Align().
   212  // As a special case, if a variable s is of struct type and f is a field
   213  // within that struct, then Alignof(s.f) will return the required alignment
   214  // of a field of that type within a struct. This case is the same as the
   215  // value returned by [reflect.TypeOf](s.f).FieldAlign().
   216  // The return value of Alignof is a Go constant if the type of the argument
   217  // does not have variable size.
   218  // (See the description of [Sizeof] for a definition of variable sized types.)
   219  func Alignof(x ArbitraryType) uintptr
   220  
   221  // The function Add adds len to ptr and returns the updated pointer
   222  // [Pointer](uintptr(ptr) + uintptr(len)).
   223  // The len argument must be of integer type or an untyped constant.
   224  // A constant len argument must be representable by a value of type int;
   225  // if it is an untyped constant it is given type int.
   226  // The rules for valid uses of Pointer still apply.
   227  func Add(ptr Pointer, len IntegerType) Pointer
   228  
   229  // The function Slice returns a slice whose underlying array starts at ptr
   230  // and whose length and capacity are len.
   231  // Slice(ptr, len) is equivalent to
   232  //
   233  //	(*[len]ArbitraryType)(unsafe.Pointer(ptr))[:]
   234  //
   235  // except that, as a special case, if ptr is nil and len is zero,
   236  // Slice returns nil.
   237  //
   238  // The len argument must be of integer type or an untyped constant.
   239  // A constant len argument must be non-negative and representable by a value of type int;
   240  // if it is an untyped constant it is given type int.
   241  // At run time, if len is negative, or if ptr is nil and len is not zero,
   242  // a run-time panic occurs.
   243  func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType
   244  
   245  // SliceData returns a pointer to the underlying array of the argument
   246  // slice.
   247  //   - If cap(slice) > 0, SliceData returns &slice[:1][0].
   248  //   - If slice == nil, SliceData returns nil.
   249  //   - Otherwise, SliceData returns a non-nil pointer to an
   250  //     unspecified memory address.
   251  func SliceData(slice []ArbitraryType) *ArbitraryType
   252  
   253  // String returns a string value whose underlying bytes
   254  // start at ptr and whose length is len.
   255  //
   256  // The len argument must be of integer type or an untyped constant.
   257  // A constant len argument must be non-negative and representable by a value of type int;
   258  // if it is an untyped constant it is given type int.
   259  // At run time, if len is negative, or if ptr is nil and len is not zero,
   260  // a run-time panic occurs.
   261  //
   262  // Since Go strings are immutable, the bytes passed to String
   263  // must not be modified as long as the returned string value exists.
   264  func String(ptr *byte, len IntegerType) string
   265  
   266  // StringData returns a pointer to the underlying bytes of str.
   267  // For an empty string the return value is unspecified, and may be nil.
   268  //
   269  // Since Go strings are immutable, the bytes returned by StringData
   270  // must not be modified.
   271  func StringData(str string) *byte
   272  

View as plain text