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