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

View as plain text