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/goarch"
    89  	"internal/goexperiment"
    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  //
   106  //go:linkname syscall_cgocaller syscall.cgocaller
   107  //go:nosplit
   108  //go:uintptrescapes
   109  func syscall_cgocaller(fn unsafe.Pointer, args ...uintptr) uintptr {
   110  	as := argset{args: unsafe.Pointer(&args[0])}
   111  	cgocall(fn, unsafe.Pointer(&as))
   112  	return as.retval
   113  }
   114  
   115  var ncgocall uint64 // number of cgo calls in total for dead m
   116  
   117  // Call from Go to C.
   118  //
   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.
   122  //
   123  //go:nosplit
   124  func cgocall(fn, arg unsafe.Pointer) int32 {
   125  	if !iscgo && GOOS != "solaris" && GOOS != "illumos" && GOOS != "windows" {
   126  		throw("cgocall unavailable")
   127  	}
   128  
   129  	if fn == nil {
   130  		throw("cgocall nil")
   131  	}
   132  
   133  	if raceenabled {
   134  		racereleasemerge(unsafe.Pointer(&racecgosync))
   135  	}
   136  
   137  	mp := getg().m
   138  	mp.ncgocall++
   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  	// 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.
   173  	mp.ncgo++
   174  
   175  	errno := asmcgocall(fn, arg)
   176  
   177  	// Update accounting before exitsyscall because exitsyscall may
   178  	// reschedule us on to a different M.
   179  	mp.incgo = false
   180  	mp.ncgo--
   181  
   182  	osPreemptExtExit(mp)
   183  
   184  	exitsyscall()
   185  
   186  	// Note that raceacquire must be called only after exitsyscall has
   187  	// wired this M to a P.
   188  	if raceenabled {
   189  		raceacquire(unsafe.Pointer(&racecgosync))
   190  	}
   191  
   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.
   202  	KeepAlive(fn)
   203  	KeepAlive(arg)
   204  	KeepAlive(mp)
   205  
   206  	return errno
   207  }
   208  
   209  // Set or reset the system stack bounds for a callback on sp.
   210  //
   211  // Must be nosplit because it is called by needm prior to fully initializing
   212  // the M.
   213  //
   214  //go:nosplit
   215  func callbackUpdateSystemStack(mp *m, sp uintptr, signal bool) {
   216  	g0 := mp.g0
   217  
   218  	inBound := sp > g0.stack.lo && sp <= g0.stack.hi
   219  	if mp.ncgo > 0 && !inBound {
   220  		// ncgo > 0 indicates that this M was in Go further up the stack
   221  		// (it called C and is now receiving a callback).
   222  		//
   223  		// !inBound indicates that we were called with SP outside the
   224  		// expected system stack bounds (C changed the stack out from
   225  		// under us between the cgocall and cgocallback?).
   226  		//
   227  		// It is not safe for the C call to change the stack out from
   228  		// under us, so throw.
   229  
   230  		// Note that this case isn't possible for signal == true, as
   231  		// that is always passing a new M from needm.
   232  
   233  		// Stack is bogus, but reset the bounds anyway so we can print.
   234  		hi := g0.stack.hi
   235  		lo := g0.stack.lo
   236  		g0.stack.hi = sp + 1024
   237  		g0.stack.lo = sp - 32*1024
   238  		g0.stackguard0 = g0.stack.lo + stackGuard
   239  		g0.stackguard1 = g0.stackguard0
   240  
   241  		print("M ", mp.id, " procid ", mp.procid, " runtime: cgocallback with sp=", hex(sp), " out of bounds [", hex(lo), ", ", hex(hi), "]")
   242  		print("\n")
   243  		exit(2)
   244  	}
   245  
   246  	if !mp.isextra {
   247  		// We allocated the stack for standard Ms. Don't replace the
   248  		// stack bounds with estimated ones when we already initialized
   249  		// with the exact ones.
   250  		return
   251  	}
   252  
   253  	// This M does not have Go further up the stack. However, it may have
   254  	// previously called into Go, initializing the stack bounds. Between
   255  	// that call returning and now the stack may have changed (perhaps the
   256  	// C thread is running a coroutine library). We need to update the
   257  	// stack bounds for this case.
   258  	//
   259  	// N.B. we need to update the stack bounds even if SP appears to
   260  	// already be in bounds. Our "bounds" may actually be estimated dummy
   261  	// bounds (below). The actual stack bounds could have shifted but still
   262  	// have partial overlap with our dummy bounds. If we failed to update
   263  	// in that case, we could find ourselves seemingly called near the
   264  	// bottom of the stack bounds, where we quickly run out of space.
   265  
   266  	// Set the stack bounds to match the current stack. If we don't
   267  	// actually know how big the stack is, like we don't know how big any
   268  	// scheduling stack is, but we assume there's at least 32 kB. If we
   269  	// can get a more accurate stack bound from pthread, use that, provided
   270  	// it actually contains SP..
   271  	g0.stack.hi = sp + 1024
   272  	g0.stack.lo = sp - 32*1024
   273  	if !signal && _cgo_getstackbound != nil {
   274  		// Don't adjust if called from the signal handler.
   275  		// We are on the signal stack, not the pthread stack.
   276  		// (We could get the stack bounds from sigaltstack, but
   277  		// we're getting out of the signal handler very soon
   278  		// anyway. Not worth it.)
   279  		var bounds [2]uintptr
   280  		asmcgocall(_cgo_getstackbound, unsafe.Pointer(&bounds))
   281  		// getstackbound is an unsupported no-op on Windows.
   282  		//
   283  		// Don't use these bounds if they don't contain SP. Perhaps we
   284  		// were called by something not using the standard thread
   285  		// stack.
   286  		if bounds[0] != 0 && sp > bounds[0] && sp <= bounds[1] {
   287  			g0.stack.lo = bounds[0]
   288  			g0.stack.hi = bounds[1]
   289  		}
   290  	}
   291  	g0.stackguard0 = g0.stack.lo + stackGuard
   292  	g0.stackguard1 = g0.stackguard0
   293  }
   294  
   295  // Call from C back to Go. fn must point to an ABIInternal Go entry-point.
   296  //
   297  //go:nosplit
   298  func cgocallbackg(fn, frame unsafe.Pointer, ctxt uintptr) {
   299  	gp := getg()
   300  	if gp != gp.m.curg {
   301  		println("runtime: bad g in cgocallback")
   302  		exit(2)
   303  	}
   304  
   305  	sp := gp.m.g0.sched.sp // system sp saved by cgocallback.
   306  	callbackUpdateSystemStack(gp.m, sp, false)
   307  
   308  	// The call from C is on gp.m's g0 stack, so we must ensure
   309  	// that we stay on that M. We have to do this before calling
   310  	// exitsyscall, since it would otherwise be free to move us to
   311  	// a different M. The call to unlockOSThread is in this function
   312  	// after cgocallbackg1, or in the case of panicking, in unwindm.
   313  	lockOSThread()
   314  
   315  	checkm := gp.m
   316  
   317  	// Save current syscall parameters, so m.syscall can be
   318  	// used again if callback decide to make syscall.
   319  	syscall := gp.m.syscall
   320  
   321  	// entersyscall saves the caller's SP to allow the GC to trace the Go
   322  	// stack. However, since we're returning to an earlier stack frame and
   323  	// need to pair with the entersyscall() call made by cgocall, we must
   324  	// save syscall* and let reentersyscall restore them.
   325  	savedsp := unsafe.Pointer(gp.syscallsp)
   326  	savedpc := gp.syscallpc
   327  	exitsyscall() // coming out of cgo call
   328  	gp.m.incgo = false
   329  	if gp.m.isextra {
   330  		gp.m.isExtraInC = false
   331  	}
   332  
   333  	osPreemptExtExit(gp.m)
   334  
   335  	if gp.nocgocallback {
   336  		panic("runtime: function marked with #cgo nocallback called back into Go")
   337  	}
   338  
   339  	cgocallbackg1(fn, frame, ctxt)
   340  
   341  	// At this point we're about to call unlockOSThread.
   342  	// The following code must not change to a different m.
   343  	// This is enforced by checking incgo in the schedule function.
   344  	gp.m.incgo = true
   345  	unlockOSThread()
   346  
   347  	if gp.m.isextra {
   348  		gp.m.isExtraInC = true
   349  	}
   350  
   351  	if gp.m != checkm {
   352  		throw("m changed unexpectedly in cgocallbackg")
   353  	}
   354  
   355  	osPreemptExtEnter(gp.m)
   356  
   357  	// going back to cgo call
   358  	reentersyscall(savedpc, uintptr(savedsp))
   359  
   360  	gp.m.syscall = syscall
   361  }
   362  
   363  func cgocallbackg1(fn, frame unsafe.Pointer, ctxt uintptr) {
   364  	gp := getg()
   365  
   366  	if gp.m.needextram || extraMWaiters.Load() > 0 {
   367  		gp.m.needextram = false
   368  		systemstack(newextram)
   369  	}
   370  
   371  	if ctxt != 0 {
   372  		s := append(gp.cgoCtxt, ctxt)
   373  
   374  		// Now we need to set gp.cgoCtxt = s, but we could get
   375  		// a SIGPROF signal while manipulating the slice, and
   376  		// the SIGPROF handler could pick up gp.cgoCtxt while
   377  		// tracing up the stack.  We need to ensure that the
   378  		// handler always sees a valid slice, so set the
   379  		// values in an order such that it always does.
   380  		p := (*slice)(unsafe.Pointer(&gp.cgoCtxt))
   381  		atomicstorep(unsafe.Pointer(&p.array), unsafe.Pointer(&s[0]))
   382  		p.cap = cap(s)
   383  		p.len = len(s)
   384  
   385  		defer func(gp *g) {
   386  			// Decrease the length of the slice by one, safely.
   387  			p := (*slice)(unsafe.Pointer(&gp.cgoCtxt))
   388  			p.len--
   389  		}(gp)
   390  	}
   391  
   392  	if gp.m.ncgo == 0 {
   393  		// The C call to Go came from a thread not currently running
   394  		// any Go. In the case of -buildmode=c-archive or c-shared,
   395  		// this call may be coming in before package initialization
   396  		// is complete. Wait until it is.
   397  		<-main_init_done
   398  	}
   399  
   400  	// Check whether the profiler needs to be turned on or off; this route to
   401  	// run Go code does not use runtime.execute, so bypasses the check there.
   402  	hz := sched.profilehz
   403  	if gp.m.profilehz != hz {
   404  		setThreadCPUProfiler(hz)
   405  	}
   406  
   407  	// Add entry to defer stack in case of panic.
   408  	restore := true
   409  	defer unwindm(&restore)
   410  
   411  	if raceenabled {
   412  		raceacquire(unsafe.Pointer(&racecgosync))
   413  	}
   414  
   415  	// Invoke callback. This function is generated by cmd/cgo and
   416  	// will unpack the argument frame and call the Go function.
   417  	var cb func(frame unsafe.Pointer)
   418  	cbFV := funcval{uintptr(fn)}
   419  	*(*unsafe.Pointer)(unsafe.Pointer(&cb)) = noescape(unsafe.Pointer(&cbFV))
   420  	cb(frame)
   421  
   422  	if raceenabled {
   423  		racereleasemerge(unsafe.Pointer(&racecgosync))
   424  	}
   425  
   426  	// Do not unwind m->g0->sched.sp.
   427  	// Our caller, cgocallback, will do that.
   428  	restore = false
   429  }
   430  
   431  func unwindm(restore *bool) {
   432  	if *restore {
   433  		// Restore sp saved by cgocallback during
   434  		// unwind of g's stack (see comment at top of file).
   435  		mp := acquirem()
   436  		sched := &mp.g0.sched
   437  		sched.sp = *(*uintptr)(unsafe.Pointer(sched.sp + alignUp(sys.MinFrameSize, sys.StackAlign)))
   438  
   439  		// Do the accounting that cgocall will not have a chance to do
   440  		// during an unwind.
   441  		//
   442  		// In the case where a Go call originates from C, ncgo is 0
   443  		// and there is no matching cgocall to end.
   444  		if mp.ncgo > 0 {
   445  			mp.incgo = false
   446  			mp.ncgo--
   447  			osPreemptExtExit(mp)
   448  		}
   449  
   450  		// Undo the call to lockOSThread in cgocallbackg, only on the
   451  		// panicking path. In normal return case cgocallbackg will call
   452  		// unlockOSThread, ensuring no preemption point after the unlock.
   453  		// Here we don't need to worry about preemption, because we're
   454  		// panicking out of the callback and unwinding the g0 stack,
   455  		// instead of reentering cgo (which requires the same thread).
   456  		unlockOSThread()
   457  
   458  		releasem(mp)
   459  	}
   460  }
   461  
   462  // called from assembly.
   463  func badcgocallback() {
   464  	throw("misaligned stack in cgocallback")
   465  }
   466  
   467  // called from (incomplete) assembly.
   468  func cgounimpl() {
   469  	throw("cgo not implemented")
   470  }
   471  
   472  var racecgosync uint64 // represents possible synchronization in C code
   473  
   474  // Pointer checking for cgo code.
   475  
   476  // We want to detect all cases where a program that does not use
   477  // unsafe makes a cgo call passing a Go pointer to memory that
   478  // contains an unpinned Go pointer. Here a Go pointer is defined as a
   479  // pointer to memory allocated by the Go runtime. Programs that use
   480  // unsafe can evade this restriction easily, so we don't try to catch
   481  // them. The cgo program will rewrite all possibly bad pointer
   482  // arguments to call cgoCheckPointer, where we can catch cases of a Go
   483  // pointer pointing to an unpinned Go pointer.
   484  
   485  // Complicating matters, taking the address of a slice or array
   486  // element permits the C program to access all elements of the slice
   487  // or array. In that case we will see a pointer to a single element,
   488  // but we need to check the entire data structure.
   489  
   490  // The cgoCheckPointer call takes additional arguments indicating that
   491  // it was called on an address expression. An additional argument of
   492  // true means that it only needs to check a single element. An
   493  // additional argument of a slice or array means that it needs to
   494  // check the entire slice/array, but nothing else. Otherwise, the
   495  // pointer could be anything, and we check the entire heap object,
   496  // which is conservative but safe.
   497  
   498  // When and if we implement a moving garbage collector,
   499  // cgoCheckPointer will pin the pointer for the duration of the cgo
   500  // call.  (This is necessary but not sufficient; the cgo program will
   501  // also have to change to pin Go pointers that cannot point to Go
   502  // pointers.)
   503  
   504  // cgoCheckPointer checks if the argument contains a Go pointer that
   505  // points to an unpinned Go pointer, and panics if it does.
   506  func cgoCheckPointer(ptr any, arg any) {
   507  	if !goexperiment.CgoCheck2 && debug.cgocheck == 0 {
   508  		return
   509  	}
   510  
   511  	ep := efaceOf(&ptr)
   512  	t := ep._type
   513  
   514  	top := true
   515  	if arg != nil && (t.Kind_&kindMask == kindPtr || t.Kind_&kindMask == kindUnsafePointer) {
   516  		p := ep.data
   517  		if t.Kind_&kindDirectIface == 0 {
   518  			p = *(*unsafe.Pointer)(p)
   519  		}
   520  		if p == nil || !cgoIsGoPointer(p) {
   521  			return
   522  		}
   523  		aep := efaceOf(&arg)
   524  		switch aep._type.Kind_ & kindMask {
   525  		case kindBool:
   526  			if t.Kind_&kindMask == kindUnsafePointer {
   527  				// We don't know the type of the element.
   528  				break
   529  			}
   530  			pt := (*ptrtype)(unsafe.Pointer(t))
   531  			cgoCheckArg(pt.Elem, p, true, false, cgoCheckPointerFail)
   532  			return
   533  		case kindSlice:
   534  			// Check the slice rather than the pointer.
   535  			ep = aep
   536  			t = ep._type
   537  		case kindArray:
   538  			// Check the array rather than the pointer.
   539  			// Pass top as false since we have a pointer
   540  			// to the array.
   541  			ep = aep
   542  			t = ep._type
   543  			top = false
   544  		default:
   545  			throw("can't happen")
   546  		}
   547  	}
   548  
   549  	cgoCheckArg(t, ep.data, t.Kind_&kindDirectIface == 0, top, cgoCheckPointerFail)
   550  }
   551  
   552  const cgoCheckPointerFail = "cgo argument has Go pointer to unpinned Go pointer"
   553  const cgoResultFail = "cgo result is unpinned Go pointer or points to unpinned Go pointer"
   554  
   555  // cgoCheckArg is the real work of cgoCheckPointer. The argument p
   556  // is either a pointer to the value (of type t), or the value itself,
   557  // depending on indir. The top parameter is whether we are at the top
   558  // level, where Go pointers are allowed. Go pointers to pinned objects are
   559  // allowed as long as they don't reference other unpinned pointers.
   560  func cgoCheckArg(t *_type, p unsafe.Pointer, indir, top bool, msg string) {
   561  	if t.PtrBytes == 0 || p == nil {
   562  		// If the type has no pointers there is nothing to do.
   563  		return
   564  	}
   565  
   566  	switch t.Kind_ & kindMask {
   567  	default:
   568  		throw("can't happen")
   569  	case kindArray:
   570  		at := (*arraytype)(unsafe.Pointer(t))
   571  		if !indir {
   572  			if at.Len != 1 {
   573  				throw("can't happen")
   574  			}
   575  			cgoCheckArg(at.Elem, p, at.Elem.Kind_&kindDirectIface == 0, top, msg)
   576  			return
   577  		}
   578  		for i := uintptr(0); i < at.Len; i++ {
   579  			cgoCheckArg(at.Elem, p, true, top, msg)
   580  			p = add(p, at.Elem.Size_)
   581  		}
   582  	case kindChan, kindMap:
   583  		// These types contain internal pointers that will
   584  		// always be allocated in the Go heap. It's never OK
   585  		// to pass them to C.
   586  		panic(errorString(msg))
   587  	case kindFunc:
   588  		if indir {
   589  			p = *(*unsafe.Pointer)(p)
   590  		}
   591  		if !cgoIsGoPointer(p) {
   592  			return
   593  		}
   594  		panic(errorString(msg))
   595  	case kindInterface:
   596  		it := *(**_type)(p)
   597  		if it == nil {
   598  			return
   599  		}
   600  		// A type known at compile time is OK since it's
   601  		// constant. A type not known at compile time will be
   602  		// in the heap and will not be OK.
   603  		if inheap(uintptr(unsafe.Pointer(it))) {
   604  			panic(errorString(msg))
   605  		}
   606  		p = *(*unsafe.Pointer)(add(p, goarch.PtrSize))
   607  		if !cgoIsGoPointer(p) {
   608  			return
   609  		}
   610  		if !top && !isPinned(p) {
   611  			panic(errorString(msg))
   612  		}
   613  		cgoCheckArg(it, p, it.Kind_&kindDirectIface == 0, false, msg)
   614  	case kindSlice:
   615  		st := (*slicetype)(unsafe.Pointer(t))
   616  		s := (*slice)(p)
   617  		p = s.array
   618  		if p == nil || !cgoIsGoPointer(p) {
   619  			return
   620  		}
   621  		if !top && !isPinned(p) {
   622  			panic(errorString(msg))
   623  		}
   624  		if st.Elem.PtrBytes == 0 {
   625  			return
   626  		}
   627  		for i := 0; i < s.cap; i++ {
   628  			cgoCheckArg(st.Elem, p, true, false, msg)
   629  			p = add(p, st.Elem.Size_)
   630  		}
   631  	case kindString:
   632  		ss := (*stringStruct)(p)
   633  		if !cgoIsGoPointer(ss.str) {
   634  			return
   635  		}
   636  		if !top && !isPinned(ss.str) {
   637  			panic(errorString(msg))
   638  		}
   639  	case kindStruct:
   640  		st := (*structtype)(unsafe.Pointer(t))
   641  		if !indir {
   642  			if len(st.Fields) != 1 {
   643  				throw("can't happen")
   644  			}
   645  			cgoCheckArg(st.Fields[0].Typ, p, st.Fields[0].Typ.Kind_&kindDirectIface == 0, top, msg)
   646  			return
   647  		}
   648  		for _, f := range st.Fields {
   649  			if f.Typ.PtrBytes == 0 {
   650  				continue
   651  			}
   652  			cgoCheckArg(f.Typ, add(p, f.Offset), true, top, msg)
   653  		}
   654  	case kindPtr, kindUnsafePointer:
   655  		if indir {
   656  			p = *(*unsafe.Pointer)(p)
   657  			if p == nil {
   658  				return
   659  			}
   660  		}
   661  
   662  		if !cgoIsGoPointer(p) {
   663  			return
   664  		}
   665  		if !top && !isPinned(p) {
   666  			panic(errorString(msg))
   667  		}
   668  
   669  		cgoCheckUnknownPointer(p, msg)
   670  	}
   671  }
   672  
   673  // cgoCheckUnknownPointer is called for an arbitrary pointer into Go
   674  // memory. It checks whether that Go memory contains any other
   675  // pointer into unpinned Go memory. If it does, we panic.
   676  // The return values are unused but useful to see in panic tracebacks.
   677  func cgoCheckUnknownPointer(p unsafe.Pointer, msg string) (base, i uintptr) {
   678  	if inheap(uintptr(p)) {
   679  		b, span, _ := findObject(uintptr(p), 0, 0)
   680  		base = b
   681  		if base == 0 {
   682  			return
   683  		}
   684  		if goexperiment.AllocHeaders {
   685  			tp := span.typePointersOfUnchecked(base)
   686  			for {
   687  				var addr uintptr
   688  				if tp, addr = tp.next(base + span.elemsize); addr == 0 {
   689  					break
   690  				}
   691  				pp := *(*unsafe.Pointer)(unsafe.Pointer(addr))
   692  				if cgoIsGoPointer(pp) && !isPinned(pp) {
   693  					panic(errorString(msg))
   694  				}
   695  			}
   696  		} else {
   697  			n := span.elemsize
   698  			hbits := heapBitsForAddr(base, n)
   699  			for {
   700  				var addr uintptr
   701  				if hbits, addr = hbits.next(); addr == 0 {
   702  					break
   703  				}
   704  				pp := *(*unsafe.Pointer)(unsafe.Pointer(addr))
   705  				if cgoIsGoPointer(pp) && !isPinned(pp) {
   706  					panic(errorString(msg))
   707  				}
   708  			}
   709  		}
   710  		return
   711  	}
   712  
   713  	for _, datap := range activeModules() {
   714  		if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) {
   715  			// We have no way to know the size of the object.
   716  			// We have to assume that it might contain a pointer.
   717  			panic(errorString(msg))
   718  		}
   719  		// In the text or noptr sections, we know that the
   720  		// pointer does not point to a Go pointer.
   721  	}
   722  
   723  	return
   724  }
   725  
   726  // cgoIsGoPointer reports whether the pointer is a Go pointer--a
   727  // pointer to Go memory. We only care about Go memory that might
   728  // contain pointers.
   729  //
   730  //go:nosplit
   731  //go:nowritebarrierrec
   732  func cgoIsGoPointer(p unsafe.Pointer) bool {
   733  	if p == nil {
   734  		return false
   735  	}
   736  
   737  	if inHeapOrStack(uintptr(p)) {
   738  		return true
   739  	}
   740  
   741  	for _, datap := range activeModules() {
   742  		if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) {
   743  			return true
   744  		}
   745  	}
   746  
   747  	return false
   748  }
   749  
   750  // cgoInRange reports whether p is between start and end.
   751  //
   752  //go:nosplit
   753  //go:nowritebarrierrec
   754  func cgoInRange(p unsafe.Pointer, start, end uintptr) bool {
   755  	return start <= uintptr(p) && uintptr(p) < end
   756  }
   757  
   758  // cgoCheckResult is called to check the result parameter of an
   759  // exported Go function. It panics if the result is or contains any
   760  // other pointer into unpinned Go memory.
   761  func cgoCheckResult(val any) {
   762  	if !goexperiment.CgoCheck2 && debug.cgocheck == 0 {
   763  		return
   764  	}
   765  
   766  	ep := efaceOf(&val)
   767  	t := ep._type
   768  	cgoCheckArg(t, ep.data, t.Kind_&kindDirectIface == 0, false, cgoResultFail)
   769  }
   770  

View as plain text