github.com/hbdrawn/golang@v0.0.0-20141214014649-6b835209aba2/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  var sigset_none = uint32(0)
    12  var sigset_all = ^uint32(0)
    13  
    14  func unimplemented(name string) {
    15  	println(name, "not implemented")
    16  	*(*int)(unsafe.Pointer(uintptr(1231))) = 1231
    17  }
    18  
    19  //go:nosplit
    20  func semawakeup(mp *m) {
    21  	mach_semrelease(uint32(mp.waitsema))
    22  }
    23  
    24  //go:nosplit
    25  func semacreate() uintptr {
    26  	var x uintptr
    27  	systemstack(func() {
    28  		x = uintptr(mach_semcreate())
    29  	})
    30  	return x
    31  }
    32  
    33  // BSD interface for threading.
    34  func osinit() {
    35  	// bsdthread_register delayed until end of goenvs so that we
    36  	// can look at the environment first.
    37  
    38  	// Use sysctl to fetch hw.ncpu.
    39  	mib := [2]uint32{6, 3}
    40  	out := uint32(0)
    41  	nout := unsafe.Sizeof(out)
    42  	ret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0)
    43  	if ret >= 0 {
    44  		ncpu = int32(out)
    45  	}
    46  }
    47  
    48  var urandom_data [_HashRandomBytes]byte
    49  var urandom_dev = []byte("/dev/random\x00")
    50  
    51  //go:nosplit
    52  func get_random_data(rnd *unsafe.Pointer, rnd_len *int32) {
    53  	fd := open(&urandom_dev[0], 0 /* O_RDONLY */, 0)
    54  	if read(fd, unsafe.Pointer(&urandom_data), _HashRandomBytes) == _HashRandomBytes {
    55  		*rnd = unsafe.Pointer(&urandom_data[0])
    56  		*rnd_len = _HashRandomBytes
    57  	} else {
    58  		*rnd = nil
    59  		*rnd_len = 0
    60  	}
    61  	close(fd)
    62  }
    63  
    64  func goenvs() {
    65  	goenvs_unix()
    66  
    67  	// Register our thread-creation callback (see sys_darwin_{amd64,386}.s)
    68  	// but only if we're not using cgo.  If we are using cgo we need
    69  	// to let the C pthread library install its own thread-creation callback.
    70  	if !iscgo {
    71  		if bsdthread_register() != 0 {
    72  			if gogetenv("DYLD_INSERT_LIBRARIES") != "" {
    73  				gothrow("runtime: bsdthread_register error (unset DYLD_INSERT_LIBRARIES)")
    74  			}
    75  			gothrow("runtime: bsdthread_register error")
    76  		}
    77  	}
    78  }
    79  
    80  func newosproc(mp *m, stk unsafe.Pointer) {
    81  	mp.tls[0] = uintptr(mp.id) // so 386 asm can find it
    82  	if false {
    83  		print("newosproc stk=", stk, " m=", mp, " g=", mp.g0, " id=", mp.id, "/", int(mp.tls[0]), " ostk=", &mp, "\n")
    84  	}
    85  
    86  	var oset uint32
    87  	sigprocmask(_SIG_SETMASK, &sigset_all, &oset)
    88  	errno := bsdthread_create(stk, mp, mp.g0, funcPC(mstart))
    89  	sigprocmask(_SIG_SETMASK, &oset, nil)
    90  
    91  	if errno < 0 {
    92  		print("runtime: failed to create new OS thread (have ", mcount(), " already; errno=", -errno, ")\n")
    93  		gothrow("runtime.newosproc")
    94  	}
    95  }
    96  
    97  // Called to initialize a new m (including the bootstrap m).
    98  // Called on the parent thread (main thread in case of bootstrap), can allocate memory.
    99  func mpreinit(mp *m) {
   100  	mp.gsignal = malg(32 * 1024) // OS X wants >= 8K
   101  	mp.gsignal.m = mp
   102  }
   103  
   104  // Called to initialize a new m (including the bootstrap m).
   105  // Called on the new thread, can not allocate memory.
   106  func minit() {
   107  	// Initialize signal handling.
   108  	_g_ := getg()
   109  	signalstack((*byte)(unsafe.Pointer(_g_.m.gsignal.stack.lo)), 32*1024)
   110  	sigprocmask(_SIG_SETMASK, &sigset_none, nil)
   111  }
   112  
   113  // Called from dropm to undo the effect of an minit.
   114  func unminit() {
   115  	signalstack(nil, 0)
   116  }
   117  
   118  // Mach IPC, to get at semaphores
   119  // Definitions are in /usr/include/mach on a Mac.
   120  
   121  func macherror(r int32, fn string) {
   122  	print("mach error ", fn, ": ", r, "\n")
   123  	gothrow("mach error")
   124  }
   125  
   126  const _DebugMach = false
   127  
   128  var zerondr machndr
   129  
   130  func mach_msgh_bits(a, b uint32) uint32 {
   131  	return a | b<<8
   132  }
   133  
   134  func mach_msg(h *machheader, op int32, send_size, rcv_size, rcv_name, timeout, notify uint32) int32 {
   135  	// TODO: Loop on interrupt.
   136  	return mach_msg_trap(unsafe.Pointer(h), op, send_size, rcv_size, rcv_name, timeout, notify)
   137  }
   138  
   139  // Mach RPC (MIG)
   140  const (
   141  	_MinMachMsg = 48
   142  	_MachReply  = 100
   143  )
   144  
   145  type codemsg struct {
   146  	h    machheader
   147  	ndr  machndr
   148  	code int32
   149  }
   150  
   151  func machcall(h *machheader, maxsize int32, rxsize int32) int32 {
   152  	_g_ := getg()
   153  	port := _g_.m.machport
   154  	if port == 0 {
   155  		port = mach_reply_port()
   156  		_g_.m.machport = port
   157  	}
   158  
   159  	h.msgh_bits |= mach_msgh_bits(_MACH_MSG_TYPE_COPY_SEND, _MACH_MSG_TYPE_MAKE_SEND_ONCE)
   160  	h.msgh_local_port = port
   161  	h.msgh_reserved = 0
   162  	id := h.msgh_id
   163  
   164  	if _DebugMach {
   165  		p := (*[10000]unsafe.Pointer)(unsafe.Pointer(h))
   166  		print("send:\t")
   167  		var i uint32
   168  		for i = 0; i < h.msgh_size/uint32(unsafe.Sizeof(p[0])); i++ {
   169  			print(" ", p[i])
   170  			if i%8 == 7 {
   171  				print("\n\t")
   172  			}
   173  		}
   174  		if i%8 != 0 {
   175  			print("\n")
   176  		}
   177  	}
   178  	ret := mach_msg(h, _MACH_SEND_MSG|_MACH_RCV_MSG, h.msgh_size, uint32(maxsize), port, 0, 0)
   179  	if ret != 0 {
   180  		if _DebugMach {
   181  			print("mach_msg error ", ret, "\n")
   182  		}
   183  		return ret
   184  	}
   185  	if _DebugMach {
   186  		p := (*[10000]unsafe.Pointer)(unsafe.Pointer(h))
   187  		var i uint32
   188  		for i = 0; i < h.msgh_size/uint32(unsafe.Sizeof(p[0])); i++ {
   189  			print(" ", p[i])
   190  			if i%8 == 7 {
   191  				print("\n\t")
   192  			}
   193  		}
   194  		if i%8 != 0 {
   195  			print("\n")
   196  		}
   197  	}
   198  	if h.msgh_id != id+_MachReply {
   199  		if _DebugMach {
   200  			print("mach_msg _MachReply id mismatch ", h.msgh_id, " != ", id+_MachReply, "\n")
   201  		}
   202  		return -303 // MIG_REPLY_MISMATCH
   203  	}
   204  	// Look for a response giving the return value.
   205  	// Any call can send this back with an error,
   206  	// and some calls only have return values so they
   207  	// send it back on success too.  I don't quite see how
   208  	// you know it's one of these and not the full response
   209  	// format, so just look if the message is right.
   210  	c := (*codemsg)(unsafe.Pointer(h))
   211  	if uintptr(h.msgh_size) == unsafe.Sizeof(*c) && h.msgh_bits&_MACH_MSGH_BITS_COMPLEX == 0 {
   212  		if _DebugMach {
   213  			print("mig result ", c.code, "\n")
   214  		}
   215  		return c.code
   216  	}
   217  	if h.msgh_size != uint32(rxsize) {
   218  		if _DebugMach {
   219  			print("mach_msg _MachReply size mismatch ", h.msgh_size, " != ", rxsize, "\n")
   220  		}
   221  		return -307 // MIG_ARRAY_TOO_LARGE
   222  	}
   223  	return 0
   224  }
   225  
   226  // Semaphores!
   227  
   228  const (
   229  	tmach_semcreate = 3418
   230  	rmach_semcreate = tmach_semcreate + _MachReply
   231  
   232  	tmach_semdestroy = 3419
   233  	rmach_semdestroy = tmach_semdestroy + _MachReply
   234  
   235  	_KERN_ABORTED             = 14
   236  	_KERN_OPERATION_TIMED_OUT = 49
   237  )
   238  
   239  type tmach_semcreatemsg struct {
   240  	h      machheader
   241  	ndr    machndr
   242  	policy int32
   243  	value  int32
   244  }
   245  
   246  type rmach_semcreatemsg struct {
   247  	h         machheader
   248  	body      machbody
   249  	semaphore machport
   250  }
   251  
   252  type tmach_semdestroymsg struct {
   253  	h         machheader
   254  	body      machbody
   255  	semaphore machport
   256  }
   257  
   258  func mach_semcreate() uint32 {
   259  	var m [256]uint8
   260  	tx := (*tmach_semcreatemsg)(unsafe.Pointer(&m))
   261  	rx := (*rmach_semcreatemsg)(unsafe.Pointer(&m))
   262  
   263  	tx.h.msgh_bits = 0
   264  	tx.h.msgh_size = uint32(unsafe.Sizeof(*tx))
   265  	tx.h.msgh_remote_port = mach_task_self()
   266  	tx.h.msgh_id = tmach_semcreate
   267  	tx.ndr = zerondr
   268  
   269  	tx.policy = 0 // 0 = SYNC_POLICY_FIFO
   270  	tx.value = 0
   271  
   272  	for {
   273  		r := machcall(&tx.h, int32(unsafe.Sizeof(m)), int32(unsafe.Sizeof(*rx)))
   274  		if r == 0 {
   275  			break
   276  		}
   277  		if r == _KERN_ABORTED { // interrupted
   278  			continue
   279  		}
   280  		macherror(r, "semaphore_create")
   281  	}
   282  	if rx.body.msgh_descriptor_count != 1 {
   283  		unimplemented("mach_semcreate desc count")
   284  	}
   285  	return rx.semaphore.name
   286  }
   287  
   288  func mach_semdestroy(sem uint32) {
   289  	var m [256]uint8
   290  	tx := (*tmach_semdestroymsg)(unsafe.Pointer(&m))
   291  
   292  	tx.h.msgh_bits = _MACH_MSGH_BITS_COMPLEX
   293  	tx.h.msgh_size = uint32(unsafe.Sizeof(*tx))
   294  	tx.h.msgh_remote_port = mach_task_self()
   295  	tx.h.msgh_id = tmach_semdestroy
   296  	tx.body.msgh_descriptor_count = 1
   297  	tx.semaphore.name = sem
   298  	tx.semaphore.disposition = _MACH_MSG_TYPE_MOVE_SEND
   299  	tx.semaphore._type = 0
   300  
   301  	for {
   302  		r := machcall(&tx.h, int32(unsafe.Sizeof(m)), 0)
   303  		if r == 0 {
   304  			break
   305  		}
   306  		if r == _KERN_ABORTED { // interrupted
   307  			continue
   308  		}
   309  		macherror(r, "semaphore_destroy")
   310  	}
   311  }
   312  
   313  // The other calls have simple system call traps in sys_darwin_{amd64,386}.s
   314  
   315  func mach_semaphore_wait(sema uint32) int32
   316  func mach_semaphore_timedwait(sema, sec, nsec uint32) int32
   317  func mach_semaphore_signal(sema uint32) int32
   318  func mach_semaphore_signal_all(sema uint32) int32
   319  
   320  func semasleep1(ns int64) int32 {
   321  	_g_ := getg()
   322  
   323  	if ns >= 0 {
   324  		var nsecs int32
   325  		secs := timediv(ns, 1000000000, &nsecs)
   326  		r := mach_semaphore_timedwait(uint32(_g_.m.waitsema), uint32(secs), uint32(nsecs))
   327  		if r == _KERN_ABORTED || r == _KERN_OPERATION_TIMED_OUT {
   328  			return -1
   329  		}
   330  		if r != 0 {
   331  			macherror(r, "semaphore_wait")
   332  		}
   333  		return 0
   334  	}
   335  
   336  	for {
   337  		r := mach_semaphore_wait(uint32(_g_.m.waitsema))
   338  		if r == 0 {
   339  			break
   340  		}
   341  		if r == _KERN_ABORTED { // interrupted
   342  			continue
   343  		}
   344  		macherror(r, "semaphore_wait")
   345  	}
   346  	return 0
   347  }
   348  
   349  //go:nosplit
   350  func semasleep(ns int64) int32 {
   351  	var r int32
   352  	systemstack(func() {
   353  		r = semasleep1(ns)
   354  	})
   355  	return r
   356  }
   357  
   358  //go:nosplit
   359  func mach_semrelease(sem uint32) {
   360  	for {
   361  		r := mach_semaphore_signal(sem)
   362  		if r == 0 {
   363  			break
   364  		}
   365  		if r == _KERN_ABORTED { // interrupted
   366  			continue
   367  		}
   368  
   369  		// mach_semrelease must be completely nosplit,
   370  		// because it is called from Go code.
   371  		// If we're going to die, start that process on the system stack
   372  		// to avoid a Go stack split.
   373  		systemstack(func() { macherror(r, "semaphore_signal") })
   374  	}
   375  }
   376  
   377  //go:nosplit
   378  func osyield() {
   379  	usleep(1)
   380  }
   381  
   382  func memlimit() uintptr {
   383  	// NOTE(rsc): Could use getrlimit here,
   384  	// like on FreeBSD or Linux, but Darwin doesn't enforce
   385  	// ulimit -v, so it's unclear why we'd try to stay within
   386  	// the limit.
   387  	return 0
   388  }
   389  
   390  func setsig(i int32, fn uintptr, restart bool) {
   391  	var sa sigactiont
   392  	memclr(unsafe.Pointer(&sa), unsafe.Sizeof(sa))
   393  	sa.sa_flags = _SA_SIGINFO | _SA_ONSTACK
   394  	if restart {
   395  		sa.sa_flags |= _SA_RESTART
   396  	}
   397  	sa.sa_mask = ^uint32(0)
   398  	sa.sa_tramp = unsafe.Pointer(funcPC(sigtramp)) // runtimeĀ·sigtramp's job is to call into real handler
   399  	*(*uintptr)(unsafe.Pointer(&sa.__sigaction_u)) = fn
   400  	sigaction(uint32(i), &sa, nil)
   401  }
   402  
   403  func getsig(i int32) uintptr {
   404  	var sa sigactiont
   405  	memclr(unsafe.Pointer(&sa), unsafe.Sizeof(sa))
   406  	sigaction(uint32(i), nil, &sa)
   407  	return *(*uintptr)(unsafe.Pointer(&sa.__sigaction_u))
   408  }
   409  
   410  func signalstack(p *byte, n int32) {
   411  	var st stackt
   412  	st.ss_sp = p
   413  	st.ss_size = uintptr(n)
   414  	st.ss_flags = 0
   415  	if p == nil {
   416  		st.ss_flags = _SS_DISABLE
   417  	}
   418  	sigaltstack(&st, nil)
   419  }
   420  
   421  func unblocksignals() {
   422  	sigprocmask(_SIG_SETMASK, &sigset_none, nil)
   423  }