github.com/miolini/go@v0.0.0-20160405192216-fca68c8cb408/src/runtime/cgocall.go (about) 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) locks g to m, calls entersyscall 12 // so as not to block other goroutines or the garbage collector, 13 // and then calls 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 calls crosscall2(_cgoexp_GoF, frame, framesize). Crosscall2 39 // (in cgo/gcc_$GOARCH.S, a gcc-compiled assembly file) is a two-argument 40 // adapter from the gcc function call ABI to the 6c function call ABI. 41 // It is called from gcc to call 6c functions. In this case it calls 42 // _cgoexp_GoF(frame, framesize), still running on m->g0's stack 43 // and outside the $GOMAXPROCS limit. Thus, this code cannot yet 44 // call arbitrary Go code directly and must be careful not to allocate 45 // memory or use up m->g0's stack. 46 // 47 // _cgoexp_GoF calls runtime.cgocallback(p.GoF, frame, framesize). 48 // (The reason for having _cgoexp_GoF instead of writing a crosscall3 49 // to make this call directly is that _cgoexp_GoF, because it is compiled 50 // with 6c instead of gcc, can refer to dotted names like 51 // runtime.cgocallback and p.GoF.) 52 // 53 // runtime.cgocallback (in asm_$GOARCH.s) switches from m->g0's 54 // stack to the original g (m->curg)'s stack, on which it calls 55 // runtime.cgocallbackg(p.GoF, frame, framesize). 56 // As part of the stack switch, runtime.cgocallback saves the current 57 // SP as m->g0->sched.sp, so that any use of m->g0's stack during the 58 // execution of the callback will be done below the existing stack frames. 59 // Before overwriting m->g0->sched.sp, it pushes the old value on the 60 // m->g0 stack, so that it can be restored later. 61 // 62 // runtime.cgocallbackg (below) is now running on a real goroutine 63 // stack (not an m->g0 stack). First it calls runtime.exitsyscall, which will 64 // block until the $GOMAXPROCS limit allows running this goroutine. 65 // Once exitsyscall has returned, it is safe to do things like call the memory 66 // allocator or invoke the Go callback function p.GoF. runtime.cgocallbackg 67 // first defers a function to unwind m->g0.sched.sp, so that if p.GoF 68 // panics, m->g0.sched.sp will be restored to its old value: the m->g0 stack 69 // and the m->curg stack will be unwound in lock step. 70 // Then it calls p.GoF. Finally it pops but does not execute the deferred 71 // function, calls runtime.entersyscall, and returns to runtime.cgocallback. 72 // 73 // After it regains control, runtime.cgocallback switches back to 74 // m->g0's stack (the pointer is still in m->g0.sched.sp), restores the old 75 // m->g0.sched.sp value from the stack, and returns to _cgoexp_GoF. 76 // 77 // _cgoexp_GoF immediately returns to crosscall2, which restores the 78 // callee-save registers for gcc and returns to GoF, which returns to f. 79 80 package runtime 81 82 import ( 83 "runtime/internal/sys" 84 "unsafe" 85 ) 86 87 // Addresses collected in a cgo backtrace when crashing. 88 // Length must match arg.Max in x_cgo_callers in runtime/cgo/gcc_traceback.c. 89 type cgoCallers [32]uintptr 90 91 // Call from Go to C. 92 //go:nosplit 93 func cgocall(fn, arg unsafe.Pointer) int32 { 94 if !iscgo && GOOS != "solaris" && GOOS != "windows" { 95 throw("cgocall unavailable") 96 } 97 98 if fn == nil { 99 throw("cgocall nil") 100 } 101 102 if raceenabled { 103 racereleasemerge(unsafe.Pointer(&racecgosync)) 104 } 105 106 /* 107 * Lock g to m to ensure we stay on the same stack if we do a 108 * cgo callback. Add entry to defer stack in case of panic. 109 */ 110 lockOSThread() 111 mp := getg().m 112 mp.ncgocall++ 113 mp.ncgo++ 114 defer endcgo(mp) 115 116 // Reset traceback. 117 mp.cgoCallers[0] = 0 118 119 /* 120 * Announce we are entering a system call 121 * so that the scheduler knows to create another 122 * M to run goroutines while we are in the 123 * foreign code. 124 * 125 * The call to asmcgocall is guaranteed not to 126 * split the stack and does not allocate memory, 127 * so it is safe to call while "in a system call", outside 128 * the $GOMAXPROCS accounting. 129 */ 130 entersyscall(0) 131 errno := asmcgocall(fn, arg) 132 exitsyscall(0) 133 134 return errno 135 } 136 137 //go:nosplit 138 func endcgo(mp *m) { 139 mp.ncgo-- 140 141 if raceenabled { 142 raceacquire(unsafe.Pointer(&racecgosync)) 143 } 144 145 unlockOSThread() // invalidates mp 146 } 147 148 // Helper functions for cgo code. 149 150 func cmalloc(n uintptr) unsafe.Pointer { 151 var args struct { 152 n uint64 153 ret unsafe.Pointer 154 } 155 args.n = uint64(n) 156 cgocall(_cgo_malloc, unsafe.Pointer(&args)) 157 if args.ret == nil { 158 throw("C malloc failed") 159 } 160 return args.ret 161 } 162 163 func cfree(p unsafe.Pointer) { 164 cgocall(_cgo_free, p) 165 } 166 167 // Call from C back to Go. 168 //go:nosplit 169 func cgocallbackg() { 170 gp := getg() 171 if gp != gp.m.curg { 172 println("runtime: bad g in cgocallback") 173 exit(2) 174 } 175 176 // Save current syscall parameters, so m.syscall can be 177 // used again if callback decide to make syscall. 178 syscall := gp.m.syscall 179 180 // entersyscall saves the caller's SP to allow the GC to trace the Go 181 // stack. However, since we're returning to an earlier stack frame and 182 // need to pair with the entersyscall() call made by cgocall, we must 183 // save syscall* and let reentersyscall restore them. 184 savedsp := unsafe.Pointer(gp.syscallsp) 185 savedpc := gp.syscallpc 186 exitsyscall(0) // coming out of cgo call 187 cgocallbackg1() 188 // going back to cgo call 189 reentersyscall(savedpc, uintptr(savedsp)) 190 191 gp.m.syscall = syscall 192 } 193 194 func cgocallbackg1() { 195 gp := getg() 196 if gp.m.needextram { 197 gp.m.needextram = false 198 systemstack(newextram) 199 } 200 201 if gp.m.ncgo == 0 { 202 // The C call to Go came from a thread not currently running 203 // any Go. In the case of -buildmode=c-archive or c-shared, 204 // this call may be coming in before package initialization 205 // is complete. Wait until it is. 206 <-main_init_done 207 } 208 209 // Add entry to defer stack in case of panic. 210 restore := true 211 defer unwindm(&restore) 212 213 if raceenabled { 214 raceacquire(unsafe.Pointer(&racecgosync)) 215 } 216 217 type args struct { 218 fn *funcval 219 arg unsafe.Pointer 220 argsize uintptr 221 } 222 var cb *args 223 224 // Location of callback arguments depends on stack frame layout 225 // and size of stack frame of cgocallback_gofunc. 226 sp := gp.m.g0.sched.sp 227 switch GOARCH { 228 default: 229 throw("cgocallbackg is unimplemented on arch") 230 case "arm": 231 // On arm, stack frame is two words and there's a saved LR between 232 // SP and the stack frame and between the stack frame and the arguments. 233 cb = (*args)(unsafe.Pointer(sp + 4*sys.PtrSize)) 234 case "arm64": 235 // On arm64, stack frame is four words and there's a saved LR between 236 // SP and the stack frame and between the stack frame and the arguments. 237 cb = (*args)(unsafe.Pointer(sp + 5*sys.PtrSize)) 238 case "amd64": 239 // On amd64, stack frame is one word, plus caller PC. 240 if framepointer_enabled { 241 // In this case, there's also saved BP. 242 cb = (*args)(unsafe.Pointer(sp + 3*sys.PtrSize)) 243 break 244 } 245 cb = (*args)(unsafe.Pointer(sp + 2*sys.PtrSize)) 246 case "386": 247 // On 386, stack frame is three words, plus caller PC. 248 cb = (*args)(unsafe.Pointer(sp + 4*sys.PtrSize)) 249 case "ppc64", "ppc64le": 250 // On ppc64, the callback arguments are in the arguments area of 251 // cgocallback's stack frame. The stack looks like this: 252 // +--------------------+------------------------------+ 253 // | | ... | 254 // | cgoexp_$fn +------------------------------+ 255 // | | fixed frame area | 256 // +--------------------+------------------------------+ 257 // | | arguments area | 258 // | cgocallback +------------------------------+ <- sp + 2*minFrameSize + 2*ptrSize 259 // | | fixed frame area | 260 // +--------------------+------------------------------+ <- sp + minFrameSize + 2*ptrSize 261 // | | local variables (2 pointers) | 262 // | cgocallback_gofunc +------------------------------+ <- sp + minFrameSize 263 // | | fixed frame area | 264 // +--------------------+------------------------------+ <- sp 265 cb = (*args)(unsafe.Pointer(sp + 2*sys.MinFrameSize + 2*sys.PtrSize)) 266 } 267 268 // Invoke callback. 269 // NOTE(rsc): passing nil for argtype means that the copying of the 270 // results back into cb.arg happens without any corresponding write barriers. 271 // For cgo, cb.arg points into a C stack frame and therefore doesn't 272 // hold any pointers that the GC can find anyway - the write barrier 273 // would be a no-op. 274 reflectcall(nil, unsafe.Pointer(cb.fn), cb.arg, uint32(cb.argsize), 0) 275 276 if raceenabled { 277 racereleasemerge(unsafe.Pointer(&racecgosync)) 278 } 279 if msanenabled { 280 // Tell msan that we wrote to the entire argument block. 281 // This tells msan that we set the results. 282 // Since we have already called the function it doesn't 283 // matter that we are writing to the non-result parameters. 284 msanwrite(cb.arg, cb.argsize) 285 } 286 287 // Do not unwind m->g0->sched.sp. 288 // Our caller, cgocallback, will do that. 289 restore = false 290 } 291 292 func unwindm(restore *bool) { 293 if !*restore { 294 return 295 } 296 // Restore sp saved by cgocallback during 297 // unwind of g's stack (see comment at top of file). 298 mp := acquirem() 299 sched := &mp.g0.sched 300 switch GOARCH { 301 default: 302 throw("unwindm not implemented") 303 case "386", "amd64", "arm", "ppc64", "ppc64le": 304 sched.sp = *(*uintptr)(unsafe.Pointer(sched.sp + sys.MinFrameSize)) 305 case "arm64": 306 sched.sp = *(*uintptr)(unsafe.Pointer(sched.sp + 16)) 307 } 308 releasem(mp) 309 } 310 311 // called from assembly 312 func badcgocallback() { 313 throw("misaligned stack in cgocallback") 314 } 315 316 // called from (incomplete) assembly 317 func cgounimpl() { 318 throw("cgo not implemented") 319 } 320 321 var racecgosync uint64 // represents possible synchronization in C code 322 323 // Pointer checking for cgo code. 324 325 // We want to detect all cases where a program that does not use 326 // unsafe makes a cgo call passing a Go pointer to memory that 327 // contains a Go pointer. Here a Go pointer is defined as a pointer 328 // to memory allocated by the Go runtime. Programs that use unsafe 329 // can evade this restriction easily, so we don't try to catch them. 330 // The cgo program will rewrite all possibly bad pointer arguments to 331 // call cgoCheckPointer, where we can catch cases of a Go pointer 332 // pointing to a Go pointer. 333 334 // Complicating matters, taking the address of a slice or array 335 // element permits the C program to access all elements of the slice 336 // or array. In that case we will see a pointer to a single element, 337 // but we need to check the entire data structure. 338 339 // The cgoCheckPointer call takes additional arguments indicating that 340 // it was called on an address expression. An additional argument of 341 // true means that it only needs to check a single element. An 342 // additional argument of a slice or array means that it needs to 343 // check the entire slice/array, but nothing else. Otherwise, the 344 // pointer could be anything, and we check the entire heap object, 345 // which is conservative but safe. 346 347 // When and if we implement a moving garbage collector, 348 // cgoCheckPointer will pin the pointer for the duration of the cgo 349 // call. (This is necessary but not sufficient; the cgo program will 350 // also have to change to pin Go pointers that cannot point to Go 351 // pointers.) 352 353 // cgoCheckPointer checks if the argument contains a Go pointer that 354 // points to a Go pointer, and panics if it does. It returns the pointer. 355 func cgoCheckPointer(ptr interface{}, args ...interface{}) interface{} { 356 if debug.cgocheck == 0 { 357 return ptr 358 } 359 360 ep := (*eface)(unsafe.Pointer(&ptr)) 361 t := ep._type 362 363 top := true 364 if len(args) > 0 && (t.kind&kindMask == kindPtr || t.kind&kindMask == kindUnsafePointer) { 365 p := ep.data 366 if t.kind&kindDirectIface == 0 { 367 p = *(*unsafe.Pointer)(p) 368 } 369 if !cgoIsGoPointer(p) { 370 return ptr 371 } 372 aep := (*eface)(unsafe.Pointer(&args[0])) 373 switch aep._type.kind & kindMask { 374 case kindBool: 375 if t.kind&kindMask == kindUnsafePointer { 376 // We don't know the type of the element. 377 break 378 } 379 pt := (*ptrtype)(unsafe.Pointer(t)) 380 cgoCheckArg(pt.elem, p, true, false, cgoCheckPointerFail) 381 return ptr 382 case kindSlice: 383 // Check the slice rather than the pointer. 384 ep = aep 385 t = ep._type 386 case kindArray: 387 // Check the array rather than the pointer. 388 // Pass top as false since we have a pointer 389 // to the array. 390 ep = aep 391 t = ep._type 392 top = false 393 default: 394 throw("can't happen") 395 } 396 } 397 398 cgoCheckArg(t, ep.data, t.kind&kindDirectIface == 0, top, cgoCheckPointerFail) 399 return ptr 400 } 401 402 const cgoCheckPointerFail = "cgo argument has Go pointer to Go pointer" 403 const cgoResultFail = "cgo result has Go pointer" 404 405 // cgoCheckArg is the real work of cgoCheckPointer. The argument p 406 // is either a pointer to the value (of type t), or the value itself, 407 // depending on indir. The top parameter is whether we are at the top 408 // level, where Go pointers are allowed. 409 func cgoCheckArg(t *_type, p unsafe.Pointer, indir, top bool, msg string) { 410 if t.kind&kindNoPointers != 0 { 411 // If the type has no pointers there is nothing to do. 412 return 413 } 414 415 switch t.kind & kindMask { 416 default: 417 throw("can't happen") 418 case kindArray: 419 at := (*arraytype)(unsafe.Pointer(t)) 420 if !indir { 421 if at.len != 1 { 422 throw("can't happen") 423 } 424 cgoCheckArg(at.elem, p, at.elem.kind&kindDirectIface == 0, top, msg) 425 return 426 } 427 for i := uintptr(0); i < at.len; i++ { 428 cgoCheckArg(at.elem, p, true, top, msg) 429 p = add(p, at.elem.size) 430 } 431 case kindChan, kindMap: 432 // These types contain internal pointers that will 433 // always be allocated in the Go heap. It's never OK 434 // to pass them to C. 435 panic(errorString(msg)) 436 case kindFunc: 437 if indir { 438 p = *(*unsafe.Pointer)(p) 439 } 440 if !cgoIsGoPointer(p) { 441 return 442 } 443 panic(errorString(msg)) 444 case kindInterface: 445 it := *(**_type)(p) 446 if it == nil { 447 return 448 } 449 // A type known at compile time is OK since it's 450 // constant. A type not known at compile time will be 451 // in the heap and will not be OK. 452 if inheap(uintptr(unsafe.Pointer(it))) { 453 panic(errorString(msg)) 454 } 455 p = *(*unsafe.Pointer)(add(p, sys.PtrSize)) 456 if !cgoIsGoPointer(p) { 457 return 458 } 459 if !top { 460 panic(errorString(msg)) 461 } 462 cgoCheckArg(it, p, it.kind&kindDirectIface == 0, false, msg) 463 case kindSlice: 464 st := (*slicetype)(unsafe.Pointer(t)) 465 s := (*slice)(p) 466 p = s.array 467 if !cgoIsGoPointer(p) { 468 return 469 } 470 if !top { 471 panic(errorString(msg)) 472 } 473 if st.elem.kind&kindNoPointers != 0 { 474 return 475 } 476 for i := 0; i < s.cap; i++ { 477 cgoCheckArg(st.elem, p, true, false, msg) 478 p = add(p, st.elem.size) 479 } 480 case kindString: 481 ss := (*stringStruct)(p) 482 if !cgoIsGoPointer(ss.str) { 483 return 484 } 485 if !top { 486 panic(errorString(msg)) 487 } 488 case kindStruct: 489 st := (*structtype)(unsafe.Pointer(t)) 490 if !indir { 491 if len(st.fields) != 1 { 492 throw("can't happen") 493 } 494 cgoCheckArg(st.fields[0].typ, p, st.fields[0].typ.kind&kindDirectIface == 0, top, msg) 495 return 496 } 497 for _, f := range st.fields { 498 cgoCheckArg(f.typ, add(p, f.offset), true, top, msg) 499 } 500 case kindPtr, kindUnsafePointer: 501 if indir { 502 p = *(*unsafe.Pointer)(p) 503 } 504 505 if !cgoIsGoPointer(p) { 506 return 507 } 508 if !top { 509 panic(errorString(msg)) 510 } 511 512 cgoCheckUnknownPointer(p, msg) 513 } 514 } 515 516 // cgoCheckUnknownPointer is called for an arbitrary pointer into Go 517 // memory. It checks whether that Go memory contains any other 518 // pointer into Go memory. If it does, we panic. 519 // The return values are unused but useful to see in panic tracebacks. 520 func cgoCheckUnknownPointer(p unsafe.Pointer, msg string) (base, i uintptr) { 521 if cgoInRange(p, mheap_.arena_start, mheap_.arena_used) { 522 if !inheap(uintptr(p)) { 523 // On 32-bit systems it is possible for C's allocated memory 524 // to have addresses between arena_start and arena_used. 525 // Either this pointer is a stack or an unused span or it's 526 // a C allocation. Escape analysis should prevent the first, 527 // garbage collection should prevent the second, 528 // and the third is completely OK. 529 return 530 } 531 532 b, hbits, span := heapBitsForObject(uintptr(p), 0, 0) 533 base = b 534 if base == 0 { 535 return 536 } 537 n := span.elemsize 538 for i = uintptr(0); i < n; i += sys.PtrSize { 539 bits := hbits.bits() 540 if i >= 2*sys.PtrSize && bits&bitMarked == 0 { 541 // No more possible pointers. 542 break 543 } 544 if bits&bitPointer != 0 { 545 if cgoIsGoPointer(*(*unsafe.Pointer)(unsafe.Pointer(base + i))) { 546 panic(errorString(msg)) 547 } 548 } 549 hbits = hbits.next() 550 } 551 552 return 553 } 554 555 for datap := &firstmoduledata; datap != nil; datap = datap.next { 556 if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) { 557 // We have no way to know the size of the object. 558 // We have to assume that it might contain a pointer. 559 panic(errorString(msg)) 560 } 561 // In the text or noptr sections, we know that the 562 // pointer does not point to a Go pointer. 563 } 564 565 return 566 } 567 568 // cgoIsGoPointer returns whether the pointer is a Go pointer--a 569 // pointer to Go memory. We only care about Go memory that might 570 // contain pointers. 571 //go:nosplit 572 //go:nowritebarrierrec 573 func cgoIsGoPointer(p unsafe.Pointer) bool { 574 if p == nil { 575 return false 576 } 577 578 if cgoInRange(p, mheap_.arena_start, mheap_.arena_used) { 579 return true 580 } 581 582 for datap := &firstmoduledata; datap != nil; datap = datap.next { 583 if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) { 584 return true 585 } 586 } 587 588 return false 589 } 590 591 // cgoInRange returns whether p is between start and end. 592 //go:nosplit 593 //go:nowritebarrierrec 594 func cgoInRange(p unsafe.Pointer, start, end uintptr) bool { 595 return start <= uintptr(p) && uintptr(p) < end 596 } 597 598 // cgoCheckResult is called to check the result parameter of an 599 // exported Go function. It panics if the result is or contains a Go 600 // pointer. 601 func cgoCheckResult(val interface{}) { 602 if debug.cgocheck == 0 { 603 return 604 } 605 606 ep := (*eface)(unsafe.Pointer(&val)) 607 t := ep._type 608 cgoCheckArg(t, ep.data, t.kind&kindDirectIface == 0, false, cgoResultFail) 609 }