syscall_sysv.go 12 KB

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