v0.7.0-alpha.2 9ef47a2

func.go RawHistoryFolder

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				if !isAllSameFloat(outType) || outType.NumField() > 4 {
254					val := reflect.New(outType)
255					keepAlive = append(keepAlive, val)
256					syscall.arm64_r8 = val.Pointer()
257				}
258			}
259		}
260		for _, v := range args {
261			switch v.Kind() {
262			case reflect.String:
263				ptr := strings.CString(v.String())
264				keepAlive = append(keepAlive, ptr)
265				addInt(uintptr(unsafe.Pointer(ptr)))
266			case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
267				addInt(uintptr(v.Uint()))
268			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
269				addInt(uintptr(v.Int()))
270			case reflect.Ptr, reflect.UnsafePointer, reflect.Slice:
271				// There is no need to keepAlive this pointer separately because it is kept alive in the args variable
272				addInt(v.Pointer())
273			case reflect.Func:
274				addInt(NewCallback(v.Interface()))
275			case reflect.Bool:
276				if v.Bool() {
277					addInt(1)
278				} else {
279					addInt(0)
280				}
281			case reflect.Float32:
282				addFloat(uintptr(math.Float32bits(float32(v.Float()))))
283			case reflect.Float64:
284				addFloat(uintptr(math.Float64bits(v.Float())))
285			case reflect.Struct:
286				keepAlive = addStruct(v, &numInts, &numFloats, &numStack, addInt, addFloat, addStack, keepAlive)
287			default:
288				panic("purego: unsupported kind: " + v.Kind().String())
289			}
290		}
291		if runtime.GOARCH == "arm64" || runtime.GOOS != "windows" {
292			// Use the normal arm64 calling convention even on Windows
293			syscall = syscall15Args{
294				cfn,
295				sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4], sysargs[5],
296				sysargs[6], sysargs[7], sysargs[8], sysargs[9], sysargs[10], sysargs[11],
297				sysargs[12], sysargs[13], sysargs[14],
298				floats[0], floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[7],
299				0, 0, 0, syscall.arm64_r8,
300			}
301			runtime_cgocall(syscall15XABI0, unsafe.Pointer(&syscall))
302		} else {
303			// This is a fallback for Windows amd64, 386, and arm. Note this may not support floats
304			syscall.a1, syscall.a2, _ = syscall_syscall15X(cfn, sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4],
305				sysargs[5], sysargs[6], sysargs[7], sysargs[8], sysargs[9], sysargs[10], sysargs[11],
306				sysargs[12], sysargs[13], sysargs[14])
307			syscall.f1 = syscall.a2 // on amd64 a2 stores the float return. On 32bit platforms floats aren't support
308		}
309		if ty.NumOut() == 0 {
310			return nil
311		}
312		outType := ty.Out(0)
313		v := reflect.New(outType).Elem()
314		switch outType.Kind() {
315		case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
316			v.SetUint(uint64(syscall.a1))
317		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
318			v.SetInt(int64(syscall.a1))
319		case reflect.Bool:
320			v.SetBool(byte(syscall.a1) != 0)
321		case reflect.UnsafePointer:
322			// We take the address and then dereference it to trick go vet from creating a possible miss-use of unsafe.Pointer
323			v.SetPointer(*(*unsafe.Pointer)(unsafe.Pointer(&syscall.a1)))
324		case reflect.Ptr:
325			// It is safe to have the address of syscall.r1 not escape because it is immediately dereferenced with .Elem()
326			v = reflect.NewAt(outType, runtime_noescape(unsafe.Pointer(&syscall.a1))).Elem()
327		case reflect.Func:
328			// wrap this C function in a nicely typed Go function
329			v = reflect.New(outType)
330			RegisterFunc(v.Interface(), syscall.a1)
331		case reflect.String:
332			v.SetString(strings.GoString(syscall.a1))
333		case reflect.Float32:
334			// NOTE: syscall.r2 is only the floating return value on 64bit platforms.
335			// On 32bit platforms syscall.r2 is the upper part of a 64bit return.
336			v.SetFloat(float64(math.Float32frombits(uint32(syscall.f1))))
337		case reflect.Float64:
338			// NOTE: syscall.r2 is only the floating return value on 64bit platforms.
339			// On 32bit platforms syscall.r2 is the upper part of a 64bit return.
340			v.SetFloat(math.Float64frombits(uint64(syscall.f1)))
341		case reflect.Struct:
342			v = getStruct(outType, syscall)
343		default:
344			panic("purego: unsupported return kind: " + outType.Kind().String())
345		}
346		return []reflect.Value{v}
347	})
348	fn.Set(v)
349}
350
351// maxRegAllocStructSize is the biggest a struct can be while still fitting in registers.
352// if it is bigger than this than enough space must be allocated on the heap and then passed into
353// the function as the first parameter on amd64 or in R8 on arm64.
354const maxRegAllocStructSize = 16
355
356func isAllSameFloat(ty reflect.Type) bool {
357	first := ty.Field(0).Type.Kind()
358	if first != reflect.Float32 && first != reflect.Float64 {
359		return false
360	}
361	for i := 0; i < ty.NumField(); i++ {
362		f := ty.Field(i)
363		if f.Type.Kind() != first {
364			return false
365		}
366	}
367	return true
368}
369
370func checkStructFieldsSupported(ty reflect.Type) {
371	for i := 0; i < ty.NumField(); i++ {
372		f := ty.Field(i).Type
373		if f.Kind() == reflect.Array {
374			f = f.Elem()
375		} else if f.Kind() == reflect.Struct {
376			checkStructFieldsSupported(f)
377			continue
378		}
379		switch f.Kind() {
380		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
381			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
382			reflect.Uintptr, reflect.Ptr, reflect.UnsafePointer, reflect.Float64, reflect.Float32:
383		default:
384			panic(fmt.Sprintf("purego: struct field type %s is not supported", f))
385		}
386	}
387}
388
389const is32bit = unsafe.Sizeof(uintptr(0)) == 4
390
391func roundUpTo8(val uintptr) uintptr {
392	return (val + 7) &^ 7
393}
394
395func numOfIntegerRegisters() int {
396	switch runtime.GOARCH {
397	case "arm64":
398		return 8
399	case "amd64":
400		return 6
401	// TODO: figure out why 386 tests are not working
402	/*case "386":
403		return 0
404	case "arm":
405		return 4*/
406	default:
407		panic("purego: unknown GOARCH (" + runtime.GOARCH + ")")
408	}
409}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 102

↑↓ moveenter openesc close