Source file 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/abi"
    89  	"internal/goarch"
    90  	"internal/goexperiment"
    91  	"internal/runtime/sys"
    92  	"unsafe"
    93  )
    94  
    95  // Addresses collected in a cgo backtrace when crashing.
    96  // Length must match arg.Max in x_cgo_callers in runtime/cgo/gcc_traceback.c.
    97  type cgoCallers [32]uintptr
    98  
    99  // argset matches runtime/cgo/linux_syscall.c:argset_t
   100  type argset struct {
   101  	args   unsafe.Pointer
   102  	retval uintptr
   103  }
   104  
   105  // cgoSyscall is populated by runtime/cgo on platforms where libc setxid
   106  // syscall wrappers are implemented in Go.
   107  //
   108  //go:linknamestd cgoSyscall
   109  var cgoSyscall func(fn unsafe.Pointer, a0, a1, a2 uintptr) uintptr
   110  
   111  // wrapper for syscall package to call cgocall for libc (cgo) calls.
   112  //
   113  //go:linkname syscall_cgocaller syscall.cgocaller
   114  //go:nosplit
   115  //go:uintptrescapes
   116  func syscall_cgocaller(fn unsafe.Pointer, args ...uintptr) uintptr {
   117  	if goexperiment.RuntimeCgoPurego && cgoSyscall != nil {
   118  		var a0, a1, a2 uintptr
   119  		if len(args) > 0 {
   120  			a0 = args[0]
   121  		}
   122  		if len(args) > 1 {
   123  			a1 = args[1]
   124  		}
   125  		if len(args) > 2 {
   126  			a2 = args[2]
   127  		}
   128  		lockOSThread()
   129  		r := cgoSyscall(noescape(fn), a0, a1, a2)
   130  		unlockOSThread()
   131  		return r
   132  	}
   133  	as := argset{args: unsafe.Pointer(&args[0])}
   134  	cgocall(fn, unsafe.Pointer(&as))
   135  	return as.retval
   136  }
   137  
   138  var ncgocall uint64 // number of cgo calls in total for dead m
   139  
   140  // Call from Go to C.
   141  //
   142  // This must be nosplit because it's used for syscalls on some
   143  // platforms. Syscalls may have untyped arguments on the stack, so
   144  // it's not safe to grow or scan the stack.
   145  //
   146  // cgocall should be an internal detail,
   147  // but widely used packages access it using linkname.
   148  // Notable members of the hall of shame include:
   149  //   - github.com/ebitengine/purego
   150  //
   151  // Do not remove or change the type signature.
   152  // See go.dev/issue/67401.
   153  //
   154  //go:linkname cgocall
   155  //go:nosplit
   156  func cgocall(fn, arg unsafe.Pointer) int32 {
   157  	if !iscgo && GOOS != "solaris" && GOOS != "illumos" && GOOS != "windows" {
   158  		throw("cgocall unavailable")
   159  	}
   160  
   161  	if fn == nil {
   162  		throw("cgocall nil")
   163  	}
   164  
   165  	if raceenabled {
   166  		racereleasemerge(unsafe.Pointer(&racecgosync))
   167  	}
   168  
   169  	mp := getg().m
   170  	mp.ncgocall++
   171  
   172  	// Reset traceback.
   173  	mp.cgoCallers[0] = 0
   174  
   175  	// Announce we are entering a system call
   176  	// so that the scheduler knows to create another
   177  	// M to run goroutines while we are in the
   178  	// foreign code.
   179  	//
   180  	// The call to asmcgocall is guaranteed not to
   181  	// grow the stack and does not allocate memory,
   182  	// so it is safe to call while "in a system call", outside
   183  	// the $GOMAXPROCS accounting.
   184  	//
   185  	// fn may call back into Go code, in which case we'll exit the
   186  	// "system call", run the Go code (which may grow the stack),
   187  	// and then re-enter the "system call" reusing the PC and SP
   188  	// saved by entersyscall here.
   189  	if GOOS == "windows" && mp.syncIOWorker && sched.npidle.Load() == 0 {
   190  		// Synchronous pipe I/O may need a peer goroutine to make progress.
   191  		// If no other P is idle, release ours now instead of waiting for
   192  		// sysmon to retake it. Otherwise, let a short call keep its P.
   193  		entersyscallblock()
   194  	} else {
   195  		entersyscall()
   196  	}
   197  
   198  	mp.incgo = true
   199  	// We use ncgo as a check during execution tracing for whether there is
   200  	// any C on the call stack, which there will be after this point. If
   201  	// there isn't, we can use frame pointer unwinding to collect call
   202  	// stacks efficiently. This will be the case for the first Go-to-C call
   203  	// on a stack, so it's preferable to update it here, after we emit a
   204  	// trace event in entersyscall above.
   205  	mp.ncgo++
   206  
   207  	errno := asmcgocall(fn, arg)
   208  
   209  	// Update accounting before exitsyscall because exitsyscall may
   210  	// reschedule us on to a different M.
   211  	mp.incgo = false
   212  	mp.ncgo--
   213  
   214  	// After exitsyscall we can be rescheduled on a different M,
   215  	// so we need to restore the original M's winsyscall.
   216  	winsyscall := mp.winsyscall
   217  
   218  	exitsyscall()
   219  
   220  	getg().m.winsyscall = winsyscall
   221  
   222  	// Note that raceacquire must be called only after exitsyscall has
   223  	// wired this M to a P.
   224  	if raceenabled {
   225  		raceacquire(unsafe.Pointer(&racecgosync))
   226  	}
   227  
   228  	if sys.DITSupported {
   229  		// C code may have enabled or disabled DIT on this thread, restore
   230  		// our state to the expected one.
   231  		ditEnabled := sys.DITEnabled()
   232  		gp := getg()
   233  		if !gp.ditWanted && ditEnabled {
   234  			sys.DisableDIT()
   235  		} else if gp.ditWanted && !ditEnabled {
   236  			sys.EnableDIT()
   237  		}
   238  	}
   239  
   240  	// From the garbage collector's perspective, time can move
   241  	// backwards in the sequence above. If there's a callback into
   242  	// Go code, GC will see this function at the call to
   243  	// asmcgocall. When the Go call later returns to C, the
   244  	// syscall PC/SP is rolled back and the GC sees this function
   245  	// back at the call to entersyscall. Normally, fn and arg
   246  	// would be live at entersyscall and dead at asmcgocall, so if
   247  	// time moved backwards, GC would see these arguments as dead
   248  	// and then live. Prevent these undead arguments from crashing
   249  	// GC by forcing them to stay live across this time warp.
   250  	KeepAlive(fn)
   251  	KeepAlive(arg)
   252  	KeepAlive(mp)
   253  
   254  	return errno
   255  }
   256  
   257  // Set or reset the system stack bounds for a callback on sp.
   258  //
   259  // Must be nosplit because it is called by needm prior to fully initializing
   260  // the M.
   261  //
   262  //go:nosplit
   263  func callbackUpdateSystemStack(mp *m, sp uintptr, signal bool) {
   264  	g0 := mp.g0
   265  
   266  	if !mp.isextra {
   267  		// We allocated the stack for standard Ms. Don't replace the
   268  		// stack bounds with estimated ones when we already initialized
   269  		// with the exact ones.
   270  		return
   271  	}
   272  
   273  	inBound := sp > g0.stack.lo && sp <= g0.stack.hi
   274  	if inBound && mp.g0StackAccurate {
   275  		// This M has called into Go before and has the stack bounds
   276  		// initialized. We have the accurate stack bounds, and the SP
   277  		// is in bounds. We expect it continues to run within the same
   278  		// bounds.
   279  		return
   280  	}
   281  
   282  	// We don't have an accurate stack bounds (either it never calls
   283  	// into Go before, or we couldn't get the accurate bounds), or the
   284  	// current SP is not within the previous bounds (the stack may have
   285  	// changed between calls). We need to update the stack bounds.
   286  	//
   287  	// N.B. we need to update the stack bounds even if SP appears to
   288  	// already be in bounds, if our bounds are estimated dummy bounds
   289  	// (below). We may be in a different region within the same actual
   290  	// stack bounds, but our estimates were not accurate. Or the actual
   291  	// stack bounds could have shifted but still have partial overlap with
   292  	// our dummy bounds. If we failed to update in that case, we could find
   293  	// ourselves seemingly called near the bottom of the stack bounds, where
   294  	// we quickly run out of space.
   295  
   296  	// Set the stack bounds to match the current stack. If we don't
   297  	// actually know how big the stack is, like we don't know how big any
   298  	// scheduling stack is, but we assume there's at least 32 kB. If we
   299  	// can get a more accurate stack bound from pthread, use that, provided
   300  	// it actually contains SP.
   301  	g0.stack.hi = sp + 1024
   302  	g0.stack.lo = sp - 32*1024
   303  	g0.stackguard0 = g0.stack.lo + stackGuard
   304  	g0.stackguard1 = g0.stackguard0
   305  	mp.g0StackAccurate = false
   306  	if !signal && ((goexperiment.RuntimeCgoPurego && cgoGetStackBound != nil) || _cgo_getstackbound != nil) {
   307  		// Don't adjust if called from the signal handler.
   308  		// We are on the signal stack, not the pthread stack.
   309  		// (We could get the stack bounds from sigaltstack, but
   310  		// we're getting out of the signal handler very soon
   311  		// anyway. Not worth it.)
   312  		var bounds [2]uintptr
   313  		if goexperiment.RuntimeCgoPurego && cgoGetStackBound != nil {
   314  			bounds[0], bounds[1] = cgoGetStackBound()
   315  		} else {
   316  			asmcgocall(_cgo_getstackbound, unsafe.Pointer(&bounds))
   317  		}
   318  		// getstackbound is an unsupported no-op on Windows.
   319  		//
   320  		// On Unix systems, if the API to get accurate stack bounds is
   321  		// not available, it returns zeros.
   322  		//
   323  		// Don't use these bounds if they don't contain SP. Perhaps we
   324  		// were called by something not using the standard thread
   325  		// stack.
   326  		if bounds[0] != 0 && sp > bounds[0] && sp <= bounds[1] {
   327  			g0.stack.lo = bounds[0]
   328  			g0.stack.hi = bounds[1]
   329  			g0.stackguard0 = g0.stack.lo + stackGuard
   330  			g0.stackguard1 = g0.stackguard0
   331  			mp.g0StackAccurate = true
   332  		}
   333  	}
   334  }
   335  
   336  // Call from C back to Go. fn must point to an ABIInternal Go entry-point.
   337  //
   338  //go:nosplit
   339  func cgocallbackg(fn, frame unsafe.Pointer, ctxt uintptr) {
   340  	gp := getg()
   341  	if gp != gp.m.curg {
   342  		println("runtime: bad g in cgocallback")
   343  		exit(2)
   344  	}
   345  
   346  	sp := gp.m.g0.sched.sp // system sp saved by cgocallback.
   347  	oldStack := gp.m.g0.stack
   348  	oldAccurate := gp.m.g0StackAccurate
   349  	callbackUpdateSystemStack(gp.m, sp, false)
   350  
   351  	// The call from C is on gp.m's g0 stack, so we must ensure
   352  	// that we stay on that M. We have to do this before calling
   353  	// exitsyscall, since it would otherwise be free to move us to
   354  	// a different M. The call to unlockOSThread is in this function
   355  	// after cgocallbackg1, or in the case of panicking, in unwindm.
   356  	lockOSThread()
   357  
   358  	checkm := gp.m
   359  
   360  	// Save current syscall parameters, so m.winsyscall can be
   361  	// used again if callback decide to make syscall.
   362  	winsyscall := gp.m.winsyscall
   363  
   364  	// entersyscall saves the caller's SP to allow the GC to trace the Go
   365  	// stack. However, since we're returning to an earlier stack frame and
   366  	// need to pair with the entersyscall() call made by cgocall, we must
   367  	// save syscall* and let reentersyscall restore them.
   368  	//
   369  	// Note: savedsp and savedbp MUST be held in locals as an unsafe.Pointer.
   370  	// When we call into Go, the stack is free to be moved. If these locals
   371  	// aren't visible in the stack maps, they won't get updated properly,
   372  	// and will end up being stale when restored by reentersyscall.
   373  	savedsp := unsafe.Pointer(gp.syscallsp)
   374  	savedpc := gp.syscallpc
   375  	savedbp := unsafe.Pointer(gp.syscallbp)
   376  	exitsyscall() // coming out of cgo call
   377  	gp.m.incgo = false
   378  	if gp.m.isextra {
   379  		gp.m.isExtraInC = false
   380  	}
   381  
   382  	if gp.nocgocallback {
   383  		panic("runtime: function marked with #cgo nocallback called back into Go")
   384  	}
   385  
   386  	cgocallbackg1(fn, frame, ctxt)
   387  
   388  	// At this point we're about to call unlockOSThread.
   389  	// The following code must not change to a different m.
   390  	// This is enforced by checking incgo in the schedule function.
   391  	gp.m.incgo = true
   392  	unlockOSThread()
   393  
   394  	if gp.m.isextra && gp.m.ncgo == 0 {
   395  		// There are no active cgocalls above this frame (ncgo == 0),
   396  		// thus there can't be more Go frames above this frame.
   397  		gp.m.isExtraInC = true
   398  	}
   399  
   400  	if gp.m != checkm {
   401  		throw("m changed unexpectedly in cgocallbackg")
   402  	}
   403  
   404  	// going back to cgo call
   405  	reentersyscall(savedpc, uintptr(savedsp), uintptr(savedbp))
   406  
   407  	gp.m.winsyscall = winsyscall
   408  
   409  	// Restore the old g0 stack bounds
   410  	gp.m.g0.stack = oldStack
   411  	gp.m.g0.stackguard0 = oldStack.lo + stackGuard
   412  	gp.m.g0.stackguard1 = gp.m.g0.stackguard0
   413  	gp.m.g0StackAccurate = oldAccurate
   414  }
   415  
   416  // cgoCtxtTop returns the index of the innermost cgo traceback context
   417  // of gp, or -1 if gp has none.
   418  //
   419  //go:nosplit
   420  func (gp *g) cgoCtxtTop() int {
   421  	c := gp.cgoCtxt
   422  	if c == nil {
   423  		return -1
   424  	}
   425  	return len(*c) - 1
   426  }
   427  
   428  func cgocallbackg1(fn, frame unsafe.Pointer, ctxt uintptr) {
   429  	gp := getg()
   430  
   431  	if gp.m.needextram || extraMWaiters.Load() > 0 {
   432  		gp.m.needextram = false
   433  		systemstack(newextram)
   434  	}
   435  
   436  	if ctxt != 0 {
   437  		c := gp.cgoCtxt
   438  		if c == nil {
   439  			// Few goroutines ever have a cgo traceback context,
   440  			// so the slice is allocated on first use and kept
   441  			// when the g is reused.
   442  			c = new([]uintptr)
   443  			gp.cgoCtxt = c
   444  		}
   445  		s := append(*c, ctxt)
   446  
   447  		// Now we need to set *gp.cgoCtxt = s, but we could get
   448  		// a SIGPROF signal while manipulating the slice, and
   449  		// the SIGPROF handler could pick up gp.cgoCtxt while
   450  		// tracing up the stack. We need to ensure that the
   451  		// handler always sees a valid slice, so set the
   452  		// values in an order such that it always does.
   453  		p := (*slice)(unsafe.Pointer(c))
   454  		atomicstorep(unsafe.Pointer(&p.array), unsafe.Pointer(&s[0]))
   455  		p.cap = cap(s)
   456  		p.len = len(s)
   457  
   458  		defer func(c *[]uintptr) {
   459  			// Decrease the length of the slice by one, safely.
   460  			p := (*slice)(unsafe.Pointer(c))
   461  			p.len--
   462  		}(c)
   463  	}
   464  
   465  	if gp.m.ncgo == 0 {
   466  		// The C call to Go came from a thread not currently running
   467  		// any Go. In the case of -buildmode=c-archive or c-shared,
   468  		// this call may be coming in before package initialization
   469  		// is complete. Don't proceed until it is.
   470  		//
   471  		// We check a bool first for speed, and wait on a channel
   472  		// if it's not ready.
   473  		//
   474  		// In race mode, skip the optimization and always use the
   475  		// channel, which has the race instrumentation.
   476  		if raceenabled || !mainInitDone.Load() {
   477  			<-mainInitDoneChan
   478  		}
   479  	}
   480  
   481  	// Check whether the profiler needs to be turned on or off; this route to
   482  	// run Go code does not use runtime.execute, so bypasses the check there.
   483  	hz := sched.profilehz
   484  	if gp.m.profilehz != hz {
   485  		setThreadCPUProfiler(hz)
   486  	}
   487  
   488  	// Add entry to defer stack in case of panic.
   489  	restore := true
   490  	defer unwindm(&restore)
   491  
   492  	var ditStateM, ditStateG bool
   493  	if debug.dataindependenttiming == 1 && gp.m.isextra {
   494  		// We only need to enable DIT for threads that were created by C, as it
   495  		// should already by enabled on threads that were created by Go.
   496  		ditStateM = sys.EnableDIT()
   497  	} else if sys.DITSupported && debug.dataindependenttiming != 1 {
   498  		// C code may have enabled or disabled DIT on this thread. Set the flag
   499  		// on the M and G accordingly, saving their previous state to restore
   500  		// on return from the callback.
   501  		ditStateM, ditStateG = gp.m.ditEnabled, gp.ditWanted
   502  		ditEnabled := sys.DITEnabled()
   503  		gp.ditWanted = ditEnabled
   504  		gp.m.ditEnabled = ditEnabled
   505  	}
   506  
   507  	if raceenabled {
   508  		raceacquire(unsafe.Pointer(&racecgosync))
   509  	}
   510  
   511  	// Invoke callback. This function is generated by cmd/cgo and
   512  	// will unpack the argument frame and call the Go function.
   513  	var cb func(frame unsafe.Pointer)
   514  	cbFV := funcval{uintptr(fn)}
   515  	*(*unsafe.Pointer)(unsafe.Pointer(&cb)) = noescape(unsafe.Pointer(&cbFV))
   516  	cb(frame)
   517  
   518  	if raceenabled {
   519  		racereleasemerge(unsafe.Pointer(&racecgosync))
   520  	}
   521  
   522  	if debug.dataindependenttiming == 1 && !ditStateM {
   523  		// Only unset DIT if it wasn't already enabled when cgocallback was called.
   524  		sys.DisableDIT()
   525  	} else if sys.DITSupported && debug.dataindependenttiming != 1 {
   526  		// Restore DIT state on M and G.
   527  		gp.ditWanted = ditStateG
   528  		gp.m.ditEnabled = ditStateM
   529  		if !ditStateM {
   530  			sys.DisableDIT()
   531  		}
   532  	}
   533  
   534  	// Do not unwind m->g0->sched.sp.
   535  	// Our caller, cgocallback, will do that.
   536  	restore = false
   537  }
   538  
   539  func unwindm(restore *bool) {
   540  	if *restore {
   541  		// Restore sp saved by cgocallback during
   542  		// unwind of g's stack (see comment at top of file).
   543  		mp := acquirem()
   544  		sched := &mp.g0.sched
   545  		sched.sp = *(*uintptr)(unsafe.Pointer(sched.sp + alignUp(sys.MinFrameSize, sys.StackAlign)))
   546  
   547  		// Do the accounting that cgocall will not have a chance to do
   548  		// during an unwind.
   549  		//
   550  		// In the case where a Go call originates from C, ncgo is 0
   551  		// and there is no matching cgocall to end.
   552  		if mp.ncgo > 0 {
   553  			mp.incgo = false
   554  			mp.ncgo--
   555  		}
   556  
   557  		// Undo the call to lockOSThread in cgocallbackg, only on the
   558  		// panicking path. In normal return case cgocallbackg will call
   559  		// unlockOSThread, ensuring no preemption point after the unlock.
   560  		// Here we don't need to worry about preemption, because we're
   561  		// panicking out of the callback and unwinding the g0 stack,
   562  		// instead of reentering cgo (which requires the same thread).
   563  		unlockOSThread()
   564  
   565  		releasem(mp)
   566  	}
   567  }
   568  
   569  // called from assembly.
   570  func badcgocallback() {
   571  	throw("misaligned stack in cgocallback")
   572  }
   573  
   574  // called from (incomplete) assembly.
   575  func cgounimpl() {
   576  	throw("cgo not implemented")
   577  }
   578  
   579  var racecgosync uint64 // represents possible synchronization in C code
   580  
   581  // Pointer checking for cgo code.
   582  
   583  // We want to detect all cases where a program that does not use
   584  // unsafe makes a cgo call passing a Go pointer to memory that
   585  // contains an unpinned Go pointer. Here a Go pointer is defined as a
   586  // pointer to memory allocated by the Go runtime. Programs that use
   587  // unsafe can evade this restriction easily, so we don't try to catch
   588  // them. The cgo program will rewrite all possibly bad pointer
   589  // arguments to call cgoCheckPointer, where we can catch cases of a Go
   590  // pointer pointing to an unpinned Go pointer.
   591  
   592  // Complicating matters, taking the address of a slice or array
   593  // element permits the C program to access all elements of the slice
   594  // or array. In that case we will see a pointer to a single element,
   595  // but we need to check the entire data structure.
   596  
   597  // The cgoCheckPointer call takes additional arguments indicating that
   598  // it was called on an address expression. An additional argument of
   599  // true means that it only needs to check a single element. An
   600  // additional argument of a slice or array means that it needs to
   601  // check the entire slice/array, but nothing else. Otherwise, the
   602  // pointer could be anything, and we check the entire heap object,
   603  // which is conservative but safe.
   604  
   605  // When and if we implement a moving garbage collector,
   606  // cgoCheckPointer will pin the pointer for the duration of the cgo
   607  // call.  (This is necessary but not sufficient; the cgo program will
   608  // also have to change to pin Go pointers that cannot point to Go
   609  // pointers.)
   610  
   611  // cgoCheckPointer checks if the argument contains a Go pointer that
   612  // points to an unpinned Go pointer, and panics if it does.
   613  func cgoCheckPointer(ptr any, arg any) {
   614  	if !goexperiment.CgoCheck2 && debug.cgocheck == 0 {
   615  		return
   616  	}
   617  
   618  	ep := efaceOf(&ptr)
   619  	t := ep._type
   620  
   621  	top := true
   622  	if arg != nil && (t.Kind() == abi.Pointer || t.Kind() == abi.UnsafePointer) {
   623  		p := ep.data
   624  		if !t.IsDirectIface() {
   625  			p = *(*unsafe.Pointer)(p)
   626  		}
   627  		if p == nil || !cgoIsGoPointer(p) {
   628  			return
   629  		}
   630  		aep := efaceOf(&arg)
   631  		switch aep._type.Kind() {
   632  		case abi.Bool:
   633  			if t.Kind() == abi.UnsafePointer {
   634  				// We don't know the type of the element.
   635  				break
   636  			}
   637  			pt := (*ptrtype)(unsafe.Pointer(t))
   638  			cgoCheckArg(pt.Elem, p, true, false, cgoCheckPointerFail)
   639  			return
   640  		case abi.Slice:
   641  			// Check the slice rather than the pointer.
   642  			ep = aep
   643  			t = ep._type
   644  		case abi.Array:
   645  			// Check the array rather than the pointer.
   646  			// Pass top as false since we have a pointer
   647  			// to the array.
   648  			ep = aep
   649  			t = ep._type
   650  			top = false
   651  		case abi.Pointer:
   652  			// The Go code is indexing into a pointer to an array,
   653  			// and we have been passed the pointer-to-array.
   654  			// Check the array rather than the pointer.
   655  			pt := (*abi.PtrType)(unsafe.Pointer(aep._type))
   656  			t = pt.Elem
   657  			if t.Kind() != abi.Array {
   658  				throw("can't happen")
   659  			}
   660  			ep = aep
   661  			top = false
   662  		default:
   663  			throw("can't happen")
   664  		}
   665  	}
   666  
   667  	cgoCheckArg(t, ep.data, !t.IsDirectIface(), top, cgoCheckPointerFail)
   668  }
   669  
   670  type cgoErrorMsg int
   671  
   672  const (
   673  	cgoCheckPointerFail cgoErrorMsg = iota
   674  	cgoResultFail
   675  )
   676  
   677  // cgoCheckArg is the real work of cgoCheckPointer and cgoCheckResult.
   678  // The argument p is either a pointer to the value (of type t), or the value
   679  // itself, depending on indir. The top parameter is whether we are at the top
   680  // level, where Go pointers are allowed. Go pointers to pinned objects are
   681  // allowed as long as they don't reference other unpinned pointers.
   682  func cgoCheckArg(t *_type, p unsafe.Pointer, indir, top bool, msg cgoErrorMsg) {
   683  	if !t.Pointers() || p == nil {
   684  		// If the type has no pointers there is nothing to do.
   685  		return
   686  	}
   687  
   688  	switch t.Kind() {
   689  	default:
   690  		throw("can't happen")
   691  	case abi.Array:
   692  		at := (*arraytype)(unsafe.Pointer(t))
   693  		if !indir {
   694  			if at.Len != 1 {
   695  				throw("can't happen")
   696  			}
   697  			cgoCheckArg(at.Elem, p, !at.Elem.IsDirectIface(), top, msg)
   698  			return
   699  		}
   700  		for i := uintptr(0); i < at.Len; i++ {
   701  			cgoCheckArg(at.Elem, p, true, top, msg)
   702  			p = add(p, at.Elem.Size_)
   703  		}
   704  	case abi.Chan, abi.Map:
   705  		// These types contain internal pointers that will
   706  		// always be allocated in the Go heap. It's never OK
   707  		// to pass them to C.
   708  		panic(cgoFormatErr(msg, t.Kind()))
   709  	case abi.Func:
   710  		if indir {
   711  			p = *(*unsafe.Pointer)(p)
   712  		}
   713  		if !cgoIsGoPointer(p) {
   714  			return
   715  		}
   716  		panic(cgoFormatErr(msg, t.Kind()))
   717  	case abi.Interface:
   718  		it := *(**_type)(p)
   719  		if it == nil {
   720  			return
   721  		}
   722  		// A type known at compile time is OK since it's
   723  		// constant. A type not known at compile time will be
   724  		// in the heap and will not be OK.
   725  		if inheap(uintptr(unsafe.Pointer(it))) {
   726  			panic(cgoFormatErr(msg, t.Kind()))
   727  		}
   728  		p = *(*unsafe.Pointer)(add(p, goarch.PtrSize))
   729  		if !cgoIsGoPointer(p) {
   730  			return
   731  		}
   732  		if !top && !isPinned(p) {
   733  			panic(cgoFormatErr(msg, t.Kind()))
   734  		}
   735  		cgoCheckArg(it, p, !it.IsDirectIface(), false, msg)
   736  	case abi.Slice:
   737  		st := (*slicetype)(unsafe.Pointer(t))
   738  		s := (*slice)(p)
   739  		p = s.array
   740  		if p == nil || !cgoIsGoPointer(p) {
   741  			return
   742  		}
   743  		if !top && !isPinned(p) {
   744  			panic(cgoFormatErr(msg, t.Kind()))
   745  		}
   746  		if !st.Elem.Pointers() {
   747  			return
   748  		}
   749  		for i := 0; i < s.cap; i++ {
   750  			cgoCheckArg(st.Elem, p, true, false, msg)
   751  			p = add(p, st.Elem.Size_)
   752  		}
   753  	case abi.String:
   754  		ss := (*stringStruct)(p)
   755  		if !cgoIsGoPointer(ss.str) {
   756  			return
   757  		}
   758  		if !top && !isPinned(ss.str) {
   759  			panic(cgoFormatErr(msg, t.Kind()))
   760  		}
   761  	case abi.Struct:
   762  		st := (*structtype)(unsafe.Pointer(t))
   763  		if !indir {
   764  			if len(st.Fields) != 1 {
   765  				throw("can't happen")
   766  			}
   767  			cgoCheckArg(st.Fields[0].Typ, p, !st.Fields[0].Typ.IsDirectIface(), top, msg)
   768  			return
   769  		}
   770  		for _, f := range st.Fields {
   771  			if !f.Typ.Pointers() {
   772  				continue
   773  			}
   774  			cgoCheckArg(f.Typ, add(p, f.Offset), true, top, msg)
   775  		}
   776  	case abi.Pointer, abi.UnsafePointer:
   777  		if indir {
   778  			p = *(*unsafe.Pointer)(p)
   779  			if p == nil {
   780  				return
   781  			}
   782  		}
   783  
   784  		if !cgoIsGoPointer(p) {
   785  			return
   786  		}
   787  		if !top && !isPinned(p) {
   788  			panic(cgoFormatErr(msg, t.Kind()))
   789  		}
   790  
   791  		cgoCheckUnknownPointer(p, msg)
   792  	}
   793  }
   794  
   795  // cgoCheckUnknownPointer is called for an arbitrary pointer into Go
   796  // memory. It checks whether that Go memory contains any other
   797  // pointer into unpinned Go memory. If it does, we panic.
   798  // The return values are unused but useful to see in panic tracebacks.
   799  func cgoCheckUnknownPointer(p unsafe.Pointer, msg cgoErrorMsg) (base, i uintptr) {
   800  	if inheap(uintptr(p)) {
   801  		b, span, _ := findObject(uintptr(p), 0, 0)
   802  		base = b
   803  		if base == 0 {
   804  			return
   805  		}
   806  		tp := span.typePointersOfUnchecked(base)
   807  		for {
   808  			var addr uintptr
   809  			if tp, addr = tp.next(base + span.elemsize); addr == 0 {
   810  				break
   811  			}
   812  			pp := *(*unsafe.Pointer)(unsafe.Pointer(addr))
   813  			if cgoIsGoPointer(pp) && !isPinned(pp) {
   814  				panic(cgoFormatErr(msg, abi.Pointer))
   815  			}
   816  		}
   817  		return
   818  	}
   819  
   820  	for _, datap := range activeModules() {
   821  		if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) {
   822  			// We have no way to know the size of the object.
   823  			// We have to assume that it might contain a pointer.
   824  			panic(cgoFormatErr(msg, abi.Pointer))
   825  		}
   826  		// In the text or noptr sections, we know that the
   827  		// pointer does not point to a Go pointer.
   828  	}
   829  
   830  	return
   831  }
   832  
   833  // cgoIsGoPointer reports whether the pointer is a Go pointer--a
   834  // pointer to Go memory. We only care about Go memory that might
   835  // contain pointers.
   836  //
   837  //go:nosplit
   838  //go:nowritebarrierrec
   839  func cgoIsGoPointer(p unsafe.Pointer) bool {
   840  	if p == nil {
   841  		return false
   842  	}
   843  
   844  	if inHeapOrStack(uintptr(p)) {
   845  		return true
   846  	}
   847  
   848  	for _, datap := range activeModules() {
   849  		if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) {
   850  			return true
   851  		}
   852  	}
   853  
   854  	return false
   855  }
   856  
   857  // cgoInRange reports whether p is between start and end.
   858  //
   859  //go:nosplit
   860  //go:nowritebarrierrec
   861  func cgoInRange(p unsafe.Pointer, start, end uintptr) bool {
   862  	return start <= uintptr(p) && uintptr(p) < end
   863  }
   864  
   865  // cgoCheckResult is called to check the result parameter of an
   866  // exported Go function. It panics if the result is or contains any
   867  // other pointer into unpinned Go memory.
   868  func cgoCheckResult(val any) {
   869  	if !goexperiment.CgoCheck2 && debug.cgocheck == 0 {
   870  		return
   871  	}
   872  
   873  	ep := efaceOf(&val)
   874  	t := ep._type
   875  	if t == nil {
   876  		return
   877  	}
   878  	cgoCheckArg(t, ep.data, !t.IsDirectIface(), false, cgoResultFail)
   879  }
   880  
   881  // cgoFormatErr is called by cgoCheckArg and cgoCheckUnknownPointer
   882  // to format panic error messages.
   883  func cgoFormatErr(error cgoErrorMsg, kind abi.Kind) errorString {
   884  	var msg, kindname string
   885  	var cgoFunction string = "unknown"
   886  	var offset int
   887  	var buf [20]byte
   888  
   889  	// We expect one of these abi.Kind from cgoCheckArg
   890  	switch kind {
   891  	case abi.Chan:
   892  		kindname = "channel"
   893  	case abi.Func:
   894  		kindname = "function"
   895  	case abi.Interface:
   896  		kindname = "interface"
   897  	case abi.Map:
   898  		kindname = "map"
   899  	case abi.Pointer:
   900  		kindname = "pointer"
   901  	case abi.Slice:
   902  		kindname = "slice"
   903  	case abi.String:
   904  		kindname = "string"
   905  	case abi.Struct:
   906  		kindname = "struct"
   907  	case abi.UnsafePointer:
   908  		kindname = "unsafe pointer"
   909  	default:
   910  		kindname = "pointer"
   911  	}
   912  
   913  	// The cgo function name might need an offset to be obtained
   914  	if error == cgoResultFail {
   915  		offset = 21
   916  	}
   917  
   918  	// Relatively to cgoFormatErr, this is the stack frame:
   919  	// 0. cgoFormatErr
   920  	// 1. cgoCheckArg or cgoCheckUnknownPointer
   921  	// 2. cgoCheckPointer or cgoCheckResult
   922  	// 3. cgo function
   923  	pc, path, line, ok := Caller(3)
   924  	if ok && error == cgoResultFail {
   925  		function := FuncForPC(pc)
   926  
   927  		if function != nil {
   928  			// Expected format of cgo function name:
   929  			// - caller: _cgoexp_3c910ddb72c4_foo
   930  			if offset > len(function.Name()) {
   931  				cgoFunction = function.Name()
   932  			} else {
   933  				cgoFunction = function.Name()[offset:]
   934  			}
   935  		}
   936  	}
   937  
   938  	switch error {
   939  	case cgoResultFail:
   940  		msg = path + ":" + string(itoa(buf[:], uint64(line)))
   941  		msg += ": result of Go function " + cgoFunction + " called from cgo"
   942  		msg += " is unpinned Go " + kindname + " or points to unpinned Go " + kindname
   943  	case cgoCheckPointerFail:
   944  		msg += "argument of cgo function has Go pointer to unpinned Go " + kindname
   945  	}
   946  
   947  	return errorString(msg)
   948  }
   949  

View as plain text