github.com/aloncn/graphics-go@v0.0.1/src/runtime/os1_darwin.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 package runtime 6 7 import "unsafe" 8 9 //extern SigTabTT runtimeĀ·sigtab[]; 10 11 type sigset uint32 12 13 var sigset_all = ^sigset(0) 14 15 func unimplemented(name string) { 16 println(name, "not implemented") 17 *(*int)(unsafe.Pointer(uintptr(1231))) = 1231 18 } 19 20 //go:nosplit 21 func semawakeup(mp *m) { 22 mach_semrelease(mp.waitsema) 23 } 24 25 //go:nosplit 26 func semacreate(mp *m) { 27 if mp.waitsema != 0 { 28 return 29 } 30 systemstack(func() { 31 mp.waitsema = mach_semcreate() 32 }) 33 } 34 35 // BSD interface for threading. 36 func osinit() { 37 // bsdthread_register delayed until end of goenvs so that we 38 // can look at the environment first. 39 40 ncpu = getncpu() 41 } 42 43 func getncpu() int32 { 44 // Use sysctl to fetch hw.ncpu. 45 mib := [2]uint32{6, 3} 46 out := uint32(0) 47 nout := unsafe.Sizeof(out) 48 ret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0) 49 if ret >= 0 && int32(out) > 0 { 50 return int32(out) 51 } 52 return 1 53 } 54 55 var urandom_dev = []byte("/dev/urandom\x00") 56 57 //go:nosplit 58 func getRandomData(r []byte) { 59 fd := open(&urandom_dev[0], 0 /* O_RDONLY */, 0) 60 n := read(fd, unsafe.Pointer(&r[0]), int32(len(r))) 61 closefd(fd) 62 extendRandom(r, int(n)) 63 } 64 65 func goenvs() { 66 goenvs_unix() 67 68 // Register our thread-creation callback (see sys_darwin_{amd64,386}.s) 69 // but only if we're not using cgo. If we are using cgo we need 70 // to let the C pthread library install its own thread-creation callback. 71 if !iscgo { 72 if bsdthread_register() != 0 { 73 if gogetenv("DYLD_INSERT_LIBRARIES") != "" { 74 throw("runtime: bsdthread_register error (unset DYLD_INSERT_LIBRARIES)") 75 } 76 throw("runtime: bsdthread_register error") 77 } 78 } 79 } 80 81 // May run with m.p==nil, so write barriers are not allowed. 82 //go:nowritebarrier 83 func newosproc(mp *m, stk unsafe.Pointer) { 84 if false { 85 print("newosproc stk=", stk, " m=", mp, " g=", mp.g0, " id=", mp.id, " ostk=", &mp, "\n") 86 } 87 88 var oset sigset 89 sigprocmask(_SIG_SETMASK, &sigset_all, &oset) 90 errno := bsdthread_create(stk, unsafe.Pointer(mp), funcPC(mstart)) 91 sigprocmask(_SIG_SETMASK, &oset, nil) 92 93 if errno < 0 { 94 print("runtime: failed to create new OS thread (have ", mcount(), " already; errno=", -errno, ")\n") 95 throw("runtime.newosproc") 96 } 97 } 98 99 // newosproc0 is a version of newosproc that can be called before the runtime 100 // is initialized. 101 // 102 // As Go uses bsdthread_register when running without cgo, this function is 103 // not safe to use after initialization as it does not pass an M as fnarg. 104 // 105 //go:nosplit 106 func newosproc0(stacksize uintptr, fn unsafe.Pointer, fnarg uintptr) { 107 stack := sysAlloc(stacksize, &memstats.stacks_sys) 108 if stack == nil { 109 write(2, unsafe.Pointer(&failallocatestack[0]), int32(len(failallocatestack))) 110 exit(1) 111 } 112 stk := unsafe.Pointer(uintptr(stack) + stacksize) 113 114 var oset sigset 115 sigprocmask(_SIG_SETMASK, &sigset_all, &oset) 116 errno := bsdthread_create(stk, fn, fnarg) 117 sigprocmask(_SIG_SETMASK, &oset, nil) 118 119 if errno < 0 { 120 write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate))) 121 exit(1) 122 } 123 } 124 125 var failallocatestack = []byte("runtime: failed to allocate stack for the new OS thread\n") 126 var failthreadcreate = []byte("runtime: failed to create new OS thread\n") 127 128 // Called to do synchronous initialization of Go code built with 129 // -buildmode=c-archive or -buildmode=c-shared. 130 // None of the Go runtime is initialized. 131 //go:nosplit 132 //go:nowritebarrierrec 133 func libpreinit() { 134 initsig(true) 135 } 136 137 // Called to initialize a new m (including the bootstrap m). 138 // Called on the parent thread (main thread in case of bootstrap), can allocate memory. 139 func mpreinit(mp *m) { 140 mp.gsignal = malg(32 * 1024) // OS X wants >= 8K 141 mp.gsignal.m = mp 142 } 143 144 //go:nosplit 145 func msigsave(mp *m) { 146 sigprocmask(_SIG_SETMASK, nil, &mp.sigmask) 147 } 148 149 //go:nosplit 150 func msigrestore(sigmask sigset) { 151 sigprocmask(_SIG_SETMASK, &sigmask, nil) 152 } 153 154 //go:nosplit 155 func sigblock() { 156 sigprocmask(_SIG_SETMASK, &sigset_all, nil) 157 } 158 159 // Called to initialize a new m (including the bootstrap m). 160 // Called on the new thread, can not allocate memory. 161 func minit() { 162 // Initialize signal handling. 163 _g_ := getg() 164 165 // The alternate signal stack is buggy on arm and arm64. 166 // The signal handler handles it directly. 167 // The sigaltstack assembly function does nothing. 168 if GOARCH != "arm" && GOARCH != "arm64" { 169 var st stackt 170 sigaltstack(nil, &st) 171 if st.ss_flags&_SS_DISABLE != 0 { 172 signalstack(&_g_.m.gsignal.stack) 173 _g_.m.newSigstack = true 174 } else { 175 // Use existing signal stack. 176 stsp := uintptr(unsafe.Pointer(st.ss_sp)) 177 _g_.m.gsignal.stack.lo = stsp 178 _g_.m.gsignal.stack.hi = stsp + st.ss_size 179 _g_.m.gsignal.stackguard0 = stsp + _StackGuard 180 _g_.m.gsignal.stackguard1 = stsp + _StackGuard 181 _g_.m.gsignal.stackAlloc = st.ss_size 182 _g_.m.newSigstack = false 183 } 184 } 185 186 // restore signal mask from m.sigmask and unblock essential signals 187 nmask := _g_.m.sigmask 188 for i := range sigtable { 189 if sigtable[i].flags&_SigUnblock != 0 { 190 nmask &^= 1 << (uint32(i) - 1) 191 } 192 } 193 sigprocmask(_SIG_SETMASK, &nmask, nil) 194 } 195 196 // Called from dropm to undo the effect of an minit. 197 //go:nosplit 198 func unminit() { 199 if getg().m.newSigstack { 200 signalstack(nil) 201 } 202 } 203 204 // Mach IPC, to get at semaphores 205 // Definitions are in /usr/include/mach on a Mac. 206 207 func macherror(r int32, fn string) { 208 print("mach error ", fn, ": ", r, "\n") 209 throw("mach error") 210 } 211 212 const _DebugMach = false 213 214 var zerondr machndr 215 216 func mach_msgh_bits(a, b uint32) uint32 { 217 return a | b<<8 218 } 219 220 func mach_msg(h *machheader, op int32, send_size, rcv_size, rcv_name, timeout, notify uint32) int32 { 221 // TODO: Loop on interrupt. 222 return mach_msg_trap(unsafe.Pointer(h), op, send_size, rcv_size, rcv_name, timeout, notify) 223 } 224 225 // Mach RPC (MIG) 226 const ( 227 _MinMachMsg = 48 228 _MachReply = 100 229 ) 230 231 type codemsg struct { 232 h machheader 233 ndr machndr 234 code int32 235 } 236 237 func machcall(h *machheader, maxsize int32, rxsize int32) int32 { 238 _g_ := getg() 239 port := _g_.m.machport 240 if port == 0 { 241 port = mach_reply_port() 242 _g_.m.machport = port 243 } 244 245 h.msgh_bits |= mach_msgh_bits(_MACH_MSG_TYPE_COPY_SEND, _MACH_MSG_TYPE_MAKE_SEND_ONCE) 246 h.msgh_local_port = port 247 h.msgh_reserved = 0 248 id := h.msgh_id 249 250 if _DebugMach { 251 p := (*[10000]unsafe.Pointer)(unsafe.Pointer(h)) 252 print("send:\t") 253 var i uint32 254 for i = 0; i < h.msgh_size/uint32(unsafe.Sizeof(p[0])); i++ { 255 print(" ", p[i]) 256 if i%8 == 7 { 257 print("\n\t") 258 } 259 } 260 if i%8 != 0 { 261 print("\n") 262 } 263 } 264 ret := mach_msg(h, _MACH_SEND_MSG|_MACH_RCV_MSG, h.msgh_size, uint32(maxsize), port, 0, 0) 265 if ret != 0 { 266 if _DebugMach { 267 print("mach_msg error ", ret, "\n") 268 } 269 return ret 270 } 271 if _DebugMach { 272 p := (*[10000]unsafe.Pointer)(unsafe.Pointer(h)) 273 var i uint32 274 for i = 0; i < h.msgh_size/uint32(unsafe.Sizeof(p[0])); i++ { 275 print(" ", p[i]) 276 if i%8 == 7 { 277 print("\n\t") 278 } 279 } 280 if i%8 != 0 { 281 print("\n") 282 } 283 } 284 if h.msgh_id != id+_MachReply { 285 if _DebugMach { 286 print("mach_msg _MachReply id mismatch ", h.msgh_id, " != ", id+_MachReply, "\n") 287 } 288 return -303 // MIG_REPLY_MISMATCH 289 } 290 // Look for a response giving the return value. 291 // Any call can send this back with an error, 292 // and some calls only have return values so they 293 // send it back on success too. I don't quite see how 294 // you know it's one of these and not the full response 295 // format, so just look if the message is right. 296 c := (*codemsg)(unsafe.Pointer(h)) 297 if uintptr(h.msgh_size) == unsafe.Sizeof(*c) && h.msgh_bits&_MACH_MSGH_BITS_COMPLEX == 0 { 298 if _DebugMach { 299 print("mig result ", c.code, "\n") 300 } 301 return c.code 302 } 303 if h.msgh_size != uint32(rxsize) { 304 if _DebugMach { 305 print("mach_msg _MachReply size mismatch ", h.msgh_size, " != ", rxsize, "\n") 306 } 307 return -307 // MIG_ARRAY_TOO_LARGE 308 } 309 return 0 310 } 311 312 // Semaphores! 313 314 const ( 315 tmach_semcreate = 3418 316 rmach_semcreate = tmach_semcreate + _MachReply 317 318 tmach_semdestroy = 3419 319 rmach_semdestroy = tmach_semdestroy + _MachReply 320 321 _KERN_ABORTED = 14 322 _KERN_OPERATION_TIMED_OUT = 49 323 ) 324 325 type tmach_semcreatemsg struct { 326 h machheader 327 ndr machndr 328 policy int32 329 value int32 330 } 331 332 type rmach_semcreatemsg struct { 333 h machheader 334 body machbody 335 semaphore machport 336 } 337 338 type tmach_semdestroymsg struct { 339 h machheader 340 body machbody 341 semaphore machport 342 } 343 344 func mach_semcreate() uint32 { 345 var m [256]uint8 346 tx := (*tmach_semcreatemsg)(unsafe.Pointer(&m)) 347 rx := (*rmach_semcreatemsg)(unsafe.Pointer(&m)) 348 349 tx.h.msgh_bits = 0 350 tx.h.msgh_size = uint32(unsafe.Sizeof(*tx)) 351 tx.h.msgh_remote_port = mach_task_self() 352 tx.h.msgh_id = tmach_semcreate 353 tx.ndr = zerondr 354 355 tx.policy = 0 // 0 = SYNC_POLICY_FIFO 356 tx.value = 0 357 358 for { 359 r := machcall(&tx.h, int32(unsafe.Sizeof(m)), int32(unsafe.Sizeof(*rx))) 360 if r == 0 { 361 break 362 } 363 if r == _KERN_ABORTED { // interrupted 364 continue 365 } 366 macherror(r, "semaphore_create") 367 } 368 if rx.body.msgh_descriptor_count != 1 { 369 unimplemented("mach_semcreate desc count") 370 } 371 return rx.semaphore.name 372 } 373 374 func mach_semdestroy(sem uint32) { 375 var m [256]uint8 376 tx := (*tmach_semdestroymsg)(unsafe.Pointer(&m)) 377 378 tx.h.msgh_bits = _MACH_MSGH_BITS_COMPLEX 379 tx.h.msgh_size = uint32(unsafe.Sizeof(*tx)) 380 tx.h.msgh_remote_port = mach_task_self() 381 tx.h.msgh_id = tmach_semdestroy 382 tx.body.msgh_descriptor_count = 1 383 tx.semaphore.name = sem 384 tx.semaphore.disposition = _MACH_MSG_TYPE_MOVE_SEND 385 tx.semaphore._type = 0 386 387 for { 388 r := machcall(&tx.h, int32(unsafe.Sizeof(m)), 0) 389 if r == 0 { 390 break 391 } 392 if r == _KERN_ABORTED { // interrupted 393 continue 394 } 395 macherror(r, "semaphore_destroy") 396 } 397 } 398 399 // The other calls have simple system call traps in sys_darwin_{amd64,386}.s 400 401 func mach_semaphore_wait(sema uint32) int32 402 func mach_semaphore_timedwait(sema, sec, nsec uint32) int32 403 func mach_semaphore_signal(sema uint32) int32 404 func mach_semaphore_signal_all(sema uint32) int32 405 406 func semasleep1(ns int64) int32 { 407 _g_ := getg() 408 409 if ns >= 0 { 410 var nsecs int32 411 secs := timediv(ns, 1000000000, &nsecs) 412 r := mach_semaphore_timedwait(_g_.m.waitsema, uint32(secs), uint32(nsecs)) 413 if r == _KERN_ABORTED || r == _KERN_OPERATION_TIMED_OUT { 414 return -1 415 } 416 if r != 0 { 417 macherror(r, "semaphore_wait") 418 } 419 return 0 420 } 421 422 for { 423 r := mach_semaphore_wait(_g_.m.waitsema) 424 if r == 0 { 425 break 426 } 427 if r == _KERN_ABORTED { // interrupted 428 continue 429 } 430 macherror(r, "semaphore_wait") 431 } 432 return 0 433 } 434 435 //go:nosplit 436 func semasleep(ns int64) int32 { 437 var r int32 438 systemstack(func() { 439 r = semasleep1(ns) 440 }) 441 return r 442 } 443 444 //go:nosplit 445 func mach_semrelease(sem uint32) { 446 for { 447 r := mach_semaphore_signal(sem) 448 if r == 0 { 449 break 450 } 451 if r == _KERN_ABORTED { // interrupted 452 continue 453 } 454 455 // mach_semrelease must be completely nosplit, 456 // because it is called from Go code. 457 // If we're going to die, start that process on the system stack 458 // to avoid a Go stack split. 459 systemstack(func() { macherror(r, "semaphore_signal") }) 460 } 461 } 462 463 //go:nosplit 464 func osyield() { 465 usleep(1) 466 } 467 468 func memlimit() uintptr { 469 // NOTE(rsc): Could use getrlimit here, 470 // like on FreeBSD or Linux, but Darwin doesn't enforce 471 // ulimit -v, so it's unclear why we'd try to stay within 472 // the limit. 473 return 0 474 } 475 476 //go:nosplit 477 //go:nowritebarrierrec 478 func setsig(i int32, fn uintptr, restart bool) { 479 var sa sigactiont 480 sa.sa_flags = _SA_SIGINFO | _SA_ONSTACK 481 if restart { 482 sa.sa_flags |= _SA_RESTART 483 } 484 sa.sa_mask = ^uint32(0) 485 sa.sa_tramp = unsafe.Pointer(funcPC(sigtramp)) // runtimeĀ·sigtramp's job is to call into real handler 486 *(*uintptr)(unsafe.Pointer(&sa.__sigaction_u)) = fn 487 sigaction(uint32(i), &sa, nil) 488 } 489 490 //go:nosplit 491 //go:nowritebarrierrec 492 func setsigstack(i int32) { 493 var osa usigactiont 494 sigaction(uint32(i), nil, &osa) 495 handler := *(*uintptr)(unsafe.Pointer(&osa.__sigaction_u)) 496 if handler == 0 || handler == _SIG_DFL || handler == _SIG_IGN || osa.sa_flags&_SA_ONSTACK != 0 { 497 return 498 } 499 var sa sigactiont 500 *(*uintptr)(unsafe.Pointer(&sa.__sigaction_u)) = handler 501 sa.sa_tramp = unsafe.Pointer(funcPC(sigtramp)) 502 sa.sa_mask = osa.sa_mask 503 sa.sa_flags = osa.sa_flags | _SA_ONSTACK 504 sigaction(uint32(i), &sa, nil) 505 } 506 507 //go:nosplit 508 //go:nowritebarrierrec 509 func getsig(i int32) uintptr { 510 var sa usigactiont 511 sigaction(uint32(i), nil, &sa) 512 return *(*uintptr)(unsafe.Pointer(&sa.__sigaction_u)) 513 } 514 515 //go:nosplit 516 func signalstack(s *stack) { 517 var st stackt 518 if s == nil { 519 st.ss_flags = _SS_DISABLE 520 } else { 521 st.ss_sp = (*byte)(unsafe.Pointer(s.lo)) 522 st.ss_size = s.hi - s.lo 523 st.ss_flags = 0 524 } 525 sigaltstack(&st, nil) 526 } 527 528 //go:nosplit 529 //go:nowritebarrierrec 530 func updatesigmask(m sigmask) { 531 s := sigset(m[0]) 532 sigprocmask(_SIG_SETMASK, &s, nil) 533 } 534 535 func unblocksig(sig int32) { 536 mask := sigset(1) << (uint32(sig) - 1) 537 sigprocmask(_SIG_UNBLOCK, &mask, nil) 538 }