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