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 {
121 // this code checks how many registers and stack this function will use
122 // to avoid crashing with too many arguments
123 var ints int
124 var floats int
125 var stack int
126 for i := 0; i < ty.NumIn(); i++ {
127 arg := ty.In(i)
128 switch arg.Kind() {
129 case reflect.String, reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
130 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Ptr, reflect.UnsafePointer, reflect.Slice,
131 reflect.Func, reflect.Bool:
132 if ints < numOfIntegerRegisters() {
133 ints++
134 } else {
135 stack++
136 }
137 case reflect.Float32, reflect.Float64:
138 if is32bit {
139 panic("purego: floats only supported on 64bit platforms")
140 }
141 if floats < numOfFloats {
142 floats++
143 } else {
144 stack++
145 }
146 case reflect.Struct:
147 if runtime.GOOS != "darwin" || (runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64") {
148 panic("purego: struct arguments are only supported on darwin amd64 & arm64")
149 }
150 if arg.Size() == 0 {
151 continue
152 }
153 addInt := func(u uintptr) {
154 ints++
155 }
156 addFloat := func(u uintptr) {
157 floats++
158 }
159 addStack := func(u uintptr) {
160 stack++
161 }
162 _ = addStruct(reflect.New(arg).Elem(), &ints, &floats, &stack, addInt, addFloat, addStack, nil)
163 default:
164 panic("purego: unsupported kind " + arg.Kind().String())
165 }
166 }
167 if ty.NumOut() == 1 && ty.Out(0).Kind() == reflect.Struct {
168 if runtime.GOOS != "darwin" {
169 panic("purego: struct return values only supported on darwin arm64 & amd64")
170 }
171 outType := ty.Out(0)
172 checkStructFieldsSupported(outType)
173 if runtime.GOARCH == "amd64" && outType.Size() > maxRegAllocStructSize {
174 // on amd64 if struct is bigger than 16 bytes allocate the return struct
175 // and pass it in as a hidden first argument.
176 ints++
177 }
178 }
179 sizeOfStack := maxArgs - numOfIntegerRegisters()
180 if stack > sizeOfStack {
181 panic("purego: too many arguments")
182 }
183 }
184 v := reflect.MakeFunc(ty, func(args []reflect.Value) (results []reflect.Value) {
185 if len(args) > 0 {
186 if variadic, ok := args[len(args)-1].Interface().([]interface{}); ok {
187 // subtract one from args bc the last argument in args is []interface{}
188 // which we are currently expanding
189 tmp := make([]reflect.Value, len(args)-1+len(variadic))
190 n := copy(tmp, args[:len(args)-1])
191 for i, v := range variadic {
192 tmp[n+i] = reflect.ValueOf(v)
193 }
194 args = tmp
195 }
196 }
197 var sysargs [maxArgs]uintptr
198 stack := sysargs[numOfIntegerRegisters():]
199 var floats [numOfFloats]uintptr
200 var numInts int
201 var numFloats int
202 var numStack int
203 var addStack, addInt, addFloat func(x uintptr)
204 if runtime.GOARCH == "arm64" || runtime.GOOS != "windows" {
205 // Windows arm64 uses the same calling convention as macOS and Linux
206 addStack = func(x uintptr) {
207 stack[numStack] = x
208 numStack++
209 }
210 addInt = func(x uintptr) {
211 if numInts >= numOfIntegerRegisters() {
212 addStack(x)
213 } else {
214 sysargs[numInts] = x
215 numInts++
216 }
217 }
218 addFloat = func(x uintptr) {
219 if numFloats < len(floats) {
220 floats[numFloats] = x
221 numFloats++
222 } else {
223 addStack(x)
224 }
225 }
226 } else {
227 // On Windows amd64 the arguments are passed in the numbered registered.
228 // So the first int is in the first integer register and the first float
229 // is in the second floating register if there is already a first int.
230 // This is in contrast to how macOS and Linux pass arguments which
231 // tries to use as many registers as possible in the calling convention.
232 addStack = func(x uintptr) {
233 sysargs[numStack] = x
234 numStack++
235 }
236 addInt = addStack
237 addFloat = addStack
238 }
239
240 var keepAlive []interface{}
241 defer func() {
242 runtime.KeepAlive(keepAlive)
243 runtime.KeepAlive(args)
244 }()
245 var syscall syscall15Args
246 if ty.NumOut() == 1 && ty.Out(0).Kind() == reflect.Struct {
247 outType := ty.Out(0)
248 if runtime.GOARCH == "amd64" && outType.Size() > maxRegAllocStructSize {
249 val := reflect.New(outType)
250 keepAlive = append(keepAlive, val)
251 addInt(val.Pointer())
252 } else if runtime.GOARCH == "arm64" && outType.Size() > maxRegAllocStructSize {
253 isAllFloats, numFields := isAllSameFloat(outType)
254 if !isAllFloats || numFields > 4 {
255 val := reflect.New(outType)
256 keepAlive = append(keepAlive, val)
257 syscall.arm64_r8 = val.Pointer()
258 }
259 }
260 }
261 for _, v := range args {
262 switch v.Kind() {
263 case reflect.String:
264 ptr := strings.CString(v.String())
265 keepAlive = append(keepAlive, ptr)
266 addInt(uintptr(unsafe.Pointer(ptr)))
267 case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
268 addInt(uintptr(v.Uint()))
269 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
270 addInt(uintptr(v.Int()))
271 case reflect.Ptr, reflect.UnsafePointer, reflect.Slice:
272 // There is no need to keepAlive this pointer separately because it is kept alive in the args variable
273 addInt(v.Pointer())
274 case reflect.Func:
275 addInt(NewCallback(v.Interface()))
276 case reflect.Bool:
277 if v.Bool() {
278 addInt(1)
279 } else {
280 addInt(0)
281 }
282 case reflect.Float32:
283 addFloat(uintptr(math.Float32bits(float32(v.Float()))))
284 case reflect.Float64:
285 addFloat(uintptr(math.Float64bits(v.Float())))
286 case reflect.Struct:
287 keepAlive = addStruct(v, &numInts, &numFloats, &numStack, addInt, addFloat, addStack, keepAlive)
288 default:
289 panic("purego: unsupported kind: " + v.Kind().String())
290 }
291 }
292 if runtime.GOARCH == "arm64" || runtime.GOOS != "windows" {
293 // Use the normal arm64 calling convention even on Windows
294 syscall = syscall15Args{
295 cfn,
296 sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4], sysargs[5],
297 sysargs[6], sysargs[7], sysargs[8], sysargs[9], sysargs[10], sysargs[11],
298 sysargs[12], sysargs[13], sysargs[14],
299 floats[0], floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[7],
300 syscall.arm64_r8,
301 }
302 runtime_cgocall(syscall15XABI0, unsafe.Pointer(&syscall))
303 } else {
304 // This is a fallback for Windows amd64, 386, and arm. Note this may not support floats
305 syscall.a1, syscall.a2, _ = syscall_syscall15X(cfn, sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4],
306 sysargs[5], sysargs[6], sysargs[7], sysargs[8], sysargs[9], sysargs[10], sysargs[11],
307 sysargs[12], sysargs[13], sysargs[14])
308 syscall.f1 = syscall.a2 // on amd64 a2 stores the float return. On 32bit platforms floats aren't support
309 }
310 if ty.NumOut() == 0 {
311 return nil
312 }
313 outType := ty.Out(0)
314 v := reflect.New(outType).Elem()
315 switch outType.Kind() {
316 case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
317 v.SetUint(uint64(syscall.a1))
318 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
319 v.SetInt(int64(syscall.a1))
320 case reflect.Bool:
321 v.SetBool(byte(syscall.a1) != 0)
322 case reflect.UnsafePointer:
323 // We take the address and then dereference it to trick go vet from creating a possible miss-use of unsafe.Pointer
324 v.SetPointer(*(*unsafe.Pointer)(unsafe.Pointer(&syscall.a1)))
325 case reflect.Ptr:
326 // It is safe to have the address of syscall.r1 not escape because it is immediately dereferenced with .Elem()
327 v = reflect.NewAt(outType, runtime_noescape(unsafe.Pointer(&syscall.a1))).Elem()
328 case reflect.Func:
329 // wrap this C function in a nicely typed Go function
330 v = reflect.New(outType)
331 RegisterFunc(v.Interface(), syscall.a1)
332 case reflect.String:
333 v.SetString(strings.GoString(syscall.a1))
334 case reflect.Float32:
335 // NOTE: syscall.r2 is only the floating return value on 64bit platforms.
336 // On 32bit platforms syscall.r2 is the upper part of a 64bit return.
337 v.SetFloat(float64(math.Float32frombits(uint32(syscall.f1))))
338 case reflect.Float64:
339 // NOTE: syscall.r2 is only the floating return value on 64bit platforms.
340 // On 32bit platforms syscall.r2 is the upper part of a 64bit return.
341 v.SetFloat(math.Float64frombits(uint64(syscall.f1)))
342 case reflect.Struct:
343 v = getStruct(outType, syscall)
344 default:
345 panic("purego: unsupported return kind: " + outType.Kind().String())
346 }
347 return []reflect.Value{v}
348 })
349 fn.Set(v)
350}
351
352// maxRegAllocStructSize is the biggest a struct can be while still fitting in registers.
353// if it is bigger than this than enough space must be allocated on the heap and then passed into
354// the function as the first parameter on amd64 or in R8 on arm64.
355//
356// If you change this make sure to update it in objc_runtime_darwin.go
357const maxRegAllocStructSize = 16
358
359func isAllSameFloat(ty reflect.Type) (allFloats bool, numFields int) {
360 allFloats = true
361 root := ty.Field(0).Type
362 for root.Kind() == reflect.Struct {
363 root = root.Field(0).Type
364 }
365 first := root.Kind()
366 if first != reflect.Float32 && first != reflect.Float64 {
367 allFloats = false
368 }
369 for i := 0; i < ty.NumField(); i++ {
370 f := ty.Field(i).Type
371 if f.Kind() == reflect.Struct {
372 var structNumFields int
373 allFloats, structNumFields = isAllSameFloat(f)
374 numFields += structNumFields
375 continue
376 }
377 numFields++
378 if f.Kind() != first {
379 allFloats = false
380 }
381 }
382 return allFloats, numFields
383}
384
385func checkStructFieldsSupported(ty reflect.Type) {
386 for i := 0; i < ty.NumField(); i++ {
387 f := ty.Field(i).Type
388 if f.Kind() == reflect.Array {
389 f = f.Elem()
390 } else if f.Kind() == reflect.Struct {
391 checkStructFieldsSupported(f)
392 continue
393 }
394 switch f.Kind() {
395 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
396 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
397 reflect.Uintptr, reflect.Ptr, reflect.UnsafePointer, reflect.Float64, reflect.Float32:
398 default:
399 panic(fmt.Sprintf("purego: struct field type %s is not supported", f))
400 }
401 }
402}
403
404const is32bit = unsafe.Sizeof(uintptr(0)) == 4
405
406func roundUpTo8(val uintptr) uintptr {
407 return (val + 7) &^ 7
408}
409
410func numOfIntegerRegisters() int {
411 switch runtime.GOARCH {
412 case "arm64":
413 return 8
414 case "amd64":
415 return 6
416 // TODO: figure out why 386 tests are not working
417 /*case "386":
418 return 0
419 case "arm":
420 return 4*/
421 default:
422 panic("purego: unknown GOARCH (" + runtime.GOARCH + ")")
423 }
424}