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