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