Source file src/runtime/syscall_windows.go

     1  // Copyright 2014 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 (
     8  	"internal/abi"
     9  	"internal/goarch"
    10  	"internal/runtime/syscall/windows"
    11  	"unsafe"
    12  )
    13  
    14  // cbs stores all registered Go callbacks.
    15  var cbs struct {
    16  	lock  mutex // use cbsLock / cbsUnlock for race instrumentation.
    17  	ctxt  [cb_max]winCallback
    18  	index map[winCallbackKey]int
    19  	n     int
    20  }
    21  
    22  func cbsLock() {
    23  	lock(&cbs.lock)
    24  	// compileCallback is used by goenvs prior to completion of schedinit.
    25  	// raceacquire involves a racecallback to get the proc, which is not
    26  	// safe prior to scheduler initialization. Thus avoid instrumentation
    27  	// until then.
    28  	if raceenabled && mainStarted {
    29  		raceacquire(unsafe.Pointer(&cbs.lock))
    30  	}
    31  }
    32  
    33  func cbsUnlock() {
    34  	if raceenabled && mainStarted {
    35  		racerelease(unsafe.Pointer(&cbs.lock))
    36  	}
    37  	unlock(&cbs.lock)
    38  }
    39  
    40  // winCallback records information about a registered Go callback.
    41  type winCallback struct {
    42  	fn     *funcval // Go function
    43  	retPop uintptr  // For 386 cdecl, how many bytes to pop on return
    44  	abiMap abiDesc
    45  }
    46  
    47  // abiPartKind is the action an abiPart should take.
    48  type abiPartKind int
    49  
    50  const (
    51  	abiPartBad   abiPartKind = iota
    52  	abiPartStack             // Move a value from memory to the stack.
    53  	abiPartReg               // Move a value from memory to a register.
    54  )
    55  
    56  // abiPart encodes a step in translating between calling ABIs.
    57  type abiPart struct {
    58  	kind           abiPartKind
    59  	srcStackOffset uintptr
    60  	dstStackOffset uintptr // used if kind == abiPartStack
    61  	dstRegister    int     // used if kind == abiPartReg
    62  	len            uintptr
    63  }
    64  
    65  func (a *abiPart) tryMerge(b abiPart) bool {
    66  	if a.kind != abiPartStack || b.kind != abiPartStack {
    67  		return false
    68  	}
    69  	if a.srcStackOffset+a.len == b.srcStackOffset && a.dstStackOffset+a.len == b.dstStackOffset {
    70  		a.len += b.len
    71  		return true
    72  	}
    73  	return false
    74  }
    75  
    76  // abiDesc specifies how to translate from a C frame to a Go
    77  // frame. This does not specify how to translate back because
    78  // the result is always a uintptr. If the C ABI is fastcall,
    79  // this assumes the four fastcall registers were first spilled
    80  // to the shadow space.
    81  type abiDesc struct {
    82  	parts []abiPart
    83  
    84  	srcStackSize uintptr // stdcall/fastcall stack space tracking
    85  	dstStackSize uintptr // Go stack space used
    86  	dstSpill     uintptr // Extra stack space for argument spill slots
    87  	dstRegisters int     // Go ABI int argument registers used
    88  
    89  	// retOffset is the offset of the uintptr-sized result in the Go
    90  	// frame.
    91  	retOffset uintptr
    92  }
    93  
    94  func (p *abiDesc) assignArg(t *_type) {
    95  	if t.Size_ > goarch.PtrSize {
    96  		// We don't support this right now. In
    97  		// stdcall/cdecl, 64-bit ints and doubles are
    98  		// passed as two words (little endian); and
    99  		// structs are pushed on the stack. In
   100  		// fastcall, arguments larger than the word
   101  		// size are passed by reference.
   102  		panic("compileCallback: argument size is larger than uintptr")
   103  	}
   104  	if k := t.Kind(); GOARCH != "386" && (k == abi.Float32 || k == abi.Float64) {
   105  		// In fastcall, floating-point arguments in
   106  		// the first four positions are passed in
   107  		// floating-point registers, which we don't
   108  		// currently spill.
   109  		// So basically we only support 386.
   110  		panic("compileCallback: float arguments not supported")
   111  	}
   112  
   113  	if t.Size_ == 0 {
   114  		// The Go ABI aligns for zero-sized types.
   115  		p.dstStackSize = alignUp(p.dstStackSize, uintptr(t.Align_))
   116  		return
   117  	}
   118  
   119  	// In the C ABI, we're already on a word boundary.
   120  	// Also, sub-word-sized fastcall register arguments
   121  	// are stored to the least-significant bytes of the
   122  	// argument word and all supported Windows
   123  	// architectures are little endian, so srcStackOffset
   124  	// is already pointing to the right place for smaller
   125  	// arguments.
   126  
   127  	oldParts := p.parts
   128  	if p.tryRegAssignArg(t, 0) {
   129  		// Account for spill space.
   130  		//
   131  		// TODO(mknyszek): Remove this when we no longer have
   132  		// caller reserved spill space.
   133  		p.dstSpill = alignUp(p.dstSpill, uintptr(t.Align_))
   134  		p.dstSpill += t.Size_
   135  	} else {
   136  		// Register assignment failed.
   137  		// Undo the work and stack assign.
   138  		p.parts = oldParts
   139  
   140  		// The Go ABI aligns arguments.
   141  		p.dstStackSize = alignUp(p.dstStackSize, uintptr(t.Align_))
   142  
   143  		// Copy just the size of the argument. Note that this
   144  		// could be a small by-value struct, but C and Go
   145  		// struct layouts are compatible, so we can copy these
   146  		// directly, too.
   147  		part := abiPart{
   148  			kind:           abiPartStack,
   149  			srcStackOffset: p.srcStackSize,
   150  			dstStackOffset: p.dstStackSize,
   151  			len:            t.Size_,
   152  		}
   153  		// Add this step to the adapter.
   154  		if len(p.parts) == 0 || !p.parts[len(p.parts)-1].tryMerge(part) {
   155  			p.parts = append(p.parts, part)
   156  		}
   157  		// The Go ABI packs arguments.
   158  		p.dstStackSize += t.Size_
   159  	}
   160  
   161  	// cdecl, stdcall, and fastcall pad arguments to word size.
   162  	// TODO(rsc): On arm64 do we need to skip the caller's saved LR?
   163  	p.srcStackSize += goarch.PtrSize
   164  }
   165  
   166  // tryRegAssignArg tries to register-assign a value of type t.
   167  // If this type is nested in an aggregate type, then offset is the
   168  // offset of this type within its parent type.
   169  // Assumes t.size <= goarch.PtrSize and t.size != 0.
   170  //
   171  // Returns whether the assignment succeeded.
   172  func (p *abiDesc) tryRegAssignArg(t *_type, offset uintptr) bool {
   173  	switch k := t.Kind(); k {
   174  	case abi.Bool, abi.Int, abi.Int8, abi.Int16, abi.Int32, abi.Uint, abi.Uint8, abi.Uint16, abi.Uint32, abi.Uintptr, abi.Pointer, abi.UnsafePointer:
   175  		// Assign a register for all these types.
   176  		return p.assignReg(t.Size_, offset)
   177  	case abi.Int64, abi.Uint64:
   178  		// Only register-assign if the registers are big enough.
   179  		if goarch.PtrSize == 8 {
   180  			return p.assignReg(t.Size_, offset)
   181  		}
   182  	case abi.Array:
   183  		at := (*arraytype)(unsafe.Pointer(t))
   184  		if at.Len == 1 {
   185  			return p.tryRegAssignArg(at.Elem, offset) // TODO fix when runtime is fully commoned up w/ abi.Type
   186  		}
   187  	case abi.Struct:
   188  		st := (*structtype)(unsafe.Pointer(t))
   189  		for i := range st.Fields {
   190  			f := &st.Fields[i]
   191  			if !p.tryRegAssignArg(f.Typ, offset+f.Offset) {
   192  				return false
   193  			}
   194  		}
   195  		return true
   196  	}
   197  	// Pointer-sized types such as maps and channels are currently
   198  	// not supported.
   199  	panic("compileCallback: type " + toRType(t).string() + " is currently not supported for use in system callbacks")
   200  }
   201  
   202  // assignReg attempts to assign a single register for an
   203  // argument with the given size, at the given offset into the
   204  // value in the C ABI space.
   205  //
   206  // Returns whether the assignment was successful.
   207  func (p *abiDesc) assignReg(size, offset uintptr) bool {
   208  	if p.dstRegisters >= intArgRegs {
   209  		return false
   210  	}
   211  	p.parts = append(p.parts, abiPart{
   212  		kind:           abiPartReg,
   213  		srcStackOffset: p.srcStackSize + offset,
   214  		dstRegister:    p.dstRegisters,
   215  		len:            size,
   216  	})
   217  	p.dstRegisters++
   218  	return true
   219  }
   220  
   221  type winCallbackKey struct {
   222  	fn    *funcval
   223  	cdecl bool
   224  }
   225  
   226  func callbackasm()
   227  
   228  // callbackasmAddr returns address of runtime.callbackasm
   229  // function adjusted by i.
   230  // On x86 and amd64, runtime.callbackasm is a series of CALL instructions,
   231  // and we want callback to arrive at
   232  // correspondent call instruction instead of start of
   233  // runtime.callbackasm.
   234  // On ARM64, runtime.callbackasm is a series of mov and branch instructions.
   235  // R12 is loaded with the callback index. Each entry is two instructions,
   236  // hence 8 bytes.
   237  func callbackasmAddr(i int) uintptr {
   238  	var entrySize int
   239  	switch GOARCH {
   240  	default:
   241  		panic("unsupported architecture")
   242  	case "386", "amd64":
   243  		entrySize = 5
   244  	case "arm64":
   245  		// On ARM64, each entry is a MOV instruction
   246  		// followed by a branch instruction
   247  		entrySize = 8
   248  	}
   249  	return abi.FuncPCABI0(callbackasm) + uintptr(i*entrySize)
   250  }
   251  
   252  const callbackMaxFrame = 64 * goarch.PtrSize
   253  
   254  // compileCallback converts a Go function fn into a C function pointer
   255  // that can be passed to Windows APIs.
   256  //
   257  // On 386, if cdecl is true, the returned C function will use the
   258  // cdecl calling convention; otherwise, it will use stdcall. On amd64,
   259  // it always uses fastcall.
   260  //
   261  //go:linkname compileCallback syscall.compileCallback
   262  func compileCallback(fn eface, cdecl bool) (code uintptr) {
   263  	if GOARCH != "386" {
   264  		// cdecl is only meaningful on 386.
   265  		cdecl = false
   266  	}
   267  
   268  	if fn._type == nil || fn._type.Kind() != abi.Func {
   269  		panic("compileCallback: expected function with one uintptr-sized result")
   270  	}
   271  	ft := (*functype)(unsafe.Pointer(fn._type))
   272  
   273  	// Check arguments and construct ABI translation.
   274  	var abiMap abiDesc
   275  	for _, t := range ft.InSlice() {
   276  		abiMap.assignArg(t)
   277  	}
   278  	// The Go ABI aligns the result to the word size. src is
   279  	// already aligned.
   280  	abiMap.dstStackSize = alignUp(abiMap.dstStackSize, goarch.PtrSize)
   281  	abiMap.retOffset = abiMap.dstStackSize
   282  
   283  	if len(ft.OutSlice()) != 1 {
   284  		panic("compileCallback: expected function with one uintptr-sized result")
   285  	}
   286  	if ft.OutSlice()[0].Size_ != goarch.PtrSize {
   287  		panic("compileCallback: expected function with one uintptr-sized result")
   288  	}
   289  	if k := ft.OutSlice()[0].Kind(); k == abi.Float32 || k == abi.Float64 {
   290  		// In cdecl and stdcall, float results are returned in
   291  		// ST(0). In fastcall, they're returned in XMM0.
   292  		// Either way, it's not AX.
   293  		panic("compileCallback: float results not supported")
   294  	}
   295  	if intArgRegs == 0 {
   296  		// Make room for the uintptr-sized result.
   297  		// If there are argument registers, the return value will
   298  		// be passed in the first register.
   299  		abiMap.dstStackSize += goarch.PtrSize
   300  	}
   301  
   302  	// TODO(mknyszek): Remove dstSpill from this calculation when we no longer have
   303  	// caller reserved spill space.
   304  	frameSize := alignUp(abiMap.dstStackSize, goarch.PtrSize)
   305  	frameSize += abiMap.dstSpill
   306  	if frameSize > callbackMaxFrame {
   307  		panic("compileCallback: function argument frame too large")
   308  	}
   309  
   310  	// For cdecl, the callee is responsible for popping its
   311  	// arguments from the C stack.
   312  	var retPop uintptr
   313  	if cdecl {
   314  		retPop = abiMap.srcStackSize
   315  	}
   316  
   317  	key := winCallbackKey{(*funcval)(fn.data), cdecl}
   318  
   319  	cbsLock()
   320  
   321  	// Check if this callback is already registered.
   322  	if n, ok := cbs.index[key]; ok {
   323  		cbsUnlock()
   324  		return callbackasmAddr(n)
   325  	}
   326  
   327  	// Register the callback.
   328  	if cbs.index == nil {
   329  		cbs.index = make(map[winCallbackKey]int)
   330  	}
   331  	n := cbs.n
   332  	if n >= len(cbs.ctxt) {
   333  		cbsUnlock()
   334  		throw("too many callback functions")
   335  	}
   336  	c := winCallback{key.fn, retPop, abiMap}
   337  	cbs.ctxt[n] = c
   338  	cbs.index[key] = n
   339  	cbs.n++
   340  
   341  	cbsUnlock()
   342  	return callbackasmAddr(n)
   343  }
   344  
   345  type callbackArgs struct {
   346  	index uintptr
   347  	// args points to the argument block.
   348  	//
   349  	// For cdecl and stdcall, all arguments are on the stack.
   350  	//
   351  	// For fastcall, the trampoline spills register arguments to
   352  	// the reserved spill slots below the stack arguments,
   353  	// resulting in a layout equivalent to stdcall.
   354  	args unsafe.Pointer
   355  	// Below are out-args from callbackWrap
   356  	result uintptr
   357  	retPop uintptr // For 386 cdecl, how many bytes to pop on return
   358  }
   359  
   360  // callbackWrap is called by callbackasm to invoke a registered C callback.
   361  func callbackWrap(a *callbackArgs) {
   362  	c := cbs.ctxt[a.index]
   363  	a.retPop = c.retPop
   364  
   365  	// Convert from C to Go ABI.
   366  	var regs abi.RegArgs
   367  	var frame [callbackMaxFrame]byte
   368  	goArgs := unsafe.Pointer(&frame)
   369  	for _, part := range c.abiMap.parts {
   370  		switch part.kind {
   371  		case abiPartStack:
   372  			memmove(add(goArgs, part.dstStackOffset), add(a.args, part.srcStackOffset), part.len)
   373  		case abiPartReg:
   374  			goReg := unsafe.Pointer(&regs.Ints[part.dstRegister])
   375  			memmove(goReg, add(a.args, part.srcStackOffset), part.len)
   376  		default:
   377  			panic("bad ABI description")
   378  		}
   379  	}
   380  
   381  	// TODO(mknyszek): Remove this when we no longer have
   382  	// caller reserved spill space.
   383  	frameSize := alignUp(c.abiMap.dstStackSize, goarch.PtrSize)
   384  	frameSize += c.abiMap.dstSpill
   385  
   386  	// Even though this is copying back results, we can pass a nil
   387  	// type because those results must not require write barriers.
   388  	reflectcall(nil, unsafe.Pointer(c.fn), noescape(goArgs), uint32(c.abiMap.dstStackSize), uint32(c.abiMap.retOffset), uint32(frameSize), &regs)
   389  
   390  	// Extract the result.
   391  	//
   392  	// There's always exactly one return value, one pointer in size.
   393  	// If it's on the stack, then we will have reserved space for it
   394  	// at the end of the frame, otherwise it was passed in a register.
   395  	if c.abiMap.dstStackSize != c.abiMap.retOffset {
   396  		a.result = *(*uintptr)(unsafe.Pointer(&frame[c.abiMap.retOffset]))
   397  	} else {
   398  		var zero int
   399  		// On architectures with no registers, Ints[0] would be a compile error,
   400  		// so we use a dynamic index. These architectures will never take this
   401  		// branch, so this won't cause a runtime panic.
   402  		a.result = regs.Ints[zero]
   403  	}
   404  }
   405  
   406  // syscall_syscalln calls fn with args[:n].
   407  // It is used to implement [syscall.SyscallN].
   408  // It shouldn't be used in the runtime package,
   409  // use [stdcall] instead.
   410  //
   411  //go:linkname syscall_syscalln syscall.syscalln
   412  //go:nosplit
   413  //go:uintptrkeepalive
   414  func syscall_syscalln(fn, n uintptr, args ...uintptr) (r1, r2, err uintptr) {
   415  	if n > uintptr(len(args)) {
   416  		panic("syscall: n > len(args)") // should not be reachable from user code
   417  	}
   418  	if n > windows.MaxArgs {
   419  		panic("runtime: SyscallN has too many arguments")
   420  	}
   421  
   422  	// The cgocall parameters are stored in m instead of in
   423  	// the stack because the stack can move during fn if it
   424  	// calls back into Go.
   425  	c := &getg().m.winsyscall
   426  	c.Fn = fn
   427  	c.N = n
   428  	if c.N != 0 {
   429  		c.Args = uintptr(noescape(unsafe.Pointer(&args[0])))
   430  	}
   431  	cgocall(asmstdcallAddr, unsafe.Pointer(c))
   432  	// cgocall may reschedule us on to a different M,
   433  	// but it copies the return values into the new M's
   434  	// so we can read them from there.
   435  	c = &getg().m.winsyscall
   436  	return c.R1, c.R2, c.Err
   437  }
   438  

View as plain text