syscall_sysv.go raw

   1  // SPDX-License-Identifier: Apache-2.0
   2  // SPDX-FileCopyrightText: 2022 The Ebitengine Authors
   3  
   4  // TODO: remove s390x cgo dependency once golang/go#77449 is resolved
   5  //go:build darwin || freebsd || (linux && (386 || amd64 || arm || arm64 || loong64 || ppc64le || riscv64 || (cgo && s390x))) || netbsd
   6  
   7  package purego
   8  
   9  import (
  10  	"reflect"
  11  	"runtime"
  12  	"sync"
  13  	"unsafe"
  14  )
  15  
  16  var syscall15XABI0 uintptr
  17  
  18  func syscall_syscall15X(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15 uintptr) (r1, r2, err uintptr) {
  19  	args := thePool.Get().(*syscall15Args)
  20  	defer thePool.Put(args)
  21  
  22  	*args = syscall15Args{
  23  		fn: fn,
  24  		a1: a1, a2: a2, a3: a3, a4: a4, a5: a5, a6: a6, a7: a7, a8: a8,
  25  		a9: a9, a10: a10, a11: a11, a12: a12, a13: a13, a14: a14, a15: a15,
  26  		f1: a1, f2: a2, f3: a3, f4: a4, f5: a5, f6: a6, f7: a7, f8: a8,
  27  	}
  28  
  29  	runtime_cgocall(syscall15XABI0, unsafe.Pointer(args))
  30  	return args.a1, args.a2, args.a3
  31  }
  32  
  33  // NewCallback converts a Go function to a function pointer conforming to the C calling convention.
  34  // This is useful when interoperating with C code requiring callbacks. The argument is expected to be a
  35  // function with zero or one uintptr-sized result. The function must not have arguments with size larger than the size
  36  // of uintptr. Only a limited number of callbacks may be created in a single Go process, and any memory allocated
  37  // for these callbacks is never released. At least 2000 callbacks can always be created. Although this function
  38  // provides similar functionality to windows.NewCallback it is distinct.
  39  func NewCallback(fn any) uintptr {
  40  	ty := reflect.TypeOf(fn)
  41  	for i := 0; i < ty.NumIn(); i++ {
  42  		in := ty.In(i)
  43  		if !in.AssignableTo(reflect.TypeOf(CDecl{})) {
  44  			continue
  45  		}
  46  		if i != 0 {
  47  			panic("purego: CDecl must be the first argument")
  48  		}
  49  	}
  50  	return compileCallback(fn)
  51  }
  52  
  53  // maxCb is the maximum number of callbacks
  54  // only increase this if you have added more to the callbackasm function
  55  const maxCB = 2000
  56  
  57  var cbs struct {
  58  	lock  sync.Mutex
  59  	numFn int                  // the number of functions currently in cbs.funcs
  60  	funcs [maxCB]reflect.Value // the saved callbacks
  61  }
  62  
  63  func compileCallback(fn any) uintptr {
  64  	val := reflect.ValueOf(fn)
  65  	if val.Kind() != reflect.Func {
  66  		panic("purego: the type must be a function but was not")
  67  	}
  68  	if val.IsNil() {
  69  		panic("purego: function must not be nil")
  70  	}
  71  	ty := val.Type()
  72  	for i := 0; i < ty.NumIn(); i++ {
  73  		in := ty.In(i)
  74  		switch in.Kind() {
  75  		case reflect.Struct:
  76  			if i == 0 && in.AssignableTo(reflect.TypeOf(CDecl{})) {
  77  				continue
  78  			}
  79  			fallthrough
  80  		case reflect.Interface, reflect.Func, reflect.Slice,
  81  			reflect.Chan, reflect.Complex64, reflect.Complex128,
  82  			reflect.String, reflect.Map, reflect.Invalid:
  83  			panic("purego: unsupported argument type: " + in.Kind().String())
  84  		}
  85  	}
  86  output:
  87  	switch {
  88  	case ty.NumOut() == 1:
  89  		switch ty.Out(0).Kind() {
  90  		case reflect.Pointer, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  91  			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
  92  			reflect.Bool, reflect.UnsafePointer:
  93  			break output
  94  		}
  95  		panic("purego: unsupported return type: " + ty.String())
  96  	case ty.NumOut() > 1:
  97  		panic("purego: callbacks can only have one return")
  98  	}
  99  	cbs.lock.Lock()
 100  	defer cbs.lock.Unlock()
 101  	if cbs.numFn >= maxCB {
 102  		panic("purego: the maximum number of callbacks has been reached")
 103  	}
 104  	cbs.funcs[cbs.numFn] = val
 105  	cbs.numFn++
 106  	return callbackasmAddr(cbs.numFn - 1)
 107  }
 108  
 109  const ptrSize = unsafe.Sizeof((*int)(nil))
 110  
 111  const callbackMaxFrame = 64 * ptrSize
 112  
 113  // callbackasm is implemented in zcallback_GOOS_GOARCH.s
 114  //
 115  //go:linkname __callbackasm callbackasm
 116  var __callbackasm byte
 117  var callbackasmABI0 = uintptr(unsafe.Pointer(&__callbackasm))
 118  
 119  // callbackWrap_call allows the calling of the ABIInternal wrapper
 120  // which is required for runtime.cgocallback without the
 121  // <ABIInternal> tag which is only allowed in the runtime.
 122  // This closure is used inside sys_darwin_GOARCH.s
 123  var callbackWrap_call = callbackWrap
 124  
 125  // callbackWrap is called by assembly code which determines which Go function to call.
 126  // This function takes the arguments and passes them to the Go function and returns the result.
 127  func callbackWrap(a *callbackArgs) {
 128  	cbs.lock.Lock()
 129  	fn := cbs.funcs[a.index]
 130  	cbs.lock.Unlock()
 131  	fnType := fn.Type()
 132  	args := make([]reflect.Value, fnType.NumIn())
 133  	frame := (*[callbackMaxFrame]uintptr)(a.args)
 134  	// stackFrame points to stack-passed arguments. On most architectures this is
 135  	// contiguous with frame (after register args), but on ppc64le it's separate.
 136  	var stackFrame *[callbackMaxFrame]uintptr
 137  	if sf := a.stackFrame(); sf != nil {
 138  		// Only ppc64le uses separate stackArgs pointer due to NOSPLIT constraints
 139  		stackFrame = (*[callbackMaxFrame]uintptr)(sf)
 140  	}
 141  	// floatsN and intsN track the number of register slots used, not argument count.
 142  	// This distinction matters on ARM32 where float64 uses 2 slots (32-bit registers).
 143  	var floatsN int
 144  	var intsN int
 145  	// stackSlot points to the index into frame (or stackFrame) of the current stack element.
 146  	// When stackFrame is nil, stack begins after float and integer registers in frame.
 147  	// When stackFrame is not nil (ppc64le), stackSlot indexes into stackFrame starting at 0.
 148  	stackSlot := numOfIntegerRegisters() + numOfFloatRegisters()
 149  	if stackFrame != nil {
 150  		// ppc64le: stackArgs is a separate pointer, indices start at 0
 151  		stackSlot = 0
 152  	}
 153  	// stackByteOffset tracks the byte offset within the stack area for Darwin ARM64
 154  	// tight packing. On Darwin ARM64, C passes small types packed on the stack.
 155  	stackByteOffset := uintptr(0)
 156  	for i := range args {
 157  		// slots is the number of pointer-sized slots the argument takes
 158  		var slots int
 159  		inType := fnType.In(i)
 160  		switch inType.Kind() {
 161  		case reflect.Float32, reflect.Float64:
 162  			slots = int((fnType.In(i).Size() + ptrSize - 1) / ptrSize)
 163  			if floatsN+slots > numOfFloatRegisters() {
 164  				if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
 165  					// Darwin ARM64: read from packed stack with proper alignment
 166  					args[i] = callbackArgFromStack(a.args, stackSlot, &stackByteOffset, inType)
 167  				} else if stackFrame != nil {
 168  					// ppc64le/s390x: stack args are in separate stackFrame
 169  					if runtime.GOARCH == "s390x" {
 170  						// s390x big-endian: sub-8-byte values are right-justified
 171  						args[i] = callbackArgFromSlotBigEndian(unsafe.Pointer(&stackFrame[stackSlot]), inType)
 172  					} else {
 173  						args[i] = reflect.NewAt(inType, unsafe.Pointer(&stackFrame[stackSlot])).Elem()
 174  					}
 175  					stackSlot += slots
 176  				} else {
 177  					args[i] = reflect.NewAt(inType, unsafe.Pointer(&frame[stackSlot])).Elem()
 178  					stackSlot += slots
 179  				}
 180  			} else {
 181  				if runtime.GOARCH == "s390x" {
 182  					// s390x big-endian: float32 is right-justified in 8-byte FPR slot
 183  					args[i] = callbackArgFromSlotBigEndian(unsafe.Pointer(&frame[floatsN]), inType)
 184  				} else {
 185  					args[i] = reflect.NewAt(inType, unsafe.Pointer(&frame[floatsN])).Elem()
 186  				}
 187  			}
 188  			floatsN += slots
 189  		case reflect.Struct:
 190  			// This is the CDecl field
 191  			args[i] = reflect.Zero(inType)
 192  		default:
 193  			slots = int((inType.Size() + ptrSize - 1) / ptrSize)
 194  			if intsN+slots > numOfIntegerRegisters() {
 195  				if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
 196  					// Darwin ARM64: read from packed stack with proper alignment
 197  					args[i] = callbackArgFromStack(a.args, stackSlot, &stackByteOffset, inType)
 198  				} else if stackFrame != nil {
 199  					// ppc64le/s390x: stack args are in separate stackFrame
 200  					if runtime.GOARCH == "s390x" {
 201  						// s390x big-endian: sub-8-byte values are right-justified
 202  						args[i] = callbackArgFromSlotBigEndian(unsafe.Pointer(&stackFrame[stackSlot]), inType)
 203  					} else {
 204  						args[i] = reflect.NewAt(inType, unsafe.Pointer(&stackFrame[stackSlot])).Elem()
 205  					}
 206  					stackSlot += slots
 207  				} else {
 208  					args[i] = reflect.NewAt(inType, unsafe.Pointer(&frame[stackSlot])).Elem()
 209  					stackSlot += slots
 210  				}
 211  			} else {
 212  				// the integers begin after the floats in frame
 213  				pos := intsN + numOfFloatRegisters()
 214  				if runtime.GOARCH == "s390x" {
 215  					// s390x big-endian: sub-8-byte values are right-justified in GPR slot
 216  					args[i] = callbackArgFromSlotBigEndian(unsafe.Pointer(&frame[pos]), inType)
 217  				} else {
 218  					args[i] = reflect.NewAt(inType, unsafe.Pointer(&frame[pos])).Elem()
 219  				}
 220  			}
 221  			intsN += slots
 222  		}
 223  	}
 224  	ret := fn.Call(args)
 225  	if len(ret) > 0 {
 226  		switch k := ret[0].Kind(); k {
 227  		case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uintptr:
 228  			a.result = uintptr(ret[0].Uint())
 229  		case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
 230  			a.result = uintptr(ret[0].Int())
 231  		case reflect.Bool:
 232  			if ret[0].Bool() {
 233  				a.result = 1
 234  			} else {
 235  				a.result = 0
 236  			}
 237  		case reflect.Pointer:
 238  			a.result = ret[0].Pointer()
 239  		case reflect.UnsafePointer:
 240  			a.result = ret[0].Pointer()
 241  		default:
 242  			panic("purego: unsupported kind: " + k.String())
 243  		}
 244  	}
 245  }
 246  
 247  // callbackArgFromStack reads an argument from the tightly-packed stack area on Darwin ARM64.
 248  // The C ABI on Darwin ARM64 packs small types on the stack without padding to 8 bytes.
 249  // This function handles proper alignment and advances stackByteOffset accordingly.
 250  func callbackArgFromStack(argsBase unsafe.Pointer, stackSlot int, stackByteOffset *uintptr, inType reflect.Type) reflect.Value {
 251  	// Calculate base address of stack area (after float and int registers)
 252  	stackBase := unsafe.Add(argsBase, stackSlot*int(ptrSize))
 253  
 254  	// Get type's natural alignment
 255  	align := uintptr(inType.Align())
 256  	size := inType.Size()
 257  
 258  	// Align the offset
 259  	if *stackByteOffset%align != 0 {
 260  		*stackByteOffset = (*stackByteOffset + align - 1) &^ (align - 1)
 261  	}
 262  
 263  	// Read value at aligned offset
 264  	ptr := unsafe.Add(stackBase, *stackByteOffset)
 265  	*stackByteOffset += size
 266  
 267  	return reflect.NewAt(inType, ptr).Elem()
 268  }
 269  
 270  // callbackArgFromSlotBigEndian reads an argument from an 8-byte slot on big-endian architectures.
 271  // On s390x:
 272  // - Integer types are right-justified in GPRs: sub-8-byte values are at offset (8 - size)
 273  // - Float32 in FPRs is left-justified: stored in upper 32 bits, so at offset 0
 274  // - Float64 occupies the full 8-byte slot
 275  func callbackArgFromSlotBigEndian(slotPtr unsafe.Pointer, inType reflect.Type) reflect.Value {
 276  	size := inType.Size()
 277  	if size >= 8 {
 278  		// 8-byte values occupy the entire slot
 279  		return reflect.NewAt(inType, slotPtr).Elem()
 280  	}
 281  	// Float32 is left-justified in FPRs (upper 32 bits), so offset is 0
 282  	if inType.Kind() == reflect.Float32 {
 283  		return reflect.NewAt(inType, slotPtr).Elem()
 284  	}
 285  	// Integer types are right-justified: offset = 8 - size
 286  	offset := 8 - size
 287  	ptr := unsafe.Add(slotPtr, offset)
 288  	return reflect.NewAt(inType, ptr).Elem()
 289  }
 290  
 291  // callbackasmAddr returns address of runtime.callbackasm
 292  // function adjusted by i.
 293  // On x86 and amd64, runtime.callbackasm is a series of CALL instructions,
 294  // and we want callback to arrive at
 295  // correspondent call instruction instead of start of
 296  // runtime.callbackasm.
 297  // On ARM, runtime.callbackasm is a series of mov and branch instructions.
 298  // R12 is loaded with the callback index. Each entry is two instructions,
 299  // hence 8 bytes.
 300  func callbackasmAddr(i int) uintptr {
 301  	var entrySize int
 302  	switch runtime.GOARCH {
 303  	default:
 304  		panic("purego: unsupported architecture")
 305  	case "amd64":
 306  		// On amd64, each callback entry is just a CALL instruction (5 bytes)
 307  		entrySize = 5
 308  	case "386":
 309  		// On 386, each callback entry is MOVL $imm, CX (5 bytes) + JMP (5 bytes)
 310  		entrySize = 10
 311  	case "arm", "arm64", "loong64", "ppc64le", "riscv64":
 312  		// On ARM, ARM64, Loong64, PPC64LE and RISCV64, each entry is a MOV instruction
 313  		// followed by a branch instruction
 314  		entrySize = 8
 315  	case "s390x":
 316  		// On S390X, each entry is LGHI (4 bytes) + JG (6 bytes)
 317  		entrySize = 10
 318  	}
 319  	return callbackasmABI0 + uintptr(i*entrySize)
 320  }
 321