]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/cgocall.go
[dev.typeparams] all: merge master (296ddf2) into dev.typeparams
[gostls13.git] / src / runtime / cgocall.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 // Cgo call and callback support.
6 //
7 // To call into the C function f from Go, the cgo-generated code calls
8 // runtime.cgocall(_cgo_Cfunc_f, frame), where _cgo_Cfunc_f is a
9 // gcc-compiled function written by cgo.
10 //
11 // runtime.cgocall (below) calls entersyscall so as not to block
12 // other goroutines or the garbage collector, and then calls
13 // runtime.asmcgocall(_cgo_Cfunc_f, frame).
14 //
15 // runtime.asmcgocall (in asm_$GOARCH.s) switches to the m->g0 stack
16 // (assumed to be an operating system-allocated stack, so safe to run
17 // gcc-compiled code on) and calls _cgo_Cfunc_f(frame).
18 //
19 // _cgo_Cfunc_f invokes the actual C function f with arguments
20 // taken from the frame structure, records the results in the frame,
21 // and returns to runtime.asmcgocall.
22 //
23 // After it regains control, runtime.asmcgocall switches back to the
24 // original g (m->curg)'s stack and returns to runtime.cgocall.
25 //
26 // After it regains control, runtime.cgocall calls exitsyscall, which blocks
27 // until this m can run Go code without violating the $GOMAXPROCS limit,
28 // and then unlocks g from m.
29 //
30 // The above description skipped over the possibility of the gcc-compiled
31 // function f calling back into Go. If that happens, we continue down
32 // the rabbit hole during the execution of f.
33 //
34 // To make it possible for gcc-compiled C code to call a Go function p.GoF,
35 // cgo writes a gcc-compiled function named GoF (not p.GoF, since gcc doesn't
36 // know about packages).  The gcc-compiled C function f calls GoF.
37 //
38 // GoF initializes "frame", a structure containing all of its
39 // arguments and slots for p.GoF's results. It calls
40 // crosscall2(_cgoexp_GoF, frame, framesize, ctxt) using the gcc ABI.
41 //
42 // crosscall2 (in cgo/asm_$GOARCH.s) is a four-argument adapter from
43 // the gcc function call ABI to the gc function call ABI. At this
44 // point we're in the Go runtime, but we're still running on m.g0's
45 // stack and outside the $GOMAXPROCS limit. crosscall2 calls
46 // runtime.cgocallback(_cgoexp_GoF, frame, ctxt) using the gc ABI.
47 // (crosscall2's framesize argument is no longer used, but there's one
48 // case where SWIG calls crosscall2 directly and expects to pass this
49 // argument. See _cgo_panic.)
50 //
51 // runtime.cgocallback (in asm_$GOARCH.s) switches from m.g0's stack
52 // to the original g (m.curg)'s stack, on which it calls
53 // runtime.cgocallbackg(_cgoexp_GoF, frame, ctxt). As part of the
54 // stack switch, runtime.cgocallback saves the current SP as
55 // m.g0.sched.sp, so that any use of m.g0's stack during the execution
56 // of the callback will be done below the existing stack frames.
57 // Before overwriting m.g0.sched.sp, it pushes the old value on the
58 // m.g0 stack, so that it can be restored later.
59 //
60 // runtime.cgocallbackg (below) is now running on a real goroutine
61 // stack (not an m.g0 stack).  First it calls runtime.exitsyscall, which will
62 // block until the $GOMAXPROCS limit allows running this goroutine.
63 // Once exitsyscall has returned, it is safe to do things like call the memory
64 // allocator or invoke the Go callback function.  runtime.cgocallbackg
65 // first defers a function to unwind m.g0.sched.sp, so that if p.GoF
66 // panics, m.g0.sched.sp will be restored to its old value: the m.g0 stack
67 // and the m.curg stack will be unwound in lock step.
68 // Then it calls _cgoexp_GoF(frame).
69 //
70 // _cgoexp_GoF, which was generated by cmd/cgo, unpacks the arguments
71 // from frame, calls p.GoF, writes the results back to frame, and
72 // returns. Now we start unwinding this whole process.
73 //
74 // runtime.cgocallbackg pops but does not execute the deferred
75 // function to unwind m.g0.sched.sp, calls runtime.entersyscall, and
76 // returns to runtime.cgocallback.
77 //
78 // After it regains control, runtime.cgocallback switches back to
79 // m.g0's stack (the pointer is still in m.g0.sched.sp), restores the old
80 // m.g0.sched.sp value from the stack, and returns to crosscall2.
81 //
82 // crosscall2 restores the callee-save registers for gcc and returns
83 // to GoF, which unpacks any result values and returns to f.
84
85 package runtime
86
87 import (
88         "internal/goarch"
89         "runtime/internal/atomic"
90         "runtime/internal/sys"
91         "unsafe"
92 )
93
94 // Addresses collected in a cgo backtrace when crashing.
95 // Length must match arg.Max in x_cgo_callers in runtime/cgo/gcc_traceback.c.
96 type cgoCallers [32]uintptr
97
98 // argset matches runtime/cgo/linux_syscall.c:argset_t
99 type argset struct {
100         args   unsafe.Pointer
101         retval uintptr
102 }
103
104 // wrapper for syscall package to call cgocall for libc (cgo) calls.
105 //go:linkname syscall_cgocaller syscall.cgocaller
106 //go:nosplit
107 //go:uintptrescapes
108 func syscall_cgocaller(fn unsafe.Pointer, args ...uintptr) uintptr {
109         as := argset{args: unsafe.Pointer(&args[0])}
110         cgocall(fn, unsafe.Pointer(&as))
111         return as.retval
112 }
113
114 var ncgocall uint64 // number of cgo calls in total for dead m
115
116 // Call from Go to C.
117 //
118 // This must be nosplit because it's used for syscalls on some
119 // platforms. Syscalls may have untyped arguments on the stack, so
120 // it's not safe to grow or scan the stack.
121 //
122 //go:nosplit
123 func cgocall(fn, arg unsafe.Pointer) int32 {
124         if !iscgo && GOOS != "solaris" && GOOS != "illumos" && GOOS != "windows" {
125                 throw("cgocall unavailable")
126         }
127
128         if fn == nil {
129                 throw("cgocall nil")
130         }
131
132         if raceenabled {
133                 racereleasemerge(unsafe.Pointer(&racecgosync))
134         }
135
136         mp := getg().m
137         mp.ncgocall++
138         mp.ncgo++
139
140         // Reset traceback.
141         mp.cgoCallers[0] = 0
142
143         // Announce we are entering a system call
144         // so that the scheduler knows to create another
145         // M to run goroutines while we are in the
146         // foreign code.
147         //
148         // The call to asmcgocall is guaranteed not to
149         // grow the stack and does not allocate memory,
150         // so it is safe to call while "in a system call", outside
151         // the $GOMAXPROCS accounting.
152         //
153         // fn may call back into Go code, in which case we'll exit the
154         // "system call", run the Go code (which may grow the stack),
155         // and then re-enter the "system call" reusing the PC and SP
156         // saved by entersyscall here.
157         entersyscall()
158
159         // Tell asynchronous preemption that we're entering external
160         // code. We do this after entersyscall because this may block
161         // and cause an async preemption to fail, but at this point a
162         // sync preemption will succeed (though this is not a matter
163         // of correctness).
164         osPreemptExtEnter(mp)
165
166         mp.incgo = true
167         errno := asmcgocall(fn, arg)
168
169         // Update accounting before exitsyscall because exitsyscall may
170         // reschedule us on to a different M.
171         mp.incgo = false
172         mp.ncgo--
173
174         osPreemptExtExit(mp)
175
176         exitsyscall()
177
178         // Note that raceacquire must be called only after exitsyscall has
179         // wired this M to a P.
180         if raceenabled {
181                 raceacquire(unsafe.Pointer(&racecgosync))
182         }
183
184         // From the garbage collector's perspective, time can move
185         // backwards in the sequence above. If there's a callback into
186         // Go code, GC will see this function at the call to
187         // asmcgocall. When the Go call later returns to C, the
188         // syscall PC/SP is rolled back and the GC sees this function
189         // back at the call to entersyscall. Normally, fn and arg
190         // would be live at entersyscall and dead at asmcgocall, so if
191         // time moved backwards, GC would see these arguments as dead
192         // and then live. Prevent these undead arguments from crashing
193         // GC by forcing them to stay live across this time warp.
194         KeepAlive(fn)
195         KeepAlive(arg)
196         KeepAlive(mp)
197
198         return errno
199 }
200
201 // Call from C back to Go. fn must point to an ABIInternal Go entry-point.
202 //go:nosplit
203 func cgocallbackg(fn, frame unsafe.Pointer, ctxt uintptr) {
204         gp := getg()
205         if gp != gp.m.curg {
206                 println("runtime: bad g in cgocallback")
207                 exit(2)
208         }
209
210         // The call from C is on gp.m's g0 stack, so we must ensure
211         // that we stay on that M. We have to do this before calling
212         // exitsyscall, since it would otherwise be free to move us to
213         // a different M. The call to unlockOSThread is in unwindm.
214         lockOSThread()
215
216         // Save current syscall parameters, so m.syscall can be
217         // used again if callback decide to make syscall.
218         syscall := gp.m.syscall
219
220         // entersyscall saves the caller's SP to allow the GC to trace the Go
221         // stack. However, since we're returning to an earlier stack frame and
222         // need to pair with the entersyscall() call made by cgocall, we must
223         // save syscall* and let reentersyscall restore them.
224         savedsp := unsafe.Pointer(gp.syscallsp)
225         savedpc := gp.syscallpc
226         exitsyscall() // coming out of cgo call
227         gp.m.incgo = false
228
229         osPreemptExtExit(gp.m)
230
231         cgocallbackg1(fn, frame, ctxt)
232
233         // At this point unlockOSThread has been called.
234         // The following code must not change to a different m.
235         // This is enforced by checking incgo in the schedule function.
236
237         osPreemptExtEnter(gp.m)
238
239         gp.m.incgo = true
240         // going back to cgo call
241         reentersyscall(savedpc, uintptr(savedsp))
242
243         gp.m.syscall = syscall
244 }
245
246 func cgocallbackg1(fn, frame unsafe.Pointer, ctxt uintptr) {
247         gp := getg()
248         if gp.m.needextram || atomic.Load(&extraMWaiters) > 0 {
249                 gp.m.needextram = false
250                 systemstack(newextram)
251         }
252
253         if ctxt != 0 {
254                 s := append(gp.cgoCtxt, ctxt)
255
256                 // Now we need to set gp.cgoCtxt = s, but we could get
257                 // a SIGPROF signal while manipulating the slice, and
258                 // the SIGPROF handler could pick up gp.cgoCtxt while
259                 // tracing up the stack.  We need to ensure that the
260                 // handler always sees a valid slice, so set the
261                 // values in an order such that it always does.
262                 p := (*slice)(unsafe.Pointer(&gp.cgoCtxt))
263                 atomicstorep(unsafe.Pointer(&p.array), unsafe.Pointer(&s[0]))
264                 p.cap = cap(s)
265                 p.len = len(s)
266
267                 defer func(gp *g) {
268                         // Decrease the length of the slice by one, safely.
269                         p := (*slice)(unsafe.Pointer(&gp.cgoCtxt))
270                         p.len--
271                 }(gp)
272         }
273
274         if gp.m.ncgo == 0 {
275                 // The C call to Go came from a thread not currently running
276                 // any Go. In the case of -buildmode=c-archive or c-shared,
277                 // this call may be coming in before package initialization
278                 // is complete. Wait until it is.
279                 <-main_init_done
280         }
281
282         // Add entry to defer stack in case of panic.
283         restore := true
284         defer unwindm(&restore)
285
286         if raceenabled {
287                 raceacquire(unsafe.Pointer(&racecgosync))
288         }
289
290         // Invoke callback. This function is generated by cmd/cgo and
291         // will unpack the argument frame and call the Go function.
292         var cb func(frame unsafe.Pointer)
293         cbFV := funcval{uintptr(fn)}
294         *(*unsafe.Pointer)(unsafe.Pointer(&cb)) = noescape(unsafe.Pointer(&cbFV))
295         cb(frame)
296
297         if raceenabled {
298                 racereleasemerge(unsafe.Pointer(&racecgosync))
299         }
300
301         // Do not unwind m->g0->sched.sp.
302         // Our caller, cgocallback, will do that.
303         restore = false
304 }
305
306 func unwindm(restore *bool) {
307         if *restore {
308                 // Restore sp saved by cgocallback during
309                 // unwind of g's stack (see comment at top of file).
310                 mp := acquirem()
311                 sched := &mp.g0.sched
312                 sched.sp = *(*uintptr)(unsafe.Pointer(sched.sp + alignUp(sys.MinFrameSize, sys.StackAlign)))
313
314                 // Do the accounting that cgocall will not have a chance to do
315                 // during an unwind.
316                 //
317                 // In the case where a Go call originates from C, ncgo is 0
318                 // and there is no matching cgocall to end.
319                 if mp.ncgo > 0 {
320                         mp.incgo = false
321                         mp.ncgo--
322                         osPreemptExtExit(mp)
323                 }
324
325                 releasem(mp)
326         }
327
328         // Undo the call to lockOSThread in cgocallbackg.
329         // We must still stay on the same m.
330         unlockOSThread()
331 }
332
333 // called from assembly
334 func badcgocallback() {
335         throw("misaligned stack in cgocallback")
336 }
337
338 // called from (incomplete) assembly
339 func cgounimpl() {
340         throw("cgo not implemented")
341 }
342
343 var racecgosync uint64 // represents possible synchronization in C code
344
345 // Pointer checking for cgo code.
346
347 // We want to detect all cases where a program that does not use
348 // unsafe makes a cgo call passing a Go pointer to memory that
349 // contains a Go pointer. Here a Go pointer is defined as a pointer
350 // to memory allocated by the Go runtime. Programs that use unsafe
351 // can evade this restriction easily, so we don't try to catch them.
352 // The cgo program will rewrite all possibly bad pointer arguments to
353 // call cgoCheckPointer, where we can catch cases of a Go pointer
354 // pointing to a Go pointer.
355
356 // Complicating matters, taking the address of a slice or array
357 // element permits the C program to access all elements of the slice
358 // or array. In that case we will see a pointer to a single element,
359 // but we need to check the entire data structure.
360
361 // The cgoCheckPointer call takes additional arguments indicating that
362 // it was called on an address expression. An additional argument of
363 // true means that it only needs to check a single element. An
364 // additional argument of a slice or array means that it needs to
365 // check the entire slice/array, but nothing else. Otherwise, the
366 // pointer could be anything, and we check the entire heap object,
367 // which is conservative but safe.
368
369 // When and if we implement a moving garbage collector,
370 // cgoCheckPointer will pin the pointer for the duration of the cgo
371 // call.  (This is necessary but not sufficient; the cgo program will
372 // also have to change to pin Go pointers that cannot point to Go
373 // pointers.)
374
375 // cgoCheckPointer checks if the argument contains a Go pointer that
376 // points to a Go pointer, and panics if it does.
377 func cgoCheckPointer(ptr interface{}, arg interface{}) {
378         if debug.cgocheck == 0 {
379                 return
380         }
381
382         ep := efaceOf(&ptr)
383         t := ep._type
384
385         top := true
386         if arg != nil && (t.kind&kindMask == kindPtr || t.kind&kindMask == kindUnsafePointer) {
387                 p := ep.data
388                 if t.kind&kindDirectIface == 0 {
389                         p = *(*unsafe.Pointer)(p)
390                 }
391                 if p == nil || !cgoIsGoPointer(p) {
392                         return
393                 }
394                 aep := efaceOf(&arg)
395                 switch aep._type.kind & kindMask {
396                 case kindBool:
397                         if t.kind&kindMask == kindUnsafePointer {
398                                 // We don't know the type of the element.
399                                 break
400                         }
401                         pt := (*ptrtype)(unsafe.Pointer(t))
402                         cgoCheckArg(pt.elem, p, true, false, cgoCheckPointerFail)
403                         return
404                 case kindSlice:
405                         // Check the slice rather than the pointer.
406                         ep = aep
407                         t = ep._type
408                 case kindArray:
409                         // Check the array rather than the pointer.
410                         // Pass top as false since we have a pointer
411                         // to the array.
412                         ep = aep
413                         t = ep._type
414                         top = false
415                 default:
416                         throw("can't happen")
417                 }
418         }
419
420         cgoCheckArg(t, ep.data, t.kind&kindDirectIface == 0, top, cgoCheckPointerFail)
421 }
422
423 const cgoCheckPointerFail = "cgo argument has Go pointer to Go pointer"
424 const cgoResultFail = "cgo result has Go pointer"
425
426 // cgoCheckArg is the real work of cgoCheckPointer. The argument p
427 // is either a pointer to the value (of type t), or the value itself,
428 // depending on indir. The top parameter is whether we are at the top
429 // level, where Go pointers are allowed.
430 func cgoCheckArg(t *_type, p unsafe.Pointer, indir, top bool, msg string) {
431         if t.ptrdata == 0 || p == nil {
432                 // If the type has no pointers there is nothing to do.
433                 return
434         }
435
436         switch t.kind & kindMask {
437         default:
438                 throw("can't happen")
439         case kindArray:
440                 at := (*arraytype)(unsafe.Pointer(t))
441                 if !indir {
442                         if at.len != 1 {
443                                 throw("can't happen")
444                         }
445                         cgoCheckArg(at.elem, p, at.elem.kind&kindDirectIface == 0, top, msg)
446                         return
447                 }
448                 for i := uintptr(0); i < at.len; i++ {
449                         cgoCheckArg(at.elem, p, true, top, msg)
450                         p = add(p, at.elem.size)
451                 }
452         case kindChan, kindMap:
453                 // These types contain internal pointers that will
454                 // always be allocated in the Go heap. It's never OK
455                 // to pass them to C.
456                 panic(errorString(msg))
457         case kindFunc:
458                 if indir {
459                         p = *(*unsafe.Pointer)(p)
460                 }
461                 if !cgoIsGoPointer(p) {
462                         return
463                 }
464                 panic(errorString(msg))
465         case kindInterface:
466                 it := *(**_type)(p)
467                 if it == nil {
468                         return
469                 }
470                 // A type known at compile time is OK since it's
471                 // constant. A type not known at compile time will be
472                 // in the heap and will not be OK.
473                 if inheap(uintptr(unsafe.Pointer(it))) {
474                         panic(errorString(msg))
475                 }
476                 p = *(*unsafe.Pointer)(add(p, goarch.PtrSize))
477                 if !cgoIsGoPointer(p) {
478                         return
479                 }
480                 if !top {
481                         panic(errorString(msg))
482                 }
483                 cgoCheckArg(it, p, it.kind&kindDirectIface == 0, false, msg)
484         case kindSlice:
485                 st := (*slicetype)(unsafe.Pointer(t))
486                 s := (*slice)(p)
487                 p = s.array
488                 if p == nil || !cgoIsGoPointer(p) {
489                         return
490                 }
491                 if !top {
492                         panic(errorString(msg))
493                 }
494                 if st.elem.ptrdata == 0 {
495                         return
496                 }
497                 for i := 0; i < s.cap; i++ {
498                         cgoCheckArg(st.elem, p, true, false, msg)
499                         p = add(p, st.elem.size)
500                 }
501         case kindString:
502                 ss := (*stringStruct)(p)
503                 if !cgoIsGoPointer(ss.str) {
504                         return
505                 }
506                 if !top {
507                         panic(errorString(msg))
508                 }
509         case kindStruct:
510                 st := (*structtype)(unsafe.Pointer(t))
511                 if !indir {
512                         if len(st.fields) != 1 {
513                                 throw("can't happen")
514                         }
515                         cgoCheckArg(st.fields[0].typ, p, st.fields[0].typ.kind&kindDirectIface == 0, top, msg)
516                         return
517                 }
518                 for _, f := range st.fields {
519                         if f.typ.ptrdata == 0 {
520                                 continue
521                         }
522                         cgoCheckArg(f.typ, add(p, f.offset()), true, top, msg)
523                 }
524         case kindPtr, kindUnsafePointer:
525                 if indir {
526                         p = *(*unsafe.Pointer)(p)
527                         if p == nil {
528                                 return
529                         }
530                 }
531
532                 if !cgoIsGoPointer(p) {
533                         return
534                 }
535                 if !top {
536                         panic(errorString(msg))
537                 }
538
539                 cgoCheckUnknownPointer(p, msg)
540         }
541 }
542
543 // cgoCheckUnknownPointer is called for an arbitrary pointer into Go
544 // memory. It checks whether that Go memory contains any other
545 // pointer into Go memory. If it does, we panic.
546 // The return values are unused but useful to see in panic tracebacks.
547 func cgoCheckUnknownPointer(p unsafe.Pointer, msg string) (base, i uintptr) {
548         if inheap(uintptr(p)) {
549                 b, span, _ := findObject(uintptr(p), 0, 0)
550                 base = b
551                 if base == 0 {
552                         return
553                 }
554                 hbits := heapBitsForAddr(base)
555                 n := span.elemsize
556                 for i = uintptr(0); i < n; i += goarch.PtrSize {
557                         if !hbits.morePointers() {
558                                 // No more possible pointers.
559                                 break
560                         }
561                         if hbits.isPointer() && cgoIsGoPointer(*(*unsafe.Pointer)(unsafe.Pointer(base + i))) {
562                                 panic(errorString(msg))
563                         }
564                         hbits = hbits.next()
565                 }
566
567                 return
568         }
569
570         for _, datap := range activeModules() {
571                 if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) {
572                         // We have no way to know the size of the object.
573                         // We have to assume that it might contain a pointer.
574                         panic(errorString(msg))
575                 }
576                 // In the text or noptr sections, we know that the
577                 // pointer does not point to a Go pointer.
578         }
579
580         return
581 }
582
583 // cgoIsGoPointer reports whether the pointer is a Go pointer--a
584 // pointer to Go memory. We only care about Go memory that might
585 // contain pointers.
586 //go:nosplit
587 //go:nowritebarrierrec
588 func cgoIsGoPointer(p unsafe.Pointer) bool {
589         if p == nil {
590                 return false
591         }
592
593         if inHeapOrStack(uintptr(p)) {
594                 return true
595         }
596
597         for _, datap := range activeModules() {
598                 if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) {
599                         return true
600                 }
601         }
602
603         return false
604 }
605
606 // cgoInRange reports whether p is between start and end.
607 //go:nosplit
608 //go:nowritebarrierrec
609 func cgoInRange(p unsafe.Pointer, start, end uintptr) bool {
610         return start <= uintptr(p) && uintptr(p) < end
611 }
612
613 // cgoCheckResult is called to check the result parameter of an
614 // exported Go function. It panics if the result is or contains a Go
615 // pointer.
616 func cgoCheckResult(val interface{}) {
617         if debug.cgocheck == 0 {
618                 return
619         }
620
621         ep := efaceOf(&val)
622         t := ep._type
623         cgoCheckArg(t, ep.data, t.kind&kindDirectIface == 0, false, cgoResultFail)
624 }