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 // Copy syscall.a1 into a local variable to prevent v
350 // from holding a pointer to the pooled syscallArgs field.
351 a1 := syscall.a1
352 v = reflect.NewAt(outType, unsafe.Pointer(&a1)).Elem()
353 case reflect.Func:
354 // wrap this C function in a nicely typed Go function
355 v = reflect.New(outType)
356 RegisterFunc(v.Interface(), syscall.a1)
357 case reflect.String:
358 v.SetString(strings.GoString(syscall.a1))
359 case reflect.Float32:
360 // NOTE: syscall.r2 is only the floating return value on 64bit platforms.
361 // On 32bit platforms syscall.r2 is the upper part of a 64bit return.
362 // On 386, x87 FPU returns floats as float64 in ST(0), so we read as float64 and convert.
363 // On PPC64LE, C ABI converts float32 to double in FPR, so we read as float64.
364 // On S390X (big-endian), float32 is in upper 32 bits of the 64-bit FP register.
365 switch runtime.GOARCH {
366 case "386":
367 v.SetFloat(math.Float64frombits(uint64(syscall.f1) | (uint64(syscall.f2) << 32)))
368 case "ppc64le":
369 v.SetFloat(math.Float64frombits(uint64(syscall.f1)))
370 case "s390x":
371 // S390X is big-endian: float32 in upper 32 bits of 64-bit register
372 v.SetFloat(float64(math.Float32frombits(uint32(syscall.f1 >> 32))))
373 default:
374 v.SetFloat(float64(math.Float32frombits(uint32(syscall.f1))))
375 }
376 case reflect.Float64:
377 // NOTE: syscall.r2 is only the floating return value on 64bit platforms.
378 // On 32bit platforms syscall.r2 is the upper part of a 64bit return.
379 if is32bit {
380 v.SetFloat(math.Float64frombits(uint64(syscall.f1) | (uint64(syscall.f2) << 32)))
381 } else {
382 v.SetFloat(math.Float64frombits(uint64(syscall.f1)))
383 }
384 case reflect.Struct:
385 v = getStruct(outType, *syscall)
386 default:
387 panic("purego: unsupported return kind: " + outType.Kind().String())
388 }
389 if len(args) > 0 {
390 // reuse args slice instead of allocating one when possible
391 args[0] = v
392 return args[:1]
393 } else {
394 return []reflect.Value{v}
395 }
396 })
397 fn.Set(v)
398}
399
400func 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 {
401 const is32bit = unsafe.Sizeof(uintptr(0)) == 4
402 switch v.Kind() {
403 case reflect.String:
404 ptr := strings.CString(v.String())
405 keepAlive = append(keepAlive, ptr)
406 addInt(uintptr(unsafe.Pointer(ptr)))
407 case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
408 addInt(uintptr(v.Uint()))
409 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
410 addInt(uintptr(v.Int()))
411 case reflect.Pointer, reflect.UnsafePointer, reflect.Slice:
412 // There is no need to keepAlive this pointer separately because it is kept alive in the args variable
413 addInt(v.Pointer())
414 case reflect.Func:
415 addInt(NewCallback(v.Interface()))
416 case reflect.Bool:
417 if v.Bool() {
418 addInt(1)
419 } else {
420 addInt(0)
421 }
422 case reflect.Float32:
423 // On S390X big-endian, float32 goes in upper 32 bits of 64-bit FP register
424 if runtime.GOARCH == "s390x" {
425 addFloat(uintptr(math.Float32bits(float32(v.Float()))) << 32)
426 } else {
427 addFloat(uintptr(math.Float32bits(float32(v.Float()))))
428 }
429 case reflect.Float64:
430 if is32bit {
431 bits := math.Float64bits(v.Float())
432 addFloat(uintptr(bits))
433 addFloat(uintptr(bits >> 32))
434 } else {
435 addFloat(uintptr(math.Float64bits(v.Float())))
436 }
437 case reflect.Struct:
438 keepAlive = addStruct(v, numInts, numFloats, numStack, addInt, addFloat, addStack, keepAlive)
439 default:
440 panic("purego: unsupported kind: " + v.Kind().String())
441 }
442 return keepAlive
443}
444
445// maxRegAllocStructSize is the biggest a struct can be while still fitting in registers.
446// if it is bigger than this than enough space must be allocated on the heap and then passed into
447// the function as the first parameter on amd64 or in R8 on arm64.
448//
449// If you change this make sure to update it in objc_runtime_darwin.go
450const maxRegAllocStructSize = 16
451
452func isAllSameFloat(ty reflect.Type) (allFloats bool, numFields int) {
453 allFloats = true
454 root := ty.Field(0).Type
455 for root.Kind() == reflect.Struct {
456 root = root.Field(0).Type
457 }
458 first := root.Kind()
459 if first != reflect.Float32 && first != reflect.Float64 {
460 allFloats = false
461 }
462 for i := 0; i < ty.NumField(); i++ {
463 f := ty.Field(i).Type
464 if f.Kind() == reflect.Struct {
465 var structNumFields int
466 allFloats, structNumFields = isAllSameFloat(f)
467 numFields += structNumFields
468 continue
469 }
470 numFields++
471 if f.Kind() != first {
472 allFloats = false
473 }
474 }
475 return allFloats, numFields
476}
477
478func checkStructFieldsSupported(ty reflect.Type) {
479 for i := 0; i < ty.NumField(); i++ {
480 f := ty.Field(i).Type
481 if f.Kind() == reflect.Array {
482 f = f.Elem()
483 } else if f.Kind() == reflect.Struct {
484 checkStructFieldsSupported(f)
485 continue
486 }
487 switch f.Kind() {
488 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
489 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
490 reflect.Uintptr, reflect.Pointer, reflect.UnsafePointer, reflect.Float64, reflect.Float32,
491 reflect.Bool:
492 default:
493 panic(fmt.Sprintf("purego: struct field type %s is not supported", f))
494 }
495 }
496}
497
498func ensureStructSupported() {
499 if runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64" {
500 panic("purego: struct arguments/returns are only supported on amd64 and arm64")
501 }
502 if runtime.GOOS != "darwin" && runtime.GOOS != "linux" {
503 panic("purego: struct arguments/returns are only supported on darwin and linux")
504 }
505}
506
507func roundUpTo8(val uintptr) uintptr {
508 return (val + align8ByteMask) &^ align8ByteMask
509}
510
511func numOfFloatRegisters() int {
512 switch runtime.GOARCH {
513 case "amd64", "arm64", "loong64", "ppc64le", "riscv64":
514 return 8
515 case "s390x":
516 return 4
517 case "arm":
518 return 16
519 case "386":
520 // i386 SysV ABI passes all arguments on the stack, including floats
521 return 0
522 default:
523 // since this platform isn't supported and can therefore only access
524 // integer registers it is safest to return 8
525 return 8
526 }
527}
528
529func numOfIntegerRegisters() int {
530 switch runtime.GOARCH {
531 case "arm64", "loong64", "ppc64le", "riscv64":
532 return 8
533 case "amd64":
534 return 6
535 case "s390x":
536 // S390X uses R2-R6 for integer arguments
537 return 5
538 case "arm":
539 return 4
540 case "386":
541 // i386 SysV ABI passes all arguments on the stack
542 return 0
543 default:
544 // since this platform isn't supported and can therefore only access
545 // integer registers it is fine to return the maxArgs
546 return maxArgs
547 }
548}
549
550// estimateStackBytes estimates stack bytes needed for Darwin ARM64 validation.
551// This is a conservative estimate used only for early error detection.
552func estimateStackBytes(ty reflect.Type) int {
553 var numInts, numFloats int
554 var stackBytes int
555
556 for i := 0; i < ty.NumIn(); i++ {
557 arg := ty.In(i)
558 size := int(arg.Size())
559
560 // Check if this goes to register or stack
561 usesInt := arg.Kind() != reflect.Float32 && arg.Kind() != reflect.Float64
562 if usesInt && numInts < numOfIntegerRegisters() {
563 numInts++
564 } else if !usesInt && numFloats < numOfFloatRegisters() {
565 numFloats++
566 } else {
567 // Goes to stack - accumulate total bytes
568 stackBytes += size
569 }
570 }
571 // Round total to 8-byte boundary
572 if stackBytes > 0 && stackBytes%align8ByteSize != 0 {
573 stackBytes = int(roundUpTo8(uintptr(stackBytes)))
574 }
575 return stackBytes
576}