1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2022 The Ebitengine Authors
3
4//go:build darwin || freebsd || linux || netbsd || windows
5
6package purego
7
8import (
9 "fmt"
10 "math"
11 "reflect"
12 "runtime"
13 "unsafe"
14
15 "github.com/ebitengine/purego/internal/strings"
16 "github.com/ebitengine/purego/internal/xreflect"
17)
18
19const (
20 align8ByteMask = 7 // Mask for 8-byte alignment: (val + 7) &^ 7
21 align8ByteSize = 8 // 8-byte alignment boundary
22)
23
24// RegisterLibFunc is a wrapper around RegisterFunc that uses the C function returned from Dlsym(handle, name).
25// It panics if it can't find the name symbol.
26func RegisterLibFunc(fptr any, handle uintptr, name string) {
27 sym, err := loadSymbol(handle, name)
28 if err != nil {
29 panic(err)
30 }
31 RegisterFunc(fptr, sym)
32}
33
34// RegisterFunc takes a pointer to a Go function representing the calling convention of the C function.
35// fptr will be set to a function that when called will call the C function given by cfn with the
36// parameters passed in the correct registers and stack.
37//
38// A panic is produced if the type is not a function pointer or if the function returns more than 1 value.
39//
40// These conversions describe how a Go type in the fptr will be used to call
41// the C function. It is important to note that there is no way to verify that fptr
42// matches the C function. This also holds true for struct types where the padding
43// needs to be ensured to match that of C; RegisterFunc does not verify this.
44//
45// # Type Conversions (Go <=> C)
46//
47// string <=> char*
48// bool <=> _Bool
49// uintptr <=> uintptr_t
50// uint <=> uint32_t or uint64_t
51// uint8 <=> uint8_t
52// uint16 <=> uint16_t
53// uint32 <=> uint32_t
54// uint64 <=> uint64_t
55// int <=> int32_t or int64_t
56// int8 <=> int8_t
57// int16 <=> int16_t
58// int32 <=> int32_t
59// int64 <=> int64_t
60// float32 <=> float
61// float64 <=> double
62// struct <=> struct (darwin amd64/arm64, linux amd64/arm64)
63// func <=> C function
64// unsafe.Pointer, *T <=> void*
65// []T => void*
66//
67// There is a special case when the last argument of fptr is a variadic interface (or []interface}
68// it will be expanded into a call to the C function as if it had the arguments in that slice.
69// This means that using arg ...any is like a cast to the function with the arguments inside arg.
70// This is not the same as C variadic.
71//
72// # Memory
73//
74// In general it is not possible for purego to guarantee the lifetimes of objects returned or received from
75// calling functions using RegisterFunc. For arguments to a C function it is important that the C function doesn't
76// hold onto a reference to Go memory. This is the same as the [Cgo rules].
77//
78// However, there are some special cases. When passing a string as an argument if the string does not end in a null
79// terminated byte (\x00) then the string will be copied into memory maintained by purego. The memory is only valid for
80// that specific call. Therefore, if the C code keeps a reference to that string it may become invalid at some
81// undefined time. However, if the string does already contain a null-terminated byte then no copy is done.
82// It is then the responsibility of the caller to ensure the string stays alive as long as it's needed in C memory.
83// This can be done using runtime.KeepAlive or allocating the string in C memory using malloc. When a C function
84// returns a null-terminated pointer to char a Go string can be used. Purego will allocate a new string in Go memory
85// and copy the data over. This string will be garbage collected whenever Go decides it's no longer referenced.
86// This C created string will not be freed by purego. If the pointer to char is not null-terminated or must continue
87// to point to C memory (because it's a buffer for example) then use a pointer to byte and then convert that to a slice
88// using unsafe.Slice. Doing this means that it becomes the responsibility of the caller to care about the lifetime
89// of the pointer
90//
91// # Structs
92//
93// Purego can handle the most common structs that have fields of builtin types like int8, uint16, float32, etc. However,
94// it does not support aligning fields properly. It is therefore the responsibility of the caller to ensure
95// that all padding is added to the Go struct to match the C one. See `BoolStructFn` in struct_test.go for an example.
96//
97// On Darwin ARM64, purego handles proper alignment of struct arguments when passing them on the stack,
98// following the C ABI's byte-level packing rules.
99//
100// # Example
101//
102// All functions below call this C function:
103//
104// char *foo(char *str);
105//
106// // Let purego convert types
107// var foo func(s string) string
108// goString := foo("copied")
109// // Go will garbage collect this string
110//
111// // Manually, handle allocations
112// var foo2 func(b string) *byte
113// mustFree := foo2("not copied\x00")
114// defer free(mustFree)
115//
116// [Cgo rules]: https://pkg.go.dev/cmd/cgo#hdr-Go_references_to_C
117func RegisterFunc(fptr any, cfn uintptr) {
118 const is32bit = unsafe.Sizeof(uintptr(0)) == 4
119 fn := reflect.ValueOf(fptr).Elem()
120 ty := fn.Type()
121 if ty.Kind() != reflect.Func {
122 panic("purego: fptr must be a function pointer")
123 }
124 if ty.NumOut() > 1 {
125 panic("purego: function can only return zero or one values")
126 }
127 if cfn == 0 {
128 panic("purego: cfn is nil")
129 }
130 if ty.NumOut() == 1 && (ty.Out(0).Kind() == reflect.Float32 || ty.Out(0).Kind() == reflect.Float64) &&
131 runtime.GOARCH != "arm" && runtime.GOARCH != "arm64" && runtime.GOARCH != "386" && runtime.GOARCH != "amd64" && runtime.GOARCH != "loong64" && runtime.GOARCH != "ppc64le" && runtime.GOARCH != "riscv64" && runtime.GOARCH != "s390x" {
132 panic("purego: float returns are not supported")
133 }
134 {
135 // this code checks how many registers and stack this function will use
136 // to avoid crashing with too many arguments
137 var ints int
138 var floats int
139 floatArgRegs := numOfFloatRegisters()
140 var stack int
141 for i := 0; i < ty.NumIn(); i++ {
142 arg := ty.In(i)
143 switch arg.Kind() {
144 case reflect.Func:
145 // This only does preliminary testing to ensure the CDecl argument
146 // is the first argument. Full testing is done when the callback is actually
147 // created in NewCallback.
148 for j := 0; j < arg.NumIn(); j++ {
149 in := arg.In(j)
150 if !in.AssignableTo(reflect.TypeOf(CDecl{})) {
151 continue
152 }
153 if j != 0 {
154 panic("purego: CDecl must be the first argument")
155 }
156 }
157 case reflect.String, reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
158 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Pointer, reflect.UnsafePointer,
159 reflect.Slice, reflect.Bool:
160 if ints < numOfIntegerRegisters() {
161 ints++
162 } else {
163 stack++
164 }
165 case reflect.Float32, reflect.Float64:
166 if floats < floatArgRegs {
167 floats++
168 } else {
169 stack++
170 }
171 case reflect.Struct:
172 ensureStructSupported()
173 if arg.Size() == 0 {
174 continue
175 }
176 addInt := func(u uintptr) {
177 ints++
178 }
179 addFloat := func(u uintptr) {
180 floats++
181 }
182 addStack := func(u uintptr) {
183 stack++
184 }
185 _ = addStruct(reflect.New(arg).Elem(), &ints, &floats, &stack, addInt, addFloat, addStack, nil)
186 default:
187 panic("purego: unsupported kind " + arg.Kind().String())
188 }
189 }
190 if ty.NumOut() == 1 && ty.Out(0).Kind() == reflect.Struct {
191 ensureStructSupported()
192 outType := ty.Out(0)
193 checkStructFieldsSupported(outType)
194 if runtime.GOARCH == "amd64" && outType.Size() > maxRegAllocStructSize {
195 // on amd64 if struct is bigger than 16 bytes allocate the return struct
196 // and pass it in as a hidden first argument.
197 ints++
198 }
199 }
200
201 argsLimit := maxArgs
202 sizeOfStack := argsLimit - numOfIntegerRegisters()
203 if runtime.GOOS == "windows" {
204 if ints+floats+stack > argsLimit {
205 panic("purego: too many stack arguments")
206 }
207 } else if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
208 // On Darwin ARM64, use byte-based validation since arguments pack efficiently.
209 // See https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms
210 stackBytes := estimateStackBytes(ty)
211 maxStackBytes := sizeOfStack * 8
212 if stackBytes > maxStackBytes {
213 panic("purego: too many stack arguments")
214 }
215 } else {
216 if stack > sizeOfStack {
217 panic("purego: too many stack arguments")
218 }
219 }
220 }
221
222 v := reflect.MakeFunc(ty, func(args []reflect.Value) (results []reflect.Value) {
223 var sysargs [maxArgs]uintptr
224 // Use maxArgs instead of numOfFloatRegisters() to keep this code path allocation-free,
225 // since numOfFloatRegisters() is a function call, not a constant.
226 // maxArgs is always greater than or equal to numOfFloatRegisters() so this is safe.
227 var floats [maxArgs]uintptr
228 floatArgRegs := numOfFloatRegisters()
229 var numInts int
230 var numFloats int
231 var numStack int
232 var addStack, addInt, addFloat func(x uintptr)
233 if runtime.GOARCH == "arm64" || runtime.GOOS != "windows" {
234 // Windows arm64 uses the same calling convention as macOS and Linux
235 addStack = func(x uintptr) {
236 sysargs[numOfIntegerRegisters()+numStack] = x
237 numStack++
238 }
239 addInt = func(x uintptr) {
240 if numInts >= numOfIntegerRegisters() {
241 addStack(x)
242 } else {
243 sysargs[numInts] = x
244 numInts++
245 }
246 }
247 addFloat = func(x uintptr) {
248 if numFloats < floatArgRegs {
249 floats[numFloats] = x
250 numFloats++
251 } else {
252 addStack(x)
253 }
254 }
255 } else {
256 // On Windows amd64 the arguments are passed in the numbered registered.
257 // So the first int is in the first integer register and the first float
258 // is in the second floating register if there is already a first int.
259 // This is in contrast to how macOS and Linux pass arguments which
260 // tries to use as many registers as possible in the calling convention.
261 addStack = func(x uintptr) {
262 if numStack >= maxArgs {
263 panic("purego: too many stack arguments")
264 }
265 sysargs[numStack] = x
266 numStack++
267 }
268 addInt = addStack
269 addFloat = addStack
270 }
271
272 var keepAlive []any
273 defer func() {
274 runtime.KeepAlive(keepAlive)
275 runtime.KeepAlive(args)
276 }()
277
278 var arm64_r8 uintptr
279 if ty.NumOut() == 1 && ty.Out(0).Kind() == reflect.Struct {
280 outType := ty.Out(0)
281 if (runtime.GOARCH == "amd64" || runtime.GOARCH == "loong64" || runtime.GOARCH == "ppc64le" || runtime.GOARCH == "riscv64" || runtime.GOARCH == "s390x") && outType.Size() > maxRegAllocStructSize {
282 val := reflect.New(outType)
283 keepAlive = append(keepAlive, val)
284 addInt(val.Pointer())
285 } else if runtime.GOARCH == "arm64" && outType.Size() > maxRegAllocStructSize {
286 isAllFloats, numFields := isAllSameFloat(outType)
287 if !isAllFloats || numFields > 4 {
288 val := reflect.New(outType)
289 keepAlive = append(keepAlive, val)
290 arm64_r8 = val.Pointer()
291 }
292 }
293 }
294 for i, v := range args {
295 if variadic, ok := xreflect.TypeAssert[[]any](args[i]); ok {
296 if i != len(args)-1 {
297 panic("purego: can only expand last parameter")
298 }
299 for _, x := range variadic {
300 keepAlive = addValue(reflect.ValueOf(x), keepAlive, addInt, addFloat, addStack, &numInts, &numFloats, &numStack)
301 }
302 continue
303 }
304 // Check if we need to start Darwin ARM64 C-style stack packing
305 if runtime.GOARCH == "arm64" && runtime.GOOS == "darwin" && shouldBundleStackArgs(v, numInts, numFloats) {
306 // Collect and separate remaining args into register vs stack
307 stackArgs, newKeepAlive := collectStackArgs(args, i, numInts, numFloats,
308 keepAlive, addInt, addFloat, addStack, &numInts, &numFloats, &numStack)
309 keepAlive = newKeepAlive
310
311 // Bundle stack arguments with C-style packing
312 bundleStackArgs(stackArgs, addStack)
313 break
314 }
315 keepAlive = addValue(v, keepAlive, addInt, addFloat, addStack, &numInts, &numFloats, &numStack)
316 }
317
318 var syscall *syscallArgs
319 if runtime.GOOS == "windows" && runtime.GOARCH != "arm64" {
320 // Windows amd64, 386, and arm use syscall.SyscallN.
321 syscall = &syscallArgs{}
322 syscall.a1, syscall.a2, _ = syscall_syscallN(cfn, sysargs[:numStack]...)
323 syscall.f1 = syscall.a2 // on amd64 a2 stores the float return. On 32bit platforms floats aren't support
324 } else {
325 syscall = syscall_SyscallN(cfn, sysargs[:], floats[:], arm64_r8)
326 }
327 if ty.NumOut() == 0 {
328 return nil
329 }
330 outType := ty.Out(0)
331 v := reflect.New(outType).Elem()
332 switch outType.Kind() {
333 case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
334 v.SetUint(uint64(syscall.a1))
335 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
336 v.SetInt(int64(syscall.a1))
337 case reflect.Bool:
338 v.SetBool(byte(syscall.a1) != 0)
339 case reflect.UnsafePointer:
340 // We take the address and then dereference it to trick go vet from creating a possible miss-use of unsafe.Pointer
341 v.SetPointer(*(*unsafe.Pointer)(unsafe.Pointer(&syscall.a1)))
342 case reflect.Pointer:
343 v = reflect.NewAt(outType, unsafe.Pointer(&syscall.a1)).Elem()
344 case reflect.Func:
345 // wrap this C function in a nicely typed Go function
346 v = reflect.New(outType)
347 RegisterFunc(v.Interface(), syscall.a1)
348 case reflect.String:
349 v.SetString(strings.GoString(syscall.a1))
350 case reflect.Float32:
351 // NOTE: syscall.r2 is only the floating return value on 64bit platforms.
352 // On 32bit platforms syscall.r2 is the upper part of a 64bit return.
353 // On 386, x87 FPU returns floats as float64 in ST(0), so we read as float64 and convert.
354 // On PPC64LE, C ABI converts float32 to double in FPR, so we read as float64.
355 // On S390X (big-endian), float32 is in upper 32 bits of the 64-bit FP register.
356 switch runtime.GOARCH {
357 case "386":
358 v.SetFloat(math.Float64frombits(uint64(syscall.f1) | (uint64(syscall.f2) << 32)))
359 case "ppc64le":
360 v.SetFloat(math.Float64frombits(uint64(syscall.f1)))
361 case "s390x":
362 // S390X is big-endian: float32 in upper 32 bits of 64-bit register
363 v.SetFloat(float64(math.Float32frombits(uint32(syscall.f1 >> 32))))
364 default:
365 v.SetFloat(float64(math.Float32frombits(uint32(syscall.f1))))
366 }
367 case reflect.Float64:
368 // NOTE: syscall.r2 is only the floating return value on 64bit platforms.
369 // On 32bit platforms syscall.r2 is the upper part of a 64bit return.
370 if is32bit {
371 v.SetFloat(math.Float64frombits(uint64(syscall.f1) | (uint64(syscall.f2) << 32)))
372 } else {
373 v.SetFloat(math.Float64frombits(uint64(syscall.f1)))
374 }
375 case reflect.Struct:
376 v = getStruct(outType, *syscall)
377 default:
378 panic("purego: unsupported return kind: " + outType.Kind().String())
379 }
380 if len(args) > 0 {
381 // reuse args slice instead of allocating one when possible
382 args[0] = v
383 return args[:1]
384 } else {
385 return []reflect.Value{v}
386 }
387 })
388 fn.Set(v)
389}
390
391func addValue(v reflect.Value, keepAlive []any, addInt func(x uintptr), addFloat func(x uintptr), addStack func(x uintptr), numInts *int, numFloats *int, numStack *int) []any {
392 const is32bit = unsafe.Sizeof(uintptr(0)) == 4
393 switch v.Kind() {
394 case reflect.String:
395 ptr := strings.CString(v.String())
396 keepAlive = append(keepAlive, ptr)
397 addInt(uintptr(unsafe.Pointer(ptr)))
398 case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
399 addInt(uintptr(v.Uint()))
400 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
401 addInt(uintptr(v.Int()))
402 case reflect.Pointer, reflect.UnsafePointer, reflect.Slice:
403 // There is no need to keepAlive this pointer separately because it is kept alive in the args variable
404 addInt(v.Pointer())
405 case reflect.Func:
406 addInt(NewCallback(v.Interface()))
407 case reflect.Bool:
408 if v.Bool() {
409 addInt(1)
410 } else {
411 addInt(0)
412 }
413 case reflect.Float32:
414 // On S390X big-endian, float32 goes in upper 32 bits of 64-bit FP register
415 if runtime.GOARCH == "s390x" {
416 addFloat(uintptr(math.Float32bits(float32(v.Float()))) << 32)
417 } else {
418 addFloat(uintptr(math.Float32bits(float32(v.Float()))))
419 }
420 case reflect.Float64:
421 if is32bit {
422 bits := math.Float64bits(v.Float())
423 addFloat(uintptr(bits))
424 addFloat(uintptr(bits >> 32))
425 } else {
426 addFloat(uintptr(math.Float64bits(v.Float())))
427 }
428 case reflect.Struct:
429 keepAlive = addStruct(v, numInts, numFloats, numStack, addInt, addFloat, addStack, keepAlive)
430 default:
431 panic("purego: unsupported kind: " + v.Kind().String())
432 }
433 return keepAlive
434}
435
436// maxRegAllocStructSize is the biggest a struct can be while still fitting in registers.
437// if it is bigger than this than enough space must be allocated on the heap and then passed into
438// the function as the first parameter on amd64 or in R8 on arm64.
439//
440// If you change this make sure to update it in objc_runtime_darwin.go
441const maxRegAllocStructSize = 16
442
443func isAllSameFloat(ty reflect.Type) (allFloats bool, numFields int) {
444 allFloats = true
445 root := ty.Field(0).Type
446 for root.Kind() == reflect.Struct {
447 root = root.Field(0).Type
448 }
449 first := root.Kind()
450 if first != reflect.Float32 && first != reflect.Float64 {
451 allFloats = false
452 }
453 for i := 0; i < ty.NumField(); i++ {
454 f := ty.Field(i).Type
455 if f.Kind() == reflect.Struct {
456 var structNumFields int
457 allFloats, structNumFields = isAllSameFloat(f)
458 numFields += structNumFields
459 continue
460 }
461 numFields++
462 if f.Kind() != first {
463 allFloats = false
464 }
465 }
466 return allFloats, numFields
467}
468
469func checkStructFieldsSupported(ty reflect.Type) {
470 for i := 0; i < ty.NumField(); i++ {
471 f := ty.Field(i).Type
472 if f.Kind() == reflect.Array {
473 f = f.Elem()
474 } else if f.Kind() == reflect.Struct {
475 checkStructFieldsSupported(f)
476 continue
477 }
478 switch f.Kind() {
479 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
480 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
481 reflect.Uintptr, reflect.Pointer, reflect.UnsafePointer, reflect.Float64, reflect.Float32,
482 reflect.Bool:
483 default:
484 panic(fmt.Sprintf("purego: struct field type %s is not supported", f))
485 }
486 }
487}
488
489func ensureStructSupported() {
490 if runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64" {
491 panic("purego: struct arguments/returns are only supported on amd64 and arm64")
492 }
493 if runtime.GOOS != "darwin" && runtime.GOOS != "linux" {
494 panic("purego: struct arguments/returns are only supported on darwin and linux")
495 }
496}
497
498func roundUpTo8(val uintptr) uintptr {
499 return (val + align8ByteMask) &^ align8ByteMask
500}
501
502func numOfFloatRegisters() int {
503 switch runtime.GOARCH {
504 case "amd64", "arm64", "loong64", "ppc64le", "riscv64":
505 return 8
506 case "s390x":
507 return 4
508 case "arm":
509 return 16
510 case "386":
511 // i386 SysV ABI passes all arguments on the stack, including floats
512 return 0
513 default:
514 // since this platform isn't supported and can therefore only access
515 // integer registers it is safest to return 8
516 return 8
517 }
518}
519
520func numOfIntegerRegisters() int {
521 switch runtime.GOARCH {
522 case "arm64", "loong64", "ppc64le", "riscv64":
523 return 8
524 case "amd64":
525 return 6
526 case "s390x":
527 // S390X uses R2-R6 for integer arguments
528 return 5
529 case "arm":
530 return 4
531 case "386":
532 // i386 SysV ABI passes all arguments on the stack
533 return 0
534 default:
535 // since this platform isn't supported and can therefore only access
536 // integer registers it is fine to return the maxArgs
537 return maxArgs
538 }
539}
540
541// estimateStackBytes estimates stack bytes needed for Darwin ARM64 validation.
542// This is a conservative estimate used only for early error detection.
543func estimateStackBytes(ty reflect.Type) int {
544 var numInts, numFloats int
545 var stackBytes int
546
547 for i := 0; i < ty.NumIn(); i++ {
548 arg := ty.In(i)
549 size := int(arg.Size())
550
551 // Check if this goes to register or stack
552 usesInt := arg.Kind() != reflect.Float32 && arg.Kind() != reflect.Float64
553 if usesInt && numInts < numOfIntegerRegisters() {
554 numInts++
555 } else if !usesInt && numFloats < numOfFloatRegisters() {
556 numFloats++
557 } else {
558 // Goes to stack - accumulate total bytes
559 stackBytes += size
560 }
561 }
562 // Round total to 8-byte boundary
563 if stackBytes > 0 && stackBytes%align8ByteSize != 0 {
564 stackBytes = int(roundUpTo8(uintptr(stackBytes)))
565 }
566 return stackBytes
567}