1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2022 The Ebitengine Authors
3
4//go:build darwin || freebsd || linux || 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)
17
18// RegisterLibFunc is a wrapper around RegisterFunc that uses the C function returned from Dlsym(handle, name).
19// It panics if it can't find the name symbol.
20func RegisterLibFunc(fptr interface{}, handle uintptr, name string) {
21 sym, err := loadSymbol(handle, name)
22 if err != nil {
23 panic(err)
24 }
25 RegisterFunc(fptr, sym)
26}
27
28// RegisterFunc takes a pointer to a Go function representing the calling convention of the C function.
29// fptr will be set to a function that when called will call the C function given by cfn with the
30// parameters passed in the correct registers and stack.
31//
32// A panic is produced if the type is not a function pointer or if the function returns more than 1 value.
33//
34// These conversions describe how a Go type in the fptr will be used to call
35// the C function. It is important to note that there is no way to verify that fptr
36// matches the C function. This also holds true for struct types where the padding
37// needs to be ensured to match that of C; RegisterFunc does not verify this.
38//
39// # Type Conversions (Go <=> C)
40//
41// string <=> char*
42// bool <=> _Bool
43// uintptr <=> uintptr_t
44// uint <=> uint32_t or uint64_t
45// uint8 <=> uint8_t
46// uint16 <=> uint16_t
47// uint32 <=> uint32_t
48// uint64 <=> uint64_t
49// int <=> int32_t or int64_t
50// int8 <=> int8_t
51// int16 <=> int16_t
52// int32 <=> int32_t
53// int64 <=> int64_t
54// float32 <=> float
55// float64 <=> double
56// struct <=> struct (WIP - darwin only)
57// func <=> C function
58// unsafe.Pointer, *T <=> void*
59// []T => void*
60//
61// There is a special case when the last argument of fptr is a variadic interface (or []interface}
62// it will be expanded into a call to the C function as if it had the arguments in that slice.
63// This means that using arg ...interface{} is like a cast to the function with the arguments inside arg.
64// This is not the same as C variadic.
65//
66// # Memory
67//
68// In general it is not possible for purego to guarantee the lifetimes of objects returned or received from
69// calling functions using RegisterFunc. For arguments to a C function it is important that the C function doesn't
70// hold onto a reference to Go memory. This is the same as the [Cgo rules].
71//
72// However, there are some special cases. When passing a string as an argument if the string does not end in a null
73// terminated byte (\x00) then the string will be copied into memory maintained by purego. The memory is only valid for
74// that specific call. Therefore, if the C code keeps a reference to that string it may become invalid at some
75// undefined time. However, if the string does already contain a null-terminated byte then no copy is done.
76// It is then the responsibility of the caller to ensure the string stays alive as long as it's needed in C memory.
77// This can be done using runtime.KeepAlive or allocating the string in C memory using malloc. When a C function
78// returns a null-terminated pointer to char a Go string can be used. Purego will allocate a new string in Go memory
79// and copy the data over. This string will be garbage collected whenever Go decides it's no longer referenced.
80// This C created string will not be freed by purego. If the pointer to char is not null-terminated or must continue
81// 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
82// using unsafe.Slice. Doing this means that it becomes the responsibility of the caller to care about the lifetime
83// of the pointer
84//
85// # Structs
86//
87// Purego can handle the most common structs that have fields of builtin types like int8, uint16, float32, etc. However,
88// it does not support aligning fields properly. It is therefore the responsibility of the caller to ensure
89// that all padding is added to the Go struct to match the C one. See `BoolStructFn` in struct_test.go for an example.
90//
91// # Example
92//
93// All functions below call this C function:
94//
95// char *foo(char *str);
96//
97// // Let purego convert types
98// var foo func(s string) string
99// goString := foo("copied")
100// // Go will garbage collect this string
101//
102// // Manually, handle allocations
103// var foo2 func(b string) *byte
104// mustFree := foo2("not copied\x00")
105// defer free(mustFree)
106//
107// [Cgo rules]: https://pkg.go.dev/cmd/cgo#hdr-Go_references_to_C
108func RegisterFunc(fptr interface{}, cfn uintptr) {
109 fn := reflect.ValueOf(fptr).Elem()
110 ty := fn.Type()
111 if ty.Kind() != reflect.Func {
112 panic("purego: fptr must be a function pointer")
113 }
114 if ty.NumOut() > 1 {
115 panic("purego: function can only return zero or one values")
116 }
117 if cfn == 0 {
118 panic("purego: cfn is nil")
119 }
120 if ty.NumOut() == 1 && (ty.Out(0).Kind() == reflect.Float32 || ty.Out(0).Kind() == reflect.Float64) &&
121 runtime.GOARCH != "arm64" && runtime.GOARCH != "amd64" {
122 panic("purego: float returns are not supported")
123 }
124 {
125 // this code checks how many registers and stack this function will use
126 // to avoid crashing with too many arguments
127 var ints int
128 var floats int
129 var stack int
130 for i := 0; i < ty.NumIn(); i++ {
131 arg := ty.In(i)
132 switch arg.Kind() {
133 case reflect.Func:
134 // This only does preliminary testing to ensure the CDecl argument
135 // is the first argument. Full testing is done when the callback is actually
136 // created in NewCallback.
137 for j := 0; j < arg.NumIn(); j++ {
138 in := arg.In(j)
139 if !in.AssignableTo(reflect.TypeOf(CDecl{})) {
140 continue
141 }
142 if j != 0 {
143 panic("purego: CDecl must be the first argument")
144 }
145 }
146 case reflect.String, reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
147 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Ptr, reflect.UnsafePointer,
148 reflect.Slice, reflect.Bool:
149 if ints < numOfIntegerRegisters() {
150 ints++
151 } else {
152 stack++
153 }
154 case reflect.Float32, reflect.Float64:
155 const is32bit = unsafe.Sizeof(uintptr(0)) == 4
156 if is32bit {
157 panic("purego: floats only supported on 64bit platforms")
158 }
159 if floats < numOfFloats {
160 floats++
161 } else {
162 stack++
163 }
164 case reflect.Struct:
165 if runtime.GOOS != "darwin" || (runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64") {
166 panic("purego: struct arguments are only supported on darwin amd64 & arm64")
167 }
168 if arg.Size() == 0 {
169 continue
170 }
171 addInt := func(u uintptr) {
172 ints++
173 }
174 addFloat := func(u uintptr) {
175 floats++
176 }
177 addStack := func(u uintptr) {
178 stack++
179 }
180 _ = addStruct(reflect.New(arg).Elem(), &ints, &floats, &stack, addInt, addFloat, addStack, nil)
181 default:
182 panic("purego: unsupported kind " + arg.Kind().String())
183 }
184 }
185 if ty.NumOut() == 1 && ty.Out(0).Kind() == reflect.Struct {
186 if runtime.GOOS != "darwin" {
187 panic("purego: struct return values only supported on darwin arm64 & amd64")
188 }
189 outType := ty.Out(0)
190 checkStructFieldsSupported(outType)
191 if runtime.GOARCH == "amd64" && outType.Size() > maxRegAllocStructSize {
192 // on amd64 if struct is bigger than 16 bytes allocate the return struct
193 // and pass it in as a hidden first argument.
194 ints++
195 }
196 }
197 sizeOfStack := maxArgs - numOfIntegerRegisters()
198 if stack > sizeOfStack {
199 panic("purego: too many arguments")
200 }
201 }
202 v := reflect.MakeFunc(ty, func(args []reflect.Value) (results []reflect.Value) {
203 if len(args) > 0 {
204 if variadic, ok := args[len(args)-1].Interface().([]interface{}); ok {
205 // subtract one from args bc the last argument in args is []interface{}
206 // which we are currently expanding
207 tmp := make([]reflect.Value, len(args)-1+len(variadic))
208 n := copy(tmp, args[:len(args)-1])
209 for i, v := range variadic {
210 tmp[n+i] = reflect.ValueOf(v)
211 }
212 args = tmp
213 }
214 }
215 var sysargs [maxArgs]uintptr
216 stack := sysargs[numOfIntegerRegisters():]
217 var floats [numOfFloats]uintptr
218 var numInts int
219 var numFloats int
220 var numStack int
221 var addStack, addInt, addFloat func(x uintptr)
222 if runtime.GOARCH == "arm64" || runtime.GOOS != "windows" {
223 // Windows arm64 uses the same calling convention as macOS and Linux
224 addStack = func(x uintptr) {
225 stack[numStack] = x
226 numStack++
227 }
228 addInt = func(x uintptr) {
229 if numInts >= numOfIntegerRegisters() {
230 addStack(x)
231 } else {
232 sysargs[numInts] = x
233 numInts++
234 }
235 }
236 addFloat = func(x uintptr) {
237 if numFloats < len(floats) {
238 floats[numFloats] = x
239 numFloats++
240 } else {
241 addStack(x)
242 }
243 }
244 } else {
245 // On Windows amd64 the arguments are passed in the numbered registered.
246 // So the first int is in the first integer register and the first float
247 // is in the second floating register if there is already a first int.
248 // This is in contrast to how macOS and Linux pass arguments which
249 // tries to use as many registers as possible in the calling convention.
250 addStack = func(x uintptr) {
251 sysargs[numStack] = x
252 numStack++
253 }
254 addInt = addStack
255 addFloat = addStack
256 }
257
258 var keepAlive []interface{}
259 defer func() {
260 runtime.KeepAlive(keepAlive)
261 runtime.KeepAlive(args)
262 }()
263 var syscall syscall15Args
264 if ty.NumOut() == 1 && ty.Out(0).Kind() == reflect.Struct {
265 outType := ty.Out(0)
266 if runtime.GOARCH == "amd64" && outType.Size() > maxRegAllocStructSize {
267 val := reflect.New(outType)
268 keepAlive = append(keepAlive, val)
269 addInt(val.Pointer())
270 } else if runtime.GOARCH == "arm64" && outType.Size() > maxRegAllocStructSize {
271 isAllFloats, numFields := isAllSameFloat(outType)
272 if !isAllFloats || numFields > 4 {
273 val := reflect.New(outType)
274 keepAlive = append(keepAlive, val)
275 syscall.arm64_r8 = val.Pointer()
276 }
277 }
278 }
279 for _, v := range args {
280 switch v.Kind() {
281 case reflect.String:
282 ptr := strings.CString(v.String())
283 keepAlive = append(keepAlive, ptr)
284 addInt(uintptr(unsafe.Pointer(ptr)))
285 case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
286 addInt(uintptr(v.Uint()))
287 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
288 addInt(uintptr(v.Int()))
289 case reflect.Ptr, reflect.UnsafePointer, reflect.Slice:
290 // There is no need to keepAlive this pointer separately because it is kept alive in the args variable
291 addInt(v.Pointer())
292 case reflect.Func:
293 addInt(NewCallback(v.Interface()))
294 case reflect.Bool:
295 if v.Bool() {
296 addInt(1)
297 } else {
298 addInt(0)
299 }
300 case reflect.Float32:
301 addFloat(uintptr(math.Float32bits(float32(v.Float()))))
302 case reflect.Float64:
303 addFloat(uintptr(math.Float64bits(v.Float())))
304 case reflect.Struct:
305 keepAlive = addStruct(v, &numInts, &numFloats, &numStack, addInt, addFloat, addStack, keepAlive)
306 default:
307 panic("purego: unsupported kind: " + v.Kind().String())
308 }
309 }
310 if runtime.GOARCH == "arm64" || runtime.GOOS != "windows" {
311 // Use the normal arm64 calling convention even on Windows
312 syscall = syscall15Args{
313 cfn,
314 sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4], sysargs[5],
315 sysargs[6], sysargs[7], sysargs[8], sysargs[9], sysargs[10], sysargs[11],
316 sysargs[12], sysargs[13], sysargs[14],
317 floats[0], floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[7],
318 syscall.arm64_r8,
319 }
320 runtime_cgocall(syscall15XABI0, unsafe.Pointer(&syscall))
321 } else {
322 // This is a fallback for Windows amd64, 386, and arm. Note this may not support floats
323 syscall.a1, syscall.a2, _ = syscall_syscall15X(cfn, sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4],
324 sysargs[5], sysargs[6], sysargs[7], sysargs[8], sysargs[9], sysargs[10], sysargs[11],
325 sysargs[12], sysargs[13], sysargs[14])
326 syscall.f1 = syscall.a2 // on amd64 a2 stores the float return. On 32bit platforms floats aren't support
327 }
328 if ty.NumOut() == 0 {
329 return nil
330 }
331 outType := ty.Out(0)
332 v := reflect.New(outType).Elem()
333 switch outType.Kind() {
334 case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
335 v.SetUint(uint64(syscall.a1))
336 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
337 v.SetInt(int64(syscall.a1))
338 case reflect.Bool:
339 v.SetBool(byte(syscall.a1) != 0)
340 case reflect.UnsafePointer:
341 // We take the address and then dereference it to trick go vet from creating a possible miss-use of unsafe.Pointer
342 v.SetPointer(*(*unsafe.Pointer)(unsafe.Pointer(&syscall.a1)))
343 case reflect.Ptr:
344 v = reflect.NewAt(outType, unsafe.Pointer(&syscall.a1)).Elem()
345 case reflect.Func:
346 // wrap this C function in a nicely typed Go function
347 v = reflect.New(outType)
348 RegisterFunc(v.Interface(), syscall.a1)
349 case reflect.String:
350 v.SetString(strings.GoString(syscall.a1))
351 case reflect.Float32:
352 // NOTE: syscall.r2 is only the floating return value on 64bit platforms.
353 // On 32bit platforms syscall.r2 is the upper part of a 64bit return.
354 v.SetFloat(float64(math.Float32frombits(uint32(syscall.f1))))
355 case reflect.Float64:
356 // NOTE: syscall.r2 is only the floating return value on 64bit platforms.
357 // On 32bit platforms syscall.r2 is the upper part of a 64bit return.
358 v.SetFloat(math.Float64frombits(uint64(syscall.f1)))
359 case reflect.Struct:
360 v = getStruct(outType, syscall)
361 default:
362 panic("purego: unsupported return kind: " + outType.Kind().String())
363 }
364 return []reflect.Value{v}
365 })
366 fn.Set(v)
367}
368
369// maxRegAllocStructSize is the biggest a struct can be while still fitting in registers.
370// if it is bigger than this than enough space must be allocated on the heap and then passed into
371// the function as the first parameter on amd64 or in R8 on arm64.
372//
373// If you change this make sure to update it in objc_runtime_darwin.go
374const maxRegAllocStructSize = 16
375
376func isAllSameFloat(ty reflect.Type) (allFloats bool, numFields int) {
377 allFloats = true
378 root := ty.Field(0).Type
379 for root.Kind() == reflect.Struct {
380 root = root.Field(0).Type
381 }
382 first := root.Kind()
383 if first != reflect.Float32 && first != reflect.Float64 {
384 allFloats = false
385 }
386 for i := 0; i < ty.NumField(); i++ {
387 f := ty.Field(i).Type
388 if f.Kind() == reflect.Struct {
389 var structNumFields int
390 allFloats, structNumFields = isAllSameFloat(f)
391 numFields += structNumFields
392 continue
393 }
394 numFields++
395 if f.Kind() != first {
396 allFloats = false
397 }
398 }
399 return allFloats, numFields
400}
401
402func checkStructFieldsSupported(ty reflect.Type) {
403 for i := 0; i < ty.NumField(); i++ {
404 f := ty.Field(i).Type
405 if f.Kind() == reflect.Array {
406 f = f.Elem()
407 } else if f.Kind() == reflect.Struct {
408 checkStructFieldsSupported(f)
409 continue
410 }
411 switch f.Kind() {
412 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
413 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
414 reflect.Uintptr, reflect.Ptr, reflect.UnsafePointer, reflect.Float64, reflect.Float32:
415 default:
416 panic(fmt.Sprintf("purego: struct field type %s is not supported", f))
417 }
418 }
419}
420
421func roundUpTo8(val uintptr) uintptr {
422 return (val + 7) &^ 7
423}
424
425func numOfIntegerRegisters() int {
426 switch runtime.GOARCH {
427 case "arm64":
428 return 8
429 case "amd64":
430 return 6
431 default:
432 // since this platform isn't supported and can therefore only access
433 // integer registers it is fine to return the maxArgs
434 return maxArgs
435 }
436}