1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2022 The Ebitengine Authors
3
4package purego
5
6import (
7 "reflect"
8 "runtime"
9 "sync"
10 "unsafe"
11)
12
13var syscall9XABI0 uintptr
14
15type syscall9Args struct{ fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, r1, r2, err uintptr }
16
17//go:nosplit
18func syscall_syscall9X(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2, err uintptr) {
19 args := syscall9Args{fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, r1, r2, err}
20 runtime_cgocall(syscall9XABI0, unsafe.Pointer(&args))
21 return args.r1, args.r2, args.err
22}
23
24// NewCallback converts a Go function to a function pointer conforming to the C calling convention.
25// This is useful when interoperating with C code requiring callbacks. The argument is expected to be a
26// function with zero or one uintptr-sized result. The function must not have arguments with size larger than the size
27// of uintptr. Only a limited number of callbacks may be created in a single Go process, and any memory allocated
28// for these callbacks is never released. At least 2000 callbacks can always be created. Although this function
29// provides similar functionality to windows.NewCallback it is distinct.
30func NewCallback(fn interface{}) uintptr {
31 return compileCallback(fn)
32}
33
34// maxCb is the maximum number of callbacks
35// only increase this if you have added more to the callbackasm function
36const maxCB = 2000
37
38var cbs struct {
39 lock sync.Mutex
40 numFn int // the number of functions currently in cbs.funcs
41 funcs [maxCB]reflect.Value // the saved callbacks
42}
43
44type callbackArgs struct {
45 index uintptr
46 // args points to the argument block.
47 //
48 // For cdecl and stdcall, all arguments are on the stack.
49 //
50 // For fastcall, the trampoline spills register arguments to
51 // the reserved spill slots below the stack arguments,
52 // resulting in a layout equivalent to stdcall.
53 //
54 // For arm, the trampoline stores the register arguments just
55 // below the stack arguments, so again we can treat it as one
56 // big stack arguments frame.
57 args unsafe.Pointer
58 // Below are out-args from callbackWrap
59 result uintptr
60}
61
62func compileCallback(fn interface{}) uintptr {
63 val := reflect.ValueOf(fn)
64 if val.Kind() != reflect.Func {
65 panic("purego: type is not a function")
66 }
67 ty := val.Type()
68 for i := 0; i < ty.NumIn(); i++ {
69 in := ty.In(i)
70 switch in.Kind() {
71 case reflect.Struct, reflect.Float32, reflect.Float64,
72 reflect.Interface, reflect.Func, reflect.Slice,
73 reflect.Chan, reflect.Complex64, reflect.Complex128,
74 reflect.String, reflect.Map, reflect.Invalid:
75 panic("purego: unsupported argument type: " + in.Kind().String())
76 }
77 }
78 if ty.NumOut() > 1 || ty.NumOut() == 1 && ty.Out(0).Size() != ptrSize {
79 panic("purego: callbacks can only have one pointer-sized return")
80 }
81 cbs.lock.Lock()
82 defer cbs.lock.Unlock()
83 if cbs.numFn >= maxCB {
84 panic("purego: the maximum number of callbacks has been reached")
85 }
86 cbs.funcs[cbs.numFn] = val
87 cbs.numFn++
88 return callbackasmAddr(cbs.numFn - 1)
89}
90
91const ptrSize = unsafe.Sizeof((*int)(nil))
92
93const callbackMaxFrame = 64 * ptrSize
94
95// callbackasmABI0 is implemented in zcallback_GOOS_GOARCH.s
96var callbackasmABI0 uintptr
97
98// callbackWrap is called by assembly code which determines which Go function to call.
99// This function takes the arguments and passes them to the Go function and returns the result.
100func callbackWrap(a *callbackArgs) {
101 cbs.lock.Lock()
102 fn := cbs.funcs[a.index]
103 cbs.lock.Unlock()
104 fnType := fn.Type()
105 args := make([]reflect.Value, fnType.NumIn())
106 frame := (*[callbackMaxFrame]uintptr)(a.args)
107 for i := range args {
108 //TODO: support float32 and float64
109 args[i] = reflect.NewAt(fnType.In(i), unsafe.Pointer(&frame[i])).Elem()
110 }
111 ret := fn.Call(args)
112 if len(ret) > 0 {
113 switch k := ret[0].Kind(); k {
114 case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uintptr:
115 a.result = uintptr(ret[0].Uint())
116 case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
117 a.result = uintptr(ret[0].Int())
118 case reflect.Bool:
119 if ret[0].Bool() {
120 a.result = 1
121 } else {
122 a.result = 0
123 }
124 default:
125 panic("purego: unsupported kind: " + k.String())
126 }
127 }
128}
129
130// callbackasmAddr returns address of runtime.callbackasm
131// function adjusted by i.
132// On x86 and amd64, runtime.callbackasm is a series of CALL instructions,
133// and we want callback to arrive at
134// correspondent call instruction instead of start of
135// runtime.callbackasm.
136// On ARM, runtime.callbackasm is a series of mov and branch instructions.
137// R12 is loaded with the callback index. Each entry is two instructions,
138// hence 8 bytes.
139func callbackasmAddr(i int) uintptr {
140 var entrySize int
141 switch runtime.GOARCH {
142 default:
143 panic("purego: unsupported architecture")
144 case "386", "amd64":
145 entrySize = 5
146 case "arm", "arm64":
147 // On ARM and ARM64, each entry is a MOV instruction
148 // followed by a branch instruction
149 entrySize = 8
150 }
151 return callbackasmABI0 + uintptr(i*entrySize)
152}