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