1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2022 The Ebitengine Authors
3
4//go:build darwin || (!cgo && linux && (amd64 || arm64))
5
6package purego
7
8import (
9 "reflect"
10 "runtime"
11 "sync"
12 "unsafe"
13)
14
15var syscall9XABI0 uintptr
16
17type syscall9Args struct {
18 fn, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr
19 f1, f2, f3, f4, f5, f6, f7, f8 uintptr
20 r1, r2, err uintptr
21}
22
23//go:nosplit
24func syscall_syscall9X(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2, err uintptr) {
25 args := syscall9Args{
26 fn, a1, a2, a3, a4, a5, a6, a7, a8, a9,
27 a1, a2, a3, a4, a5, a6, a7, a8,
28 r1, r2, err,
29 }
30 runtime_cgocall(syscall9XABI0, unsafe.Pointer(&args))
31 return args.r1, args.r2, args.err
32}
33
34// NewCallback converts a Go function to a function pointer conforming to the C calling convention.
35// This is useful when interoperating with C code requiring callbacks. The argument is expected to be a
36// function with zero or one uintptr-sized result. The function must not have arguments with size larger than the size
37// of uintptr. Only a limited number of callbacks may be created in a single Go process, and any memory allocated
38// for these callbacks is never released. At least 2000 callbacks can always be created. Although this function
39// provides similar functionality to windows.NewCallback it is distinct.
40//
41// NOTE: Linux is currently not supported and will panic if called.
42func NewCallback(fn interface{}) uintptr {
43 if runtime.GOOS == "linux" {
44 panic("purego: NewCallback not supported")
45 }
46 return compileCallback(fn)
47}
48
49// maxCb is the maximum number of callbacks
50// only increase this if you have added more to the callbackasm function
51const maxCB = 2000
52
53var cbs struct {
54 lock sync.Mutex
55 numFn int // the number of functions currently in cbs.funcs
56 funcs [maxCB]reflect.Value // the saved callbacks
57}
58
59type callbackArgs struct {
60 index uintptr
61 // args points to the argument block.
62 //
63 // The structure of the arguments goes
64 // float registers followed by the
65 // integer registers followed by the stack.
66 //
67 // This variable is treated as a continuous
68 // block of memory containing all of the arguments
69 // for this callback.
70 args unsafe.Pointer
71 // Below are out-args from callbackWrap
72 result uintptr
73}
74
75func compileCallback(fn interface{}) uintptr {
76 val := reflect.ValueOf(fn)
77 if val.Kind() != reflect.Func {
78 panic("purego: the type must be a function but was not")
79 }
80 if val.IsNil() {
81 panic("purego: function must not be nil")
82 }
83 ty := val.Type()
84 for i := 0; i < ty.NumIn(); i++ {
85 in := ty.In(i)
86 switch in.Kind() {
87 case reflect.Struct, reflect.Interface, reflect.Func, reflect.Slice,
88 reflect.Chan, reflect.Complex64, reflect.Complex128,
89 reflect.String, reflect.Map, reflect.Invalid:
90 panic("purego: unsupported argument type: " + in.Kind().String())
91 }
92 }
93output:
94 switch {
95 case ty.NumOut() == 1:
96 switch ty.Out(0).Kind() {
97 case reflect.Pointer, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
98 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
99 reflect.Bool, reflect.UnsafePointer:
100 break output
101 }
102 panic("purego: unsupported return type: " + ty.String())
103 case ty.NumOut() > 1:
104 panic("purego: callbacks can only have one return")
105 }
106 cbs.lock.Lock()
107 defer cbs.lock.Unlock()
108 if cbs.numFn >= maxCB {
109 panic("purego: the maximum number of callbacks has been reached")
110 }
111 cbs.funcs[cbs.numFn] = val
112 cbs.numFn++
113 return callbackasmAddr(cbs.numFn - 1)
114}
115
116const ptrSize = unsafe.Sizeof((*int)(nil))
117
118const callbackMaxFrame = 64 * ptrSize
119
120// callbackasmABI0 is implemented in zcallback_GOOS_GOARCH.s
121var callbackasmABI0 uintptr
122
123// callbackWrap_call allows the calling of the ABIInternal wrapper
124// which is required for runtime.cgocallback without the
125// <ABIInternal> tag which is only allowed in the runtime.
126// This closure is used inside sys_darwin_GOARCH.s
127var callbackWrap_call = callbackWrap
128
129// callbackWrap is called by assembly code which determines which Go function to call.
130// This function takes the arguments and passes them to the Go function and returns the result.
131func callbackWrap(a *callbackArgs) {
132 cbs.lock.Lock()
133 fn := cbs.funcs[a.index]
134 cbs.lock.Unlock()
135 fnType := fn.Type()
136 args := make([]reflect.Value, fnType.NumIn())
137 frame := (*[callbackMaxFrame]uintptr)(a.args)
138 var floatsN int // floatsN represents the number of float arguments processed
139 var intsN int // intsN represents the number of integer arguments processed
140 // stack points to the index into frame of the current stack element.
141 // The stack begins after the float and integer registers.
142 stack := numOfIntegerRegisters() + numOfFloats
143 for i := range args {
144 var pos int
145 switch fnType.In(i).Kind() {
146 case reflect.Float32, reflect.Float64:
147 if floatsN >= numOfFloats {
148 pos = stack
149 stack++
150 } else {
151 pos = floatsN
152 }
153 floatsN++
154 default:
155 if intsN >= numOfIntegerRegisters() {
156 pos = stack
157 stack++
158 } else {
159 // the integers begin after the floats in frame
160 pos = intsN + numOfFloats
161 }
162 intsN++
163 }
164 args[i] = reflect.NewAt(fnType.In(i), unsafe.Pointer(&frame[pos])).Elem()
165 }
166 ret := fn.Call(args)
167 if len(ret) > 0 {
168 switch k := ret[0].Kind(); k {
169 case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uintptr:
170 a.result = uintptr(ret[0].Uint())
171 case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
172 a.result = uintptr(ret[0].Int())
173 case reflect.Bool:
174 if ret[0].Bool() {
175 a.result = 1
176 } else {
177 a.result = 0
178 }
179 case reflect.Pointer:
180 a.result = ret[0].Pointer()
181 case reflect.UnsafePointer:
182 a.result = ret[0].Pointer()
183 default:
184 panic("purego: unsupported kind: " + k.String())
185 }
186 }
187}
188
189// callbackasmAddr returns address of runtime.callbackasm
190// function adjusted by i.
191// On x86 and amd64, runtime.callbackasm is a series of CALL instructions,
192// and we want callback to arrive at
193// correspondent call instruction instead of start of
194// runtime.callbackasm.
195// On ARM, runtime.callbackasm is a series of mov and branch instructions.
196// R12 is loaded with the callback index. Each entry is two instructions,
197// hence 8 bytes.
198func callbackasmAddr(i int) uintptr {
199 var entrySize int
200 switch runtime.GOARCH {
201 default:
202 panic("purego: unsupported architecture")
203 case "386", "amd64":
204 entrySize = 5
205 case "arm", "arm64":
206 // On ARM and ARM64, each entry is a MOV instruction
207 // followed by a branch instruction
208 entrySize = 8
209 }
210 return callbackasmABI0 + uintptr(i*entrySize)
211}