1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2022 The Ebitengine Authors
3
4//go:build darwin || linux
5
6package purego
7
8import (
9 "math"
10 "reflect"
11 "runtime"
12 "unsafe"
13
14 "github.com/ebitengine/purego/internal/strings"
15)
16
17// RegisterLibFunc is a wrapper around RegisterFunc that uses the C function returned from Dlsym(handle, name).
18// It panics if Dlsym fails.
19//
20// Windows does not support this function.
21func RegisterLibFunc(fptr interface{}, handle uintptr, name string) {
22 sym := Dlsym(handle, name)
23 if sym == 0 {
24 panic("purego: couldn't find symbol: " + Dlerror())
25 }
26 RegisterFunc(fptr, sym)
27}
28
29// RegisterFunc takes a pointer to a Go function representing the calling convention of the C function.
30// fptr will be set to a function that when called will call the C function given by cfn with the
31// parameters passed in the correct registers and stack.
32//
33// A panic is produced if the type is not a function pointer or if the function returns more than 1 value.
34//
35// These conversions describe how a Go type in the fptr will be used to call
36// the C function. It is important to note that there is no way to verify that fptr
37// matches the C function. This also holds true for struct types where the padding
38// needs to be ensured to match that of C; RegisterFunc does not verify this.
39//
40// Type Conversions (Go => C)
41//
42// string <=> char*
43// bool <=> _Bool
44// uintptr <=> uintptr_t
45// uint <=> uint32_t or uint64_t
46// uint8 <=> uint8_t
47// uint16 <=> uint16_t
48// uint32 <=> uint32_t
49// uint64 <=> uint64_t
50// int <=> int32_t or int64_t
51// int8 <=> int8_t
52// int16 <=> int16_t
53// int32 <=> int32_t
54// int64 <=> int64_t
55// float32 <=> float (WIP)
56// float64 <=> double (WIP)
57// struct <=> struct (WIP)
58// func <=> C function
59// unsafe.Pointer, *T <=> void*
60// []T => void*
61//
62// There is a special case when the last argument of fptr is a variadic interface (or []interface}
63// it will be expanded into a call to the C function as if it had the arguments in that slice.
64// This means that using arg ...interface{} is like a cast to the function with the arguments inside arg.
65// This is not the same as C variadic.
66//
67// There are some limitations when using RegisterFunc on Linux. First, there is no support for function arguments.
68// Second, float32 and float64 arguments and return values do not work when CGO_ENABLED=1. Otherwise, Linux
69// has the same feature parity as Darwin.
70//
71// Windows does not support this function.
72func RegisterFunc(fptr interface{}, cfn uintptr) {
73 fn := reflect.ValueOf(fptr).Elem()
74 ty := fn.Type()
75 if ty.Kind() != reflect.Func {
76 panic("purego: fptr must be a function pointer")
77 }
78 if ty.NumOut() > 1 {
79 panic("purego: function can only return zero or one values")
80 }
81 if cfn == 0 {
82 panic("purego: cfn is nil")
83 }
84 {
85 // this code checks how many registers and stack this function will use
86 // to avoid crashing with too many arguments
87 var ints int
88 var floats int
89 var stack int
90 for i := 0; i < ty.NumIn(); i++ {
91 arg := ty.In(i)
92 switch arg.Kind() {
93 case reflect.String, reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
94 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Ptr, reflect.UnsafePointer, reflect.Slice,
95 reflect.Func, reflect.Bool:
96 if ints < numOfIntegerRegisters() {
97 ints++
98 } else {
99 stack++
100 }
101 case reflect.Float32, reflect.Float64:
102 if floats < 8 {
103 floats++
104 } else {
105 stack++
106 }
107 default:
108 panic("purego: unsupported kind " + arg.Kind().String())
109 }
110 }
111 if ints+stack > maxArgs || floats+stack > maxArgs {
112 panic("purego: too many arguments")
113 }
114 }
115 v := reflect.MakeFunc(ty, func(args []reflect.Value) (results []reflect.Value) {
116 if len(args) > 0 {
117 if variadic, ok := args[len(args)-1].Interface().([]interface{}); ok {
118 // subtract one from args bc the last argument in args is []interface{}
119 // which we are currently expanding
120 tmp := make([]reflect.Value, len(args)-1+len(variadic))
121 n := copy(tmp, args[:len(args)-1])
122 for i, v := range variadic {
123 tmp[n+i] = reflect.ValueOf(v)
124 }
125 args = tmp
126 }
127 }
128 var sysargs [maxArgs]uintptr
129 var stack = sysargs[numOfIntegerRegisters():]
130 var floats [8]float64
131 var numInts int
132 var numFloats int
133 var numStack int
134 addStack := func(x uintptr) {
135 stack[numStack] = x
136 numStack++
137 }
138 addInt := func(x uintptr) {
139 if numInts >= numOfIntegerRegisters() {
140 addStack(x)
141 } else {
142 sysargs[numInts] = x
143 numInts++
144 }
145 }
146 var keepAlive []interface{}
147 defer func() {
148 runtime.KeepAlive(keepAlive)
149 }()
150 for _, v := range args {
151 switch v.Kind() {
152 case reflect.String:
153 ptr := strings.CString(v.String())
154 keepAlive = append(keepAlive, ptr)
155 addInt(uintptr(unsafe.Pointer(ptr)))
156 case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
157 addInt(uintptr(v.Uint()))
158 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
159 addInt(uintptr(v.Int()))
160 case reflect.Ptr, reflect.UnsafePointer, reflect.Slice:
161 keepAlive = append(keepAlive, v.Pointer())
162 addInt(v.Pointer())
163 case reflect.Func:
164 addInt(NewCallback(v.Interface()))
165 case reflect.Bool:
166 if v.Bool() {
167 addInt(1)
168 } else {
169 addInt(0)
170 }
171 case reflect.Float32, reflect.Float64:
172 if numFloats < len(floats) {
173 floats[numFloats] = v.Float()
174 numFloats++
175 } else {
176 addStack(uintptr(math.Float64bits(v.Float())))
177 }
178 default:
179 panic("purego: unsupported kind: " + v.Kind().String())
180 }
181 }
182 // TODO: support structs
183 syscall := syscall9Args{
184 cfn,
185 sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4], sysargs[5], sysargs[6], sysargs[7], sysargs[8],
186 floats[0], floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[7],
187 0, 0, 0}
188 runtime_cgocall(syscall9XABI0, unsafe.Pointer(&syscall))
189 r1, r2 := syscall.r1, syscall.r2
190
191 if ty.NumOut() == 0 {
192 return nil
193 }
194 outType := ty.Out(0)
195 v := reflect.New(outType).Elem()
196 switch outType.Kind() {
197 case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
198 v.SetUint(uint64(r1))
199 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
200 v.SetInt(int64(r1))
201 case reflect.Bool:
202 v.SetBool(r1 != 0)
203 case reflect.UnsafePointer:
204 // We take the address and then dereference it to trick go vet from creating a possible miss-use of unsafe.Pointer
205 v.SetPointer(*(*unsafe.Pointer)(unsafe.Pointer(&r1)))
206 case reflect.Ptr:
207 v = reflect.NewAt(outType, unsafe.Pointer(&r1)).Elem()
208 case reflect.Func:
209 // wrap this C function in a nicely typed Go function
210 v = reflect.New(outType)
211 RegisterFunc(v.Interface(), r1)
212 case reflect.String:
213 v.SetString(strings.GoString(r1))
214 case reflect.Float32, reflect.Float64:
215 // NOTE: r2 is only the floating return value on 64bit platforms.
216 // On 32bit platforms r2 is the upper part of a 64bit return.
217 v.SetFloat(math.Float64frombits(uint64(r2)))
218 default:
219 panic("purego: unsupported return kind: " + outType.Kind().String())
220 }
221 return []reflect.Value{v}
222 })
223 fn.Set(v)
224}
225
226func numOfIntegerRegisters() int {
227 switch runtime.GOARCH {
228 case "arm64":
229 return 8
230 case "amd64":
231 return 6
232 default:
233 panic("purego: unknown GOARCH (" + runtime.GOARCH + ")")
234 }
235}