github.com/x04/go/src@v0.0.0-20200202162449-3d481ceb3525/runtime/os_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 "github.com/x04/go/src/unsafe" 8 9 type mOS struct { 10 initialized bool 11 mutex pthreadmutex 12 cond pthreadcond 13 count int 14 } 15 16 func unimplemented(name string) { 17 println(name, "not implemented") 18 *(*int)(unsafe.Pointer(uintptr(1231))) = 1231 19 } 20 21 //go:nosplit 22 func semacreate(mp *m) { 23 if mp.initialized { 24 return 25 } 26 mp.initialized = true 27 if err := pthread_mutex_init(&mp.mutex, nil); err != 0 { 28 throw("pthread_mutex_init") 29 } 30 if err := pthread_cond_init(&mp.cond, nil); err != 0 { 31 throw("pthread_cond_init") 32 } 33 } 34 35 //go:nosplit 36 func semasleep(ns int64) int32 { 37 var start int64 38 if ns >= 0 { 39 start = nanotime() 40 } 41 mp := getg().m 42 pthread_mutex_lock(&mp.mutex) 43 for { 44 if mp.count > 0 { 45 mp.count-- 46 pthread_mutex_unlock(&mp.mutex) 47 return 0 48 } 49 if ns >= 0 { 50 spent := nanotime() - start 51 if spent >= ns { 52 pthread_mutex_unlock(&mp.mutex) 53 return -1 54 } 55 var t timespec 56 t.setNsec(ns - spent) 57 err := pthread_cond_timedwait_relative_np(&mp.cond, &mp.mutex, &t) 58 if err == _ETIMEDOUT { 59 pthread_mutex_unlock(&mp.mutex) 60 return -1 61 } 62 } else { 63 pthread_cond_wait(&mp.cond, &mp.mutex) 64 } 65 } 66 } 67 68 //go:nosplit 69 func semawakeup(mp *m) { 70 pthread_mutex_lock(&mp.mutex) 71 mp.count++ 72 if mp.count > 0 { 73 pthread_cond_signal(&mp.cond) 74 } 75 pthread_mutex_unlock(&mp.mutex) 76 } 77 78 // The read and write file descriptors used by the sigNote functions. 79 var sigNoteRead, sigNoteWrite int32 80 81 // sigNoteSetup initializes an async-signal-safe note. 82 // 83 // The current implementation of notes on Darwin is not async-signal-safe, 84 // because the functions pthread_mutex_lock, pthread_cond_signal, and 85 // pthread_mutex_unlock, called by semawakeup, are not async-signal-safe. 86 // There is only one case where we need to wake up a note from a signal 87 // handler: the sigsend function. The signal handler code does not require 88 // all the features of notes: it does not need to do a timed wait. 89 // This is a separate implementation of notes, based on a pipe, that does 90 // not support timed waits but is async-signal-safe. 91 func sigNoteSetup(*note) { 92 if sigNoteRead != 0 || sigNoteWrite != 0 { 93 throw("duplicate sigNoteSetup") 94 } 95 var errno int32 96 sigNoteRead, sigNoteWrite, errno = pipe() 97 if errno != 0 { 98 throw("pipe failed") 99 } 100 closeonexec(sigNoteRead) 101 closeonexec(sigNoteWrite) 102 103 // Make the write end of the pipe non-blocking, so that if the pipe 104 // buffer is somehow full we will not block in the signal handler. 105 // Leave the read end of the pipe blocking so that we will block 106 // in sigNoteSleep. 107 setNonblock(sigNoteWrite) 108 } 109 110 // sigNoteWakeup wakes up a thread sleeping on a note created by sigNoteSetup. 111 func sigNoteWakeup(*note) { 112 var b byte 113 write(uintptr(sigNoteWrite), unsafe.Pointer(&b), 1) 114 } 115 116 // sigNoteSleep waits for a note created by sigNoteSetup to be woken. 117 func sigNoteSleep(*note) { 118 entersyscallblock() 119 var b byte 120 read(sigNoteRead, unsafe.Pointer(&b), 1) 121 exitsyscall() 122 } 123 124 // BSD interface for threading. 125 func osinit() { 126 // pthread_create delayed until end of goenvs so that we 127 // can look at the environment first. 128 129 ncpu = getncpu() 130 physPageSize = getPageSize() 131 } 132 133 const ( 134 _CTL_HW = 6 135 _HW_NCPU = 3 136 _HW_PAGESIZE = 7 137 ) 138 139 func getncpu() int32 { 140 // Use sysctl to fetch hw.ncpu. 141 mib := [2]uint32{_CTL_HW, _HW_NCPU} 142 out := uint32(0) 143 nout := unsafe.Sizeof(out) 144 ret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0) 145 if ret >= 0 && int32(out) > 0 { 146 return int32(out) 147 } 148 return 1 149 } 150 151 func getPageSize() uintptr { 152 // Use sysctl to fetch hw.pagesize. 153 mib := [2]uint32{_CTL_HW, _HW_PAGESIZE} 154 out := uint32(0) 155 nout := unsafe.Sizeof(out) 156 ret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0) 157 if ret >= 0 && int32(out) > 0 { 158 return uintptr(out) 159 } 160 return 0 161 } 162 163 var urandom_dev = []byte("/dev/urandom\x00") 164 165 //go:nosplit 166 func getRandomData(r []byte) { 167 fd := open(&urandom_dev[0], 0 /* O_RDONLY */, 0) 168 n := read(fd, unsafe.Pointer(&r[0]), int32(len(r))) 169 closefd(fd) 170 extendRandom(r, int(n)) 171 } 172 173 func goenvs() { 174 goenvs_unix() 175 } 176 177 // May run with m.p==nil, so write barriers are not allowed. 178 //go:nowritebarrierrec 179 func newosproc(mp *m) { 180 stk := unsafe.Pointer(mp.g0.stack.hi) 181 if false { 182 print("newosproc stk=", stk, " m=", mp, " g=", mp.g0, " id=", mp.id, " ostk=", &mp, "\n") 183 } 184 185 // Initialize an attribute object. 186 var attr pthreadattr 187 var err int32 188 err = pthread_attr_init(&attr) 189 if err != 0 { 190 write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate))) 191 exit(1) 192 } 193 194 // Find out OS stack size for our own stack guard. 195 var stacksize uintptr 196 if pthread_attr_getstacksize(&attr, &stacksize) != 0 { 197 write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate))) 198 exit(1) 199 } 200 mp.g0.stack.hi = stacksize // for mstart 201 //mSysStatInc(&memstats.stacks_sys, stacksize) //TODO: do this? 202 203 // Tell the pthread library we won't join with this thread. 204 if pthread_attr_setdetachstate(&attr, _PTHREAD_CREATE_DETACHED) != 0 { 205 write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate))) 206 exit(1) 207 } 208 209 // Finally, create the thread. It starts at mstart_stub, which does some low-level 210 // setup and then calls mstart. 211 var oset sigset 212 sigprocmask(_SIG_SETMASK, &sigset_all, &oset) 213 err = pthread_create(&attr, funcPC(mstart_stub), unsafe.Pointer(mp)) 214 sigprocmask(_SIG_SETMASK, &oset, nil) 215 if err != 0 { 216 write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate))) 217 exit(1) 218 } 219 } 220 221 // glue code to call mstart from pthread_create. 222 func mstart_stub() 223 224 // newosproc0 is a version of newosproc that can be called before the runtime 225 // is initialized. 226 // 227 // This function is not safe to use after initialization as it does not pass an M as fnarg. 228 // 229 //go:nosplit 230 func newosproc0(stacksize uintptr, fn uintptr) { 231 // Initialize an attribute object. 232 var attr pthreadattr 233 var err int32 234 err = pthread_attr_init(&attr) 235 if err != 0 { 236 write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate))) 237 exit(1) 238 } 239 240 // The caller passes in a suggested stack size, 241 // from when we allocated the stack and thread ourselves, 242 // without libpthread. Now that we're using libpthread, 243 // we use the OS default stack size instead of the suggestion. 244 // Find out that stack size for our own stack guard. 245 if pthread_attr_getstacksize(&attr, &stacksize) != 0 { 246 write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate))) 247 exit(1) 248 } 249 g0.stack.hi = stacksize // for mstart 250 mSysStatInc(&memstats.stacks_sys, stacksize) 251 252 // Tell the pthread library we won't join with this thread. 253 if pthread_attr_setdetachstate(&attr, _PTHREAD_CREATE_DETACHED) != 0 { 254 write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate))) 255 exit(1) 256 } 257 258 // Finally, create the thread. It starts at mstart_stub, which does some low-level 259 // setup and then calls mstart. 260 var oset sigset 261 sigprocmask(_SIG_SETMASK, &sigset_all, &oset) 262 err = pthread_create(&attr, fn, nil) 263 sigprocmask(_SIG_SETMASK, &oset, nil) 264 if err != 0 { 265 write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate))) 266 exit(1) 267 } 268 } 269 270 var failallocatestack = []byte("runtime: failed to allocate stack for the new OS thread\n") 271 var failthreadcreate = []byte("runtime: failed to create new OS thread\n") 272 273 // Called to do synchronous initialization of Go code built with 274 // -buildmode=c-archive or -buildmode=c-shared. 275 // None of the Go runtime is initialized. 276 //go:nosplit 277 //go:nowritebarrierrec 278 func libpreinit() { 279 initsig(true) 280 } 281 282 // Called to initialize a new m (including the bootstrap m). 283 // Called on the parent thread (main thread in case of bootstrap), can allocate memory. 284 func mpreinit(mp *m) { 285 mp.gsignal = malg(32 * 1024) // OS X wants >= 8K 286 mp.gsignal.m = mp 287 } 288 289 // Called to initialize a new m (including the bootstrap m). 290 // Called on the new thread, cannot allocate memory. 291 func minit() { 292 // The alternate signal stack is buggy on arm and arm64. 293 // The signal handler handles it directly. 294 if GOARCH != "arm" && GOARCH != "arm64" { 295 minitSignalStack() 296 } 297 minitSignalMask() 298 getg().m.procid = uint64(pthread_self()) 299 } 300 301 // Called from dropm to undo the effect of an minit. 302 //go:nosplit 303 func unminit() { 304 // The alternate signal stack is buggy on arm and arm64. 305 // See minit. 306 if GOARCH != "arm" && GOARCH != "arm64" { 307 unminitSignals() 308 } 309 } 310 311 //go:nosplit 312 func osyield() { 313 usleep(1) 314 } 315 316 const ( 317 _NSIG = 32 318 _SI_USER = 0 /* empirically true, but not what headers say */ 319 _SIG_BLOCK = 1 320 _SIG_UNBLOCK = 2 321 _SIG_SETMASK = 3 322 _SS_DISABLE = 4 323 ) 324 325 //extern SigTabTT runtimeĀ·sigtab[]; 326 327 type sigset uint32 328 329 var sigset_all = ^sigset(0) 330 331 //go:nosplit 332 //go:nowritebarrierrec 333 func setsig(i uint32, fn uintptr) { 334 var sa usigactiont 335 sa.sa_flags = _SA_SIGINFO | _SA_ONSTACK | _SA_RESTART 336 sa.sa_mask = ^uint32(0) 337 if fn == funcPC(sighandler) { 338 if iscgo { 339 fn = funcPC(cgoSigtramp) 340 } else { 341 fn = funcPC(sigtramp) 342 } 343 } 344 *(*uintptr)(unsafe.Pointer(&sa.__sigaction_u)) = fn 345 sigaction(i, &sa, nil) 346 } 347 348 // sigtramp is the callback from libc when a signal is received. 349 // It is called with the C calling convention. 350 func sigtramp() 351 func cgoSigtramp() 352 353 //go:nosplit 354 //go:nowritebarrierrec 355 func setsigstack(i uint32) { 356 var osa usigactiont 357 sigaction(i, nil, &osa) 358 handler := *(*uintptr)(unsafe.Pointer(&osa.__sigaction_u)) 359 if osa.sa_flags&_SA_ONSTACK != 0 { 360 return 361 } 362 var sa usigactiont 363 *(*uintptr)(unsafe.Pointer(&sa.__sigaction_u)) = handler 364 sa.sa_mask = osa.sa_mask 365 sa.sa_flags = osa.sa_flags | _SA_ONSTACK 366 sigaction(i, &sa, nil) 367 } 368 369 //go:nosplit 370 //go:nowritebarrierrec 371 func getsig(i uint32) uintptr { 372 var sa usigactiont 373 sigaction(i, nil, &sa) 374 return *(*uintptr)(unsafe.Pointer(&sa.__sigaction_u)) 375 } 376 377 // setSignaltstackSP sets the ss_sp field of a stackt. 378 //go:nosplit 379 func setSignalstackSP(s *stackt, sp uintptr) { 380 *(*uintptr)(unsafe.Pointer(&s.ss_sp)) = sp 381 } 382 383 //go:nosplit 384 //go:nowritebarrierrec 385 func sigaddset(mask *sigset, i int) { 386 *mask |= 1 << (uint32(i) - 1) 387 } 388 389 func sigdelset(mask *sigset, i int) { 390 *mask &^= 1 << (uint32(i) - 1) 391 } 392 393 //go:linkname executablePath os.executablePath 394 var executablePath string 395 396 func sysargs(argc int32, argv **byte) { 397 // skip over argv, envv and the first string will be the path 398 n := argc + 1 399 for argv_index(argv, n) != nil { 400 n++ 401 } 402 executablePath = gostringnocopy(argv_index(argv, n+1)) 403 404 // strip "executable_path=" prefix if available, it's added after OS X 10.11. 405 const prefix = "executable_path=" 406 if len(executablePath) > len(prefix) && executablePath[:len(prefix)] == prefix { 407 executablePath = executablePath[len(prefix):] 408 } 409 } 410 411 func signalM(mp *m, sig int) { 412 pthread_kill(pthread(mp.procid), uint32(sig)) 413 }