-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathffi.go
243 lines (219 loc) · 8.05 KB
/
ffi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//go:build (freebsd || linux || windows || darwin) && (amd64 || arm64)
package ffi
import (
"unsafe"
"github.com/ebitengine/purego"
)
var prepCif, prepCifVar, call, closureAlloc, closureFree, prepClosureLoc uintptr
type Abi uint32
// Arg can be used as a return value for functions, which return integers smaller than 8 bytes.
//
// See [Call].
type Arg uint64
// Bool converts [Arg] into a Boolean.
func (a Arg) Bool() bool {
return byte(a) != 0
}
type Status uint32
const (
OK Status = iota
BadTypedef
BadAbi
BadArgType
)
func (s Status) String() string {
status := map[Status]string{OK: "OK", BadTypedef: "bad type definition", BadAbi: "bad ABI", BadArgType: "bad argument type"}
return status[s]
}
// These constants are used for the Type field of [Type].
const (
Void = iota
Int
Float
Double
Longdouble
Uint8
Sint8
Uint16
Sint16
Uint32
Sint32
Uint64
Sint64
Struct
Pointer
Complex
)
// Type is used to describe the structure of a data type.
//
// Example:
//
// // C struct:
// // typedef struct Point {
// // int x;
// // int y;
// // } Point;
//
// typePoint := ffi.Type{Type: ffi.Struct, Elements: &[]*ffi.Type{&ffi.TypeSint32, &ffi.TypeSint32, nil}[0]}
//
// Primitive data types are already defined (e.g. [TypeDouble] for float64).
type Type struct {
Size uint64 // Initialize to 0 (automatically set by libffi as needed).
Alignment uint16 // Initialize to 0 (automatically set by libffi as needed).
Type uint16 // Use ffi.Struct for struct types.
Elements **Type // Pointer to the first element of a nil-terminated slice.
}
// NewType can by used to create a new struct [Type].
//
// Example:
//
// ffi.NewType(&ffi.TypeFloat, &ffi.TypeFloat)
// // is equivalent to
// ffi.Type{Type: ffi.Struct, Elements: &[]*ffi.Type{&ffi.TypeFloat, &ffi.TypeFloat, nil}[0]}
func NewType(elements ...*Type) Type {
elements = append(elements, nil)
return Type{Type: Struct, Elements: &elements[0]}
}
// Cif stands for "Call InterFace". It describes the signature of a function.
//
// Use [PrepCif] to initialize it.
type Cif struct {
Abi uint32
NArgs uint32
ArgTypes **Type
RType *Type
Bytes uint32
Flags uint32
}
// Closure can be used to create callbacks (function pointers) at runtime.
//
// Use [ClosureAlloc] for allocation and [PrepClosureLoc] for preparation.
type Closure struct {
Tramp [TrampolineSize]byte
Cif *Cif
Fun unsafe.Pointer
UserData unsafe.Pointer
}
func NewCallback(fn func(cif *Cif, ret unsafe.Pointer, args *unsafe.Pointer, userData unsafe.Pointer) uintptr) uintptr {
return purego.NewCallback(fn)
}
// PrepCif initializes cif.
// - abi is the ABI to use. Normally [DefaultAbi] is what you want.
// - nArgs is the number of arguments. Use 0 if the function has none.
// - rType is the return type. Use [TypeVoid] if the function has none.
// - aTypes are the arguments. Leave empty or provide nil if the function has none.
//
// The returned status code will be [OK], if everything worked properly.
//
// Example:
//
// // C function:
// // double cos(double x);
//
// var cif ffi.Cif
// status := ffi.PrepCif(&cif, ffi.DefaultAbi, 1, &ffi.TypeDouble, &ffi.TypeDouble)
// if status != ffi.OK {
// panic(status)
// }
func PrepCif(cif *Cif, abi Abi, nArgs uint32, rType *Type, aTypes ...*Type) Status {
if len(aTypes) > 0 {
ret, _, _ := purego.SyscallN(prepCif, uintptr(unsafe.Pointer(cif)), uintptr(abi), uintptr(nArgs), uintptr(unsafe.Pointer(rType)), uintptr(unsafe.Pointer(&aTypes[0])))
return Status(ret)
}
ret, _, _ := purego.SyscallN(prepCif, uintptr(unsafe.Pointer(cif)), uintptr(abi), uintptr(nArgs), uintptr(unsafe.Pointer(rType)))
return Status(ret)
}
// PrepCifVar initializes cif for a call to a variadic function.
//
// In general its operation is the same as for [PrepCif] except that:
// - nFixedArgs is the number of fixed arguments, prior to any variadic arguments. It must be greater than zero.
// - nTotalArgs is the total number of arguments, including variadic and fixed arguments. aTypes must have this many elements.
//
// This function will return [BadArgType] if any of the variable argument types is [TypeFloat].
// Same goes for integer types smaller than 4 bytes. See [issue 608].
//
// Note that, different cif's must be prepped for calls to the same function when different numbers of arguments are passed.
//
// Also note that a call to this function with nFixedArgs = nTotalArgs is NOT equivalent to a call to [PrepCif].
//
// Example:
//
// // C function:
// // int printf(const char *restrict format, ...);
//
// var cif ffi.Cif
// status := ffi.PrepCifVar(&cif, ffi.DefaultAbi, 1, 2, &ffi.TypeSint32, &ffi.TypePointer, &ffi.TypeDouble)
// if status != ffi.OK {
// panic(status)
// }
//
// text, _ := unix.BytePtrFromString("Pi is %f\n")
// pi := math.Pi
// var nCharsPrinted int32
// ffi.Call(&cif, printf, unsafe.Pointer(&nCharsPrinted), unsafe.Pointer(&text), unsafe.Pointer(&pi))
//
// [issue 608]: https://github.com/libffi/libffi/issues/608
func PrepCifVar(cif *Cif, abi Abi, nFixedArgs, nTotalArgs uint32, rType *Type, aTypes ...*Type) Status {
const intSize = 4
// This check has been rebuild according to the original: https://github.com/libffi/libffi/blob/v3.4.6/src/prep_cif.c#L244
//
// Without rebuild, the type check wouldn't work for float,
// because libffi compares the pointer to ffi_type_float instead of value equality.
for i := nFixedArgs; i < nTotalArgs; i++ {
argType := *aTypes[i]
if argType == TypeFloat || ((argType.Type != Struct && argType.Type != Complex) && argType.Size < intSize) {
return BadArgType
}
}
if len(aTypes) > 0 {
ret, _, _ := purego.SyscallN(prepCifVar, uintptr(unsafe.Pointer(cif)), uintptr(abi), uintptr(nFixedArgs), uintptr(nTotalArgs), uintptr(unsafe.Pointer(rType)), uintptr(unsafe.Pointer(&aTypes[0])))
return Status(ret)
}
ret, _, _ := purego.SyscallN(prepCifVar, uintptr(unsafe.Pointer(cif)), uintptr(abi), uintptr(nFixedArgs), uintptr(nTotalArgs), uintptr(unsafe.Pointer(rType)))
return Status(ret)
}
// Call calls the function fn according to the description given in cif. cif must have already been prepared using [PrepCif].
// - fn is the address of the desired function. Use [purego.Dlsym] to get one.
// - rValue is a pointer to a variable that will hold the result of the function call. Provide nil if the function has no return value.
// You cannot use integer types smaller than 8 bytes here (float32 and structs are not affected). Use [Arg] instead and typecast afterwards.
// - aValues are pointers to the argument values. Leave empty or provide nil if the function takes none.
//
// Example:
//
// // C function:
// // int ilogb(double x);
//
// var result ffi.Arg
// x := 1.0
// ffi.Call(&cif, ilogb, unsafe.Pointer(&result), unsafe.Pointer(&x))
// fmt.Printf("%d\n", int32(result))
func Call(cif *Cif, fn uintptr, rValue unsafe.Pointer, aValues ...unsafe.Pointer) {
if len(aValues) > 0 {
purego.SyscallN(call, uintptr(unsafe.Pointer(cif)), fn, uintptr(rValue), uintptr(unsafe.Pointer(&aValues[0])))
return
}
purego.SyscallN(call, uintptr(unsafe.Pointer(cif)), fn, uintptr(rValue))
}
// ClosureAlloc allocates a new [Closure].
// - size should be big enough to hold a [Closure] object.
// - code is the corresponding executable address (function pointer).
//
// The Closure is not managed by Go's garbage collector. It can be deallocated by using [ClosureFree].
//
// Example:
//
// var code unsafe.Pointer
// closure := ffi.ClosureAlloc(unsafe.Sizeof(ffi.Closure{}), &code)
// defer ffi.ClosureFree(closure)
func ClosureAlloc(size uintptr, code *unsafe.Pointer) *Closure {
ret, _, _ := purego.SyscallN(closureAlloc, size, uintptr(unsafe.Pointer(code)))
return *(**Closure)(unsafe.Pointer(&ret))
}
// ClosureFree is used to free memory allocated by [ClosureAlloc].
func ClosureFree(writable *Closure) {
purego.SyscallN(closureFree, uintptr(unsafe.Pointer(writable)))
}
func PrepClosureLoc(closure *Closure, cif *Cif, fun uintptr, userData, codeLoc unsafe.Pointer) Status {
ret, _, _ := purego.SyscallN(prepClosureLoc, uintptr(unsafe.Pointer(closure)), uintptr(unsafe.Pointer(cif)), fun, uintptr(userData), uintptr(codeLoc))
return Status(ret)
}