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 // 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.
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).
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).
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.
23 // After it regains control, runtime.asmcgocall switches back to the
24 // original g (m->curg)'s stack and returns to runtime.cgocall.
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.
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.
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.
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.
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.)
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.
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).
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.
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.
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.
82 // crosscall2 restores the callee-save registers for gcc and returns
83 // to GoF, which unpacks any result values and returns to f.
89 "internal/goexperiment"
90 "runtime/internal/sys"
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
98 // argset matches runtime/cgo/linux_syscall.c:argset_t
104 // wrapper for syscall package to call cgocall for libc (cgo) calls.
106 //go:linkname syscall_cgocaller syscall.cgocaller
109 func syscall_cgocaller(fn unsafe.Pointer, args ...uintptr) uintptr {
110 as := argset{args: unsafe.Pointer(&args[0])}
111 cgocall(fn, unsafe.Pointer(&as))
115 var ncgocall uint64 // number of cgo calls in total for dead m
117 // Call from Go to C.
119 // This must be nosplit because it's used for syscalls on some
120 // platforms. Syscalls may have untyped arguments on the stack, so
121 // it's not safe to grow or scan the stack.
124 func cgocall(fn, arg unsafe.Pointer) int32 {
125 if !iscgo && GOOS != "solaris" && GOOS != "illumos" && GOOS != "windows" {
126 throw("cgocall unavailable")
134 racereleasemerge(unsafe.Pointer(&racecgosync))
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
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.
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.
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
164 osPreemptExtEnter(mp)
167 // We use ncgo as a check during execution tracing for whether there is
168 // any C on the call stack, which there will be after this point. If
169 // there isn't, we can use frame pointer unwinding to collect call
170 // stacks efficiently. This will be the case for the first Go-to-C call
171 // on a stack, so it's preferable to update it here, after we emit a
172 // trace event in entersyscall above.
175 errno := asmcgocall(fn, arg)
177 // Update accounting before exitsyscall because exitsyscall may
178 // reschedule us on to a different M.
186 // Note that raceacquire must be called only after exitsyscall has
187 // wired this M to a P.
189 raceacquire(unsafe.Pointer(&racecgosync))
192 // From the garbage collector's perspective, time can move
193 // backwards in the sequence above. If there's a callback into
194 // Go code, GC will see this function at the call to
195 // asmcgocall. When the Go call later returns to C, the
196 // syscall PC/SP is rolled back and the GC sees this function
197 // back at the call to entersyscall. Normally, fn and arg
198 // would be live at entersyscall and dead at asmcgocall, so if
199 // time moved backwards, GC would see these arguments as dead
200 // and then live. Prevent these undead arguments from crashing
201 // GC by forcing them to stay live across this time warp.
209 // Call from C back to Go. fn must point to an ABIInternal Go entry-point.
212 func cgocallbackg(fn, frame unsafe.Pointer, ctxt uintptr) {
215 println("runtime: bad g in cgocallback")
219 // The call from C is on gp.m's g0 stack, so we must ensure
220 // that we stay on that M. We have to do this before calling
221 // exitsyscall, since it would otherwise be free to move us to
222 // a different M. The call to unlockOSThread is in unwindm.
227 // Save current syscall parameters, so m.syscall can be
228 // used again if callback decide to make syscall.
229 syscall := gp.m.syscall
231 // entersyscall saves the caller's SP to allow the GC to trace the Go
232 // stack. However, since we're returning to an earlier stack frame and
233 // need to pair with the entersyscall() call made by cgocall, we must
234 // save syscall* and let reentersyscall restore them.
235 savedsp := unsafe.Pointer(gp.syscallsp)
236 savedpc := gp.syscallpc
237 exitsyscall() // coming out of cgo call
240 gp.m.isExtraInC = false
243 osPreemptExtExit(gp.m)
245 if gp.nocgocallback {
246 panic("runtime: function marked with #cgo nocallback called back into Go")
249 cgocallbackg1(fn, frame, ctxt) // will call unlockOSThread
251 // At this point unlockOSThread has been called.
252 // The following code must not change to a different m.
253 // This is enforced by checking incgo in the schedule function.
257 gp.m.isExtraInC = true
261 throw("m changed unexpectedly in cgocallbackg")
264 osPreemptExtEnter(gp.m)
266 // going back to cgo call
267 reentersyscall(savedpc, uintptr(savedsp))
269 gp.m.syscall = syscall
272 func cgocallbackg1(fn, frame unsafe.Pointer, ctxt uintptr) {
275 // When we return, undo the call to lockOSThread in cgocallbackg.
276 // We must still stay on the same m.
277 defer unlockOSThread()
279 if gp.m.needextram || extraMWaiters.Load() > 0 {
280 gp.m.needextram = false
281 systemstack(newextram)
285 s := append(gp.cgoCtxt, ctxt)
287 // Now we need to set gp.cgoCtxt = s, but we could get
288 // a SIGPROF signal while manipulating the slice, and
289 // the SIGPROF handler could pick up gp.cgoCtxt while
290 // tracing up the stack. We need to ensure that the
291 // handler always sees a valid slice, so set the
292 // values in an order such that it always does.
293 p := (*slice)(unsafe.Pointer(&gp.cgoCtxt))
294 atomicstorep(unsafe.Pointer(&p.array), unsafe.Pointer(&s[0]))
299 // Decrease the length of the slice by one, safely.
300 p := (*slice)(unsafe.Pointer(&gp.cgoCtxt))
306 // The C call to Go came from a thread not currently running
307 // any Go. In the case of -buildmode=c-archive or c-shared,
308 // this call may be coming in before package initialization
309 // is complete. Wait until it is.
313 // Check whether the profiler needs to be turned on or off; this route to
314 // run Go code does not use runtime.execute, so bypasses the check there.
315 hz := sched.profilehz
316 if gp.m.profilehz != hz {
317 setThreadCPUProfiler(hz)
320 // Add entry to defer stack in case of panic.
322 defer unwindm(&restore)
325 raceacquire(unsafe.Pointer(&racecgosync))
328 // Invoke callback. This function is generated by cmd/cgo and
329 // will unpack the argument frame and call the Go function.
330 var cb func(frame unsafe.Pointer)
331 cbFV := funcval{uintptr(fn)}
332 *(*unsafe.Pointer)(unsafe.Pointer(&cb)) = noescape(unsafe.Pointer(&cbFV))
336 racereleasemerge(unsafe.Pointer(&racecgosync))
339 // Do not unwind m->g0->sched.sp.
340 // Our caller, cgocallback, will do that.
344 func unwindm(restore *bool) {
346 // Restore sp saved by cgocallback during
347 // unwind of g's stack (see comment at top of file).
349 sched := &mp.g0.sched
350 sched.sp = *(*uintptr)(unsafe.Pointer(sched.sp + alignUp(sys.MinFrameSize, sys.StackAlign)))
352 // Do the accounting that cgocall will not have a chance to do
355 // In the case where a Go call originates from C, ncgo is 0
356 // and there is no matching cgocall to end.
367 // called from assembly.
368 func badcgocallback() {
369 throw("misaligned stack in cgocallback")
372 // called from (incomplete) assembly.
374 throw("cgo not implemented")
377 var racecgosync uint64 // represents possible synchronization in C code
379 // Pointer checking for cgo code.
381 // We want to detect all cases where a program that does not use
382 // unsafe makes a cgo call passing a Go pointer to memory that
383 // contains an unpinned Go pointer. Here a Go pointer is defined as a
384 // pointer to memory allocated by the Go runtime. Programs that use
385 // unsafe can evade this restriction easily, so we don't try to catch
386 // them. The cgo program will rewrite all possibly bad pointer
387 // arguments to call cgoCheckPointer, where we can catch cases of a Go
388 // pointer pointing to an unpinned Go pointer.
390 // Complicating matters, taking the address of a slice or array
391 // element permits the C program to access all elements of the slice
392 // or array. In that case we will see a pointer to a single element,
393 // but we need to check the entire data structure.
395 // The cgoCheckPointer call takes additional arguments indicating that
396 // it was called on an address expression. An additional argument of
397 // true means that it only needs to check a single element. An
398 // additional argument of a slice or array means that it needs to
399 // check the entire slice/array, but nothing else. Otherwise, the
400 // pointer could be anything, and we check the entire heap object,
401 // which is conservative but safe.
403 // When and if we implement a moving garbage collector,
404 // cgoCheckPointer will pin the pointer for the duration of the cgo
405 // call. (This is necessary but not sufficient; the cgo program will
406 // also have to change to pin Go pointers that cannot point to Go
409 // cgoCheckPointer checks if the argument contains a Go pointer that
410 // points to an unpinned Go pointer, and panics if it does.
411 func cgoCheckPointer(ptr any, arg any) {
412 if !goexperiment.CgoCheck2 && debug.cgocheck == 0 {
420 if arg != nil && (t.Kind_&kindMask == kindPtr || t.Kind_&kindMask == kindUnsafePointer) {
422 if t.Kind_&kindDirectIface == 0 {
423 p = *(*unsafe.Pointer)(p)
425 if p == nil || !cgoIsGoPointer(p) {
429 switch aep._type.Kind_ & kindMask {
431 if t.Kind_&kindMask == kindUnsafePointer {
432 // We don't know the type of the element.
435 pt := (*ptrtype)(unsafe.Pointer(t))
436 cgoCheckArg(pt.Elem, p, true, false, cgoCheckPointerFail)
439 // Check the slice rather than the pointer.
443 // Check the array rather than the pointer.
444 // Pass top as false since we have a pointer
450 throw("can't happen")
454 cgoCheckArg(t, ep.data, t.Kind_&kindDirectIface == 0, top, cgoCheckPointerFail)
457 const cgoCheckPointerFail = "cgo argument has Go pointer to unpinned Go pointer"
458 const cgoResultFail = "cgo result has Go pointer"
460 // cgoCheckArg is the real work of cgoCheckPointer. The argument p
461 // is either a pointer to the value (of type t), or the value itself,
462 // depending on indir. The top parameter is whether we are at the top
463 // level, where Go pointers are allowed. Go pointers to pinned objects are
465 func cgoCheckArg(t *_type, p unsafe.Pointer, indir, top bool, msg string) {
466 if t.PtrBytes == 0 || p == nil {
467 // If the type has no pointers there is nothing to do.
471 switch t.Kind_ & kindMask {
473 throw("can't happen")
475 at := (*arraytype)(unsafe.Pointer(t))
478 throw("can't happen")
480 cgoCheckArg(at.Elem, p, at.Elem.Kind_&kindDirectIface == 0, top, msg)
483 for i := uintptr(0); i < at.Len; i++ {
484 cgoCheckArg(at.Elem, p, true, top, msg)
485 p = add(p, at.Elem.Size_)
487 case kindChan, kindMap:
488 // These types contain internal pointers that will
489 // always be allocated in the Go heap. It's never OK
490 // to pass them to C.
491 panic(errorString(msg))
494 p = *(*unsafe.Pointer)(p)
496 if !cgoIsGoPointer(p) {
499 panic(errorString(msg))
505 // A type known at compile time is OK since it's
506 // constant. A type not known at compile time will be
507 // in the heap and will not be OK.
508 if inheap(uintptr(unsafe.Pointer(it))) {
509 panic(errorString(msg))
511 p = *(*unsafe.Pointer)(add(p, goarch.PtrSize))
512 if !cgoIsGoPointer(p) {
515 if !top && !isPinned(p) {
516 panic(errorString(msg))
518 cgoCheckArg(it, p, it.Kind_&kindDirectIface == 0, false, msg)
520 st := (*slicetype)(unsafe.Pointer(t))
523 if p == nil || !cgoIsGoPointer(p) {
526 if !top && !isPinned(p) {
527 panic(errorString(msg))
529 if st.Elem.PtrBytes == 0 {
532 for i := 0; i < s.cap; i++ {
533 cgoCheckArg(st.Elem, p, true, false, msg)
534 p = add(p, st.Elem.Size_)
537 ss := (*stringStruct)(p)
538 if !cgoIsGoPointer(ss.str) {
541 if !top && !isPinned(ss.str) {
542 panic(errorString(msg))
545 st := (*structtype)(unsafe.Pointer(t))
547 if len(st.Fields) != 1 {
548 throw("can't happen")
550 cgoCheckArg(st.Fields[0].Typ, p, st.Fields[0].Typ.Kind_&kindDirectIface == 0, top, msg)
553 for _, f := range st.Fields {
554 if f.Typ.PtrBytes == 0 {
557 cgoCheckArg(f.Typ, add(p, f.Offset), true, top, msg)
559 case kindPtr, kindUnsafePointer:
561 p = *(*unsafe.Pointer)(p)
567 if !cgoIsGoPointer(p) {
570 if !top && !isPinned(p) {
571 panic(errorString(msg))
574 cgoCheckUnknownPointer(p, msg)
578 // cgoCheckUnknownPointer is called for an arbitrary pointer into Go
579 // memory. It checks whether that Go memory contains any other
580 // pointer into unpinned Go memory. If it does, we panic.
581 // The return values are unused but useful to see in panic tracebacks.
582 func cgoCheckUnknownPointer(p unsafe.Pointer, msg string) (base, i uintptr) {
583 if inheap(uintptr(p)) {
584 b, span, _ := findObject(uintptr(p), 0, 0)
590 hbits := heapBitsForAddr(base, n)
593 if hbits, addr = hbits.next(); addr == 0 {
596 pp := *(*unsafe.Pointer)(unsafe.Pointer(addr))
597 if cgoIsGoPointer(pp) && !isPinned(pp) {
598 panic(errorString(msg))
605 for _, datap := range activeModules() {
606 if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) {
607 // We have no way to know the size of the object.
608 // We have to assume that it might contain a pointer.
609 panic(errorString(msg))
611 // In the text or noptr sections, we know that the
612 // pointer does not point to a Go pointer.
618 // cgoIsGoPointer reports whether the pointer is a Go pointer--a
619 // pointer to Go memory. We only care about Go memory that might
623 //go:nowritebarrierrec
624 func cgoIsGoPointer(p unsafe.Pointer) bool {
629 if inHeapOrStack(uintptr(p)) {
633 for _, datap := range activeModules() {
634 if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) {
642 // cgoInRange reports whether p is between start and end.
645 //go:nowritebarrierrec
646 func cgoInRange(p unsafe.Pointer, start, end uintptr) bool {
647 return start <= uintptr(p) && uintptr(p) < end
650 // cgoCheckResult is called to check the result parameter of an
651 // exported Go function. It panics if the result is or contains a Go
653 func cgoCheckResult(val any) {
654 if !goexperiment.CgoCheck2 && debug.cgocheck == 0 {
660 cgoCheckArg(t, ep.data, t.Kind_&kindDirectIface == 0, false, cgoResultFail)