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