cgocall.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. // Cgo call and callback support.
  5. //
  6. // To call into the C function f from Go, the cgo-generated code calls
  7. // runtime.cgocall(_cgo_Cfunc_f, frame), where _cgo_Cfunc_f is a
  8. // gcc-compiled function written by cgo.
  9. //
  10. // runtime.cgocall (below) locks g to m, calls entersyscall
  11. // so as not to block other goroutines or the garbage collector,
  12. // and then calls runtime.asmcgocall(_cgo_Cfunc_f, frame).
  13. //
  14. // runtime.asmcgocall (in asm_$GOARCH.s) switches to the m->g0 stack
  15. // (assumed to be an operating system-allocated stack, so safe to run
  16. // gcc-compiled code on) and calls _cgo_Cfunc_f(frame).
  17. //
  18. // _cgo_Cfunc_f invokes the actual C function f with arguments
  19. // taken from the frame structure, records the results in the frame,
  20. // and returns to runtime.asmcgocall.
  21. //
  22. // After it regains control, runtime.asmcgocall switches back to the
  23. // original g (m->curg)'s stack and returns to runtime.cgocall.
  24. //
  25. // After it regains control, runtime.cgocall calls exitsyscall, which blocks
  26. // until this m can run Go code without violating the $GOMAXPROCS limit,
  27. // and then unlocks g from m.
  28. //
  29. // The above description skipped over the possibility of the gcc-compiled
  30. // function f calling back into Go. If that happens, we continue down
  31. // the rabbit hole during the execution of f.
  32. //
  33. // To make it possible for gcc-compiled C code to call a Go function p.GoF,
  34. // cgo writes a gcc-compiled function named GoF (not p.GoF, since gcc doesn't
  35. // know about packages). The gcc-compiled C function f calls GoF.
  36. //
  37. // GoF calls crosscall2(_cgoexp_GoF, frame, framesize). Crosscall2
  38. // (in cgo/gcc_$GOARCH.S, a gcc-compiled assembly file) is a two-argument
  39. // adapter from the gcc function call ABI to the 6c function call ABI.
  40. // It is called from gcc to call 6c functions. In this case it calls
  41. // _cgoexp_GoF(frame, framesize), still running on m->g0's stack
  42. // and outside the $GOMAXPROCS limit. Thus, this code cannot yet
  43. // call arbitrary Go code directly and must be careful not to allocate
  44. // memory or use up m->g0's stack.
  45. //
  46. // _cgoexp_GoF calls runtime.cgocallback(p.GoF, frame, framesize).
  47. // (The reason for having _cgoexp_GoF instead of writing a crosscall3
  48. // to make this call directly is that _cgoexp_GoF, because it is compiled
  49. // with 6c instead of gcc, can refer to dotted names like
  50. // runtime.cgocallback and p.GoF.)
  51. //
  52. // runtime.cgocallback (in asm_$GOARCH.s) switches from m->g0's
  53. // stack to the original g (m->curg)'s stack, on which it calls
  54. // runtime.cgocallbackg(p.GoF, frame, framesize).
  55. // As part of the stack switch, runtime.cgocallback saves the current
  56. // SP as m->g0->sched.sp, so that any use of m->g0's stack during the
  57. // execution of the callback will be done below the existing stack frames.
  58. // Before overwriting m->g0->sched.sp, it pushes the old value on the
  59. // m->g0 stack, so that it can be restored later.
  60. //
  61. // runtime.cgocallbackg (below) is now running on a real goroutine
  62. // stack (not an m->g0 stack). First it calls runtime.exitsyscall, which will
  63. // block until the $GOMAXPROCS limit allows running this goroutine.
  64. // Once exitsyscall has returned, it is safe to do things like call the memory
  65. // allocator or invoke the Go callback function p.GoF. runtime.cgocallbackg
  66. // first defers a function to unwind m->g0.sched.sp, so that if p.GoF
  67. // panics, m->g0.sched.sp will be restored to its old value: the m->g0 stack
  68. // and the m->curg stack will be unwound in lock step.
  69. // Then it calls p.GoF. Finally it pops but does not execute the deferred
  70. // function, calls runtime.entersyscall, and returns to runtime.cgocallback.
  71. //
  72. // After it regains control, runtime.cgocallback switches back to
  73. // m->g0's stack (the pointer is still in m->g0.sched.sp), restores the old
  74. // m->g0.sched.sp value from the stack, and returns to _cgoexp_GoF.
  75. //
  76. // _cgoexp_GoF immediately returns to crosscall2, which restores the
  77. // callee-save registers for gcc and returns to GoF, which returns to f.
  78. package runtime
  79. import "unsafe"
  80. // Call from Go to C.
  81. //go:nosplit
  82. func cgocall(fn, arg unsafe.Pointer) {
  83. cgocall_errno(fn, arg)
  84. }
  85. //go:nosplit
  86. func cgocall_errno(fn, arg unsafe.Pointer) int32 {
  87. if !iscgo && GOOS != "solaris" && GOOS != "windows" {
  88. gothrow("cgocall unavailable")
  89. }
  90. if fn == nil {
  91. gothrow("cgocall nil")
  92. }
  93. if raceenabled {
  94. racereleasemerge(unsafe.Pointer(&racecgosync))
  95. }
  96. // Create an extra M for callbacks on threads not created by Go on first cgo call.
  97. if needextram == 1 && cas(&needextram, 1, 0) {
  98. onM(newextram)
  99. }
  100. /*
  101. * Lock g to m to ensure we stay on the same stack if we do a
  102. * cgo callback. Add entry to defer stack in case of panic.
  103. */
  104. lockOSThread()
  105. mp := getg().m
  106. mp.ncgocall++
  107. mp.ncgo++
  108. defer endcgo(mp)
  109. /*
  110. * Announce we are entering a system call
  111. * so that the scheduler knows to create another
  112. * M to run goroutines while we are in the
  113. * foreign code.
  114. *
  115. * The call to asmcgocall is guaranteed not to
  116. * split the stack and does not allocate memory,
  117. * so it is safe to call while "in a system call", outside
  118. * the $GOMAXPROCS accounting.
  119. */
  120. entersyscall()
  121. errno := asmcgocall_errno(fn, arg)
  122. exitsyscall()
  123. return errno
  124. }
  125. //go:nosplit
  126. func endcgo(mp *m) {
  127. mp.ncgo--
  128. if mp.ncgo == 0 {
  129. // We are going back to Go and are not in a recursive
  130. // call. Let the GC collect any memory allocated via
  131. // _cgo_allocate that is no longer referenced.
  132. mp.cgomal = nil
  133. }
  134. if raceenabled {
  135. raceacquire(unsafe.Pointer(&racecgosync))
  136. }
  137. unlockOSThread() // invalidates mp
  138. }
  139. // Helper functions for cgo code.
  140. // Filled by schedinit from corresponding C variables,
  141. // which are in turn filled in by dynamic linker when Cgo is available.
  142. var cgoMalloc, cgoFree unsafe.Pointer
  143. func cmalloc(n uintptr) unsafe.Pointer {
  144. var args struct {
  145. n uint64
  146. ret unsafe.Pointer
  147. }
  148. args.n = uint64(n)
  149. cgocall(cgoMalloc, unsafe.Pointer(&args))
  150. if args.ret == nil {
  151. gothrow("C malloc failed")
  152. }
  153. return args.ret
  154. }
  155. func cfree(p unsafe.Pointer) {
  156. cgocall(cgoFree, p)
  157. }
  158. // Call from C back to Go.
  159. //go:nosplit
  160. func cgocallbackg() {
  161. gp := getg()
  162. if gp != gp.m.curg {
  163. println("runtime: bad g in cgocallback")
  164. exit(2)
  165. }
  166. // entersyscall saves the caller's SP to allow the GC to trace the Go
  167. // stack. However, since we're returning to an earlier stack frame and
  168. // need to pair with the entersyscall() call made by cgocall, we must
  169. // save syscall* and let reentersyscall restore them.
  170. savedsp := unsafe.Pointer(gp.syscallsp)
  171. savedpc := gp.syscallpc
  172. exitsyscall() // coming out of cgo call
  173. cgocallbackg1()
  174. // going back to cgo call
  175. reentersyscall(savedpc, savedsp)
  176. }
  177. func cgocallbackg1() {
  178. gp := getg()
  179. if gp.m.needextram {
  180. gp.m.needextram = false
  181. onM(newextram)
  182. }
  183. // Add entry to defer stack in case of panic.
  184. restore := true
  185. defer unwindm(&restore)
  186. if raceenabled {
  187. raceacquire(unsafe.Pointer(&racecgosync))
  188. }
  189. type args struct {
  190. fn *funcval
  191. arg unsafe.Pointer
  192. argsize uintptr
  193. }
  194. var cb *args
  195. // Location of callback arguments depends on stack frame layout
  196. // and size of stack frame of cgocallback_gofunc.
  197. sp := gp.m.g0.sched.sp
  198. switch GOARCH {
  199. default:
  200. gothrow("cgocallbackg is unimplemented on arch")
  201. case "arm":
  202. // On arm, stack frame is two words and there's a saved LR between
  203. // SP and the stack frame and between the stack frame and the arguments.
  204. cb = (*args)(unsafe.Pointer(sp + 4*ptrSize))
  205. case "amd64":
  206. // On amd64, stack frame is one word, plus caller PC.
  207. cb = (*args)(unsafe.Pointer(sp + 2*ptrSize))
  208. case "386":
  209. // On 386, stack frame is three words, plus caller PC.
  210. cb = (*args)(unsafe.Pointer(sp + 4*ptrSize))
  211. }
  212. // Invoke callback.
  213. reflectcall(unsafe.Pointer(cb.fn), unsafe.Pointer(cb.arg), uint32(cb.argsize), 0)
  214. if raceenabled {
  215. racereleasemerge(unsafe.Pointer(&racecgosync))
  216. }
  217. // Do not unwind m->g0->sched.sp.
  218. // Our caller, cgocallback, will do that.
  219. restore = false
  220. }
  221. func unwindm(restore *bool) {
  222. if !*restore {
  223. return
  224. }
  225. // Restore sp saved by cgocallback during
  226. // unwind of g's stack (see comment at top of file).
  227. mp := acquirem()
  228. sched := &mp.g0.sched
  229. switch GOARCH {
  230. default:
  231. gothrow("unwindm not implemented")
  232. case "386", "amd64":
  233. sched.sp = *(*uintptr)(unsafe.Pointer(sched.sp))
  234. case "arm":
  235. sched.sp = *(*uintptr)(unsafe.Pointer(sched.sp + 4))
  236. }
  237. releasem(mp)
  238. }
  239. // called from assembly
  240. func badcgocallback() {
  241. gothrow("misaligned stack in cgocallback")
  242. }
  243. // called from (incomplete) assembly
  244. func cgounimpl() {
  245. gothrow("cgo not implemented")
  246. }
  247. var racecgosync uint64 // represents possible synchronization in C code