* builtins.def (BUILT_IN_SETJMP): Revert latest change.
[official-gcc.git] / libgo / go / runtime / cgocall.go
blob2e0e591138a326ce31164e568fad8abd6508109d
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.
5 // Cgo call and callback support.
7 package runtime
9 import (
10 "runtime/internal/sys"
11 "unsafe"
14 // Pointer checking for cgo code.
16 // We want to detect all cases where a program that does not use
17 // unsafe makes a cgo call passing a Go pointer to memory that
18 // contains a Go pointer. Here a Go pointer is defined as a pointer
19 // to memory allocated by the Go runtime. Programs that use unsafe
20 // can evade this restriction easily, so we don't try to catch them.
21 // The cgo program will rewrite all possibly bad pointer arguments to
22 // call cgoCheckPointer, where we can catch cases of a Go pointer
23 // pointing to a Go pointer.
25 // Complicating matters, taking the address of a slice or array
26 // element permits the C program to access all elements of the slice
27 // or array. In that case we will see a pointer to a single element,
28 // but we need to check the entire data structure.
30 // The cgoCheckPointer call takes additional arguments indicating that
31 // it was called on an address expression. An additional argument of
32 // true means that it only needs to check a single element. An
33 // additional argument of a slice or array means that it needs to
34 // check the entire slice/array, but nothing else. Otherwise, the
35 // pointer could be anything, and we check the entire heap object,
36 // which is conservative but safe.
38 // When and if we implement a moving garbage collector,
39 // cgoCheckPointer will pin the pointer for the duration of the cgo
40 // call. (This is necessary but not sufficient; the cgo program will
41 // also have to change to pin Go pointers that cannot point to Go
42 // pointers.)
44 // cgoCheckPointer checks if the argument contains a Go pointer that
45 // points to a Go pointer, and panics if it does.
46 func cgoCheckPointer(ptr interface{}, args ...interface{}) {
47 if debug.cgocheck == 0 {
48 return
51 ep := (*eface)(unsafe.Pointer(&ptr))
52 t := ep._type
54 top := true
55 if len(args) > 0 && (t.kind&kindMask == kindPtr || t.kind&kindMask == kindUnsafePointer) {
56 p := ep.data
57 if t.kind&kindDirectIface == 0 {
58 p = *(*unsafe.Pointer)(p)
60 if !cgoIsGoPointer(p) {
61 return
63 aep := (*eface)(unsafe.Pointer(&args[0]))
64 switch aep._type.kind & kindMask {
65 case kindBool:
66 if t.kind&kindMask == kindUnsafePointer {
67 // We don't know the type of the element.
68 break
70 pt := (*ptrtype)(unsafe.Pointer(t))
71 cgoCheckArg(pt.elem, p, true, false, cgoCheckPointerFail)
72 return
73 case kindSlice:
74 // Check the slice rather than the pointer.
75 ep = aep
76 t = ep._type
77 case kindArray:
78 // Check the array rather than the pointer.
79 // Pass top as false since we have a pointer
80 // to the array.
81 ep = aep
82 t = ep._type
83 top = false
84 default:
85 throw("can't happen")
89 cgoCheckArg(t, ep.data, t.kind&kindDirectIface == 0, top, cgoCheckPointerFail)
92 const cgoCheckPointerFail = "cgo argument has Go pointer to Go pointer"
93 const cgoResultFail = "cgo result has Go pointer"
95 // cgoCheckArg is the real work of cgoCheckPointer. The argument p
96 // is either a pointer to the value (of type t), or the value itself,
97 // depending on indir. The top parameter is whether we are at the top
98 // level, where Go pointers are allowed.
99 func cgoCheckArg(t *_type, p unsafe.Pointer, indir, top bool, msg string) {
100 if t.kind&kindNoPointers != 0 {
101 // If the type has no pointers there is nothing to do.
102 return
105 switch t.kind & kindMask {
106 default:
107 throw("can't happen")
108 case kindArray:
109 at := (*arraytype)(unsafe.Pointer(t))
110 if !indir {
111 if at.len != 1 {
112 throw("can't happen")
114 cgoCheckArg(at.elem, p, at.elem.kind&kindDirectIface == 0, top, msg)
115 return
117 for i := uintptr(0); i < at.len; i++ {
118 cgoCheckArg(at.elem, p, true, top, msg)
119 p = add(p, at.elem.size)
121 case kindChan, kindMap:
122 // These types contain internal pointers that will
123 // always be allocated in the Go heap. It's never OK
124 // to pass them to C.
125 panic(errorString(msg))
126 case kindFunc:
127 if indir {
128 p = *(*unsafe.Pointer)(p)
130 if !cgoIsGoPointer(p) {
131 return
133 panic(errorString(msg))
134 case kindInterface:
135 it := *(**_type)(p)
136 if it == nil {
137 return
139 // A type known at compile time is OK since it's
140 // constant. A type not known at compile time will be
141 // in the heap and will not be OK.
142 if inheap(uintptr(unsafe.Pointer(it))) {
143 panic(errorString(msg))
145 p = *(*unsafe.Pointer)(add(p, sys.PtrSize))
146 if !cgoIsGoPointer(p) {
147 return
149 if !top {
150 panic(errorString(msg))
152 cgoCheckArg(it, p, it.kind&kindDirectIface == 0, false, msg)
153 case kindSlice:
154 st := (*slicetype)(unsafe.Pointer(t))
155 s := (*slice)(p)
156 p = s.array
157 if !cgoIsGoPointer(p) {
158 return
160 if !top {
161 panic(errorString(msg))
163 if st.elem.kind&kindNoPointers != 0 {
164 return
166 for i := 0; i < s.cap; i++ {
167 cgoCheckArg(st.elem, p, true, false, msg)
168 p = add(p, st.elem.size)
170 case kindString:
171 ss := (*stringStruct)(p)
172 if !cgoIsGoPointer(ss.str) {
173 return
175 if !top {
176 panic(errorString(msg))
178 case kindStruct:
179 st := (*structtype)(unsafe.Pointer(t))
180 if !indir {
181 if len(st.fields) != 1 {
182 throw("can't happen")
184 cgoCheckArg(st.fields[0].typ, p, st.fields[0].typ.kind&kindDirectIface == 0, top, msg)
185 return
187 for _, f := range st.fields {
188 cgoCheckArg(f.typ, add(p, f.offset), true, top, msg)
190 case kindPtr, kindUnsafePointer:
191 if indir {
192 p = *(*unsafe.Pointer)(p)
195 if !cgoIsGoPointer(p) {
196 return
198 if !top {
199 panic(errorString(msg))
202 cgoCheckUnknownPointer(p, msg)
206 // cgoCheckUnknownPointer is called for an arbitrary pointer into Go
207 // memory. It checks whether that Go memory contains any other
208 // pointer into Go memory. If it does, we panic.
209 // The return values are unused but useful to see in panic tracebacks.
210 func cgoCheckUnknownPointer(p unsafe.Pointer, msg string) (base, i uintptr) {
211 if cgoInRange(p, mheap_.arena_start, mheap_.arena_used) {
212 if !inheap(uintptr(p)) {
213 // On 32-bit systems it is possible for C's allocated memory
214 // to have addresses between arena_start and arena_used.
215 // Either this pointer is a stack or an unused span or it's
216 // a C allocation. Escape analysis should prevent the first,
217 // garbage collection should prevent the second,
218 // and the third is completely OK.
219 return
222 b, hbits, span, _ := heapBitsForObject(uintptr(p), 0, 0, false)
223 base = b
224 if base == 0 {
225 return
227 n := span.elemsize
228 for i = uintptr(0); i < n; i += sys.PtrSize {
229 if i != 1*sys.PtrSize && !hbits.morePointers() {
230 // No more possible pointers.
231 break
233 if hbits.isPointer() {
234 if cgoIsGoPointer(*(*unsafe.Pointer)(unsafe.Pointer(base + i))) {
235 panic(errorString(msg))
238 hbits = hbits.next()
241 return
244 roots := gcRoots
245 for roots != nil {
246 for j := 0; j < roots.count; j++ {
247 pr := roots.roots[j]
248 addr := uintptr(pr.decl)
249 if cgoInRange(p, addr, addr+pr.size) {
250 cgoCheckBits(pr.decl, pr.gcdata, 0, pr.ptrdata)
251 return
254 roots = roots.next
257 return
260 // cgoIsGoPointer returns whether the pointer is a Go pointer--a
261 // pointer to Go memory. We only care about Go memory that might
262 // contain pointers.
263 //go:nosplit
264 //go:nowritebarrierrec
265 func cgoIsGoPointer(p unsafe.Pointer) bool {
266 if p == nil {
267 return false
270 if inHeapOrStack(uintptr(p)) {
271 return true
274 roots := gcRoots
275 for roots != nil {
276 for i := 0; i < roots.count; i++ {
277 pr := roots.roots[i]
278 addr := uintptr(pr.decl)
279 if cgoInRange(p, addr, addr+pr.size) {
280 return true
283 roots = roots.next
286 return false
289 // cgoInRange returns whether p is between start and end.
290 //go:nosplit
291 //go:nowritebarrierrec
292 func cgoInRange(p unsafe.Pointer, start, end uintptr) bool {
293 return start <= uintptr(p) && uintptr(p) < end
296 // cgoCheckResult is called to check the result parameter of an
297 // exported Go function. It panics if the result is or contains a Go
298 // pointer.
299 func cgoCheckResult(val interface{}) {
300 if debug.cgocheck == 0 {
301 return
304 ep := (*eface)(unsafe.Pointer(&val))
305 t := ep._type
306 cgoCheckArg(t, ep.data, t.kind&kindDirectIface == 0, false, cgoResultFail)