v0.9.0-alpha.2 6cbd046

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	"sync"
14	"unsafe"
15
16	"github.com/ebitengine/purego/internal/strings"
17)
18
19var thePool = sync.Pool{New: func() any {
20	return new(syscall15Args)
21}}
22
23// RegisterLibFunc is a wrapper around RegisterFunc that uses the C function returned from Dlsym(handle, name).
24// It panics if it can't find the name symbol.
25func RegisterLibFunc(fptr any, handle uintptr, name string) {
26	sym, err := loadSymbol(handle, name)
27	if err != nil {
28		panic(err)
29	}
30	RegisterFunc(fptr, sym)
31}
32
33// RegisterFunc takes a pointer to a Go function representing the calling convention of the C function.
34// fptr will be set to a function that when called will call the C function given by cfn with the
35// parameters passed in the correct registers and stack.
36//
37// A panic is produced if the type is not a function pointer or if the function returns more than 1 value.
38//
39// These conversions describe how a Go type in the fptr will be used to call
40// the C function. It is important to note that there is no way to verify that fptr
41// matches the C function. This also holds true for struct types where the padding
42// needs to be ensured to match that of C; RegisterFunc does not verify this.
43//
44// # Type Conversions (Go <=> C)
45//
46//	string <=> char*
47//	bool <=> _Bool
48//	uintptr <=> uintptr_t
49//	uint <=> uint32_t or uint64_t
50//	uint8 <=> uint8_t
51//	uint16 <=> uint16_t
52//	uint32 <=> uint32_t
53//	uint64 <=> uint64_t
54//	int <=> int32_t or int64_t
55//	int8 <=> int8_t
56//	int16 <=> int16_t
57//	int32 <=> int32_t
58//	int64 <=> int64_t
59//	float32 <=> float
60//	float64 <=> double
61//	struct <=> struct (WIP - darwin only)
62//	func <=> C function
63//	unsafe.Pointer, *T <=> void*
64//	[]T => void*
65//
66// There is a special case when the last argument of fptr is a variadic interface (or []interface}
67// it will be expanded into a call to the C function as if it had the arguments in that slice.
68// This means that using arg ...any is like a cast to the function with the arguments inside arg.
69// This is not the same as C variadic.
70//
71// # Memory
72//
73// In general it is not possible for purego to guarantee the lifetimes of objects returned or received from
74// calling functions using RegisterFunc. For arguments to a C function it is important that the C function doesn't
75// hold onto a reference to Go memory. This is the same as the [Cgo rules].
76//
77// However, there are some special cases. When passing a string as an argument if the string does not end in a null
78// terminated byte (\x00) then the string will be copied into memory maintained by purego. The memory is only valid for
79// that specific call. Therefore, if the C code keeps a reference to that string it may become invalid at some
80// undefined time. However, if the string does already contain a null-terminated byte then no copy is done.
81// It is then the responsibility of the caller to ensure the string stays alive as long as it's needed in C memory.
82// This can be done using runtime.KeepAlive or allocating the string in C memory using malloc. When a C function
83// returns a null-terminated pointer to char a Go string can be used. Purego will allocate a new string in Go memory
84// and copy the data over. This string will be garbage collected whenever Go decides it's no longer referenced.
85// This C created string will not be freed by purego. If the pointer to char is not null-terminated or must continue
86// 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
87// using unsafe.Slice. Doing this means that it becomes the responsibility of the caller to care about the lifetime
88// of the pointer
89//
90// # Structs
91//
92// Purego can handle the most common structs that have fields of builtin types like int8, uint16, float32, etc. However,
93// it does not support aligning fields properly. It is therefore the responsibility of the caller to ensure
94// that all padding is added to the Go struct to match the C one. See `BoolStructFn` in struct_test.go for an example.
95//
96// # Example
97//
98// All functions below call this C function:
99//
100//	char *foo(char *str);
101//
102//	// Let purego convert types
103//	var foo func(s string) string
104//	goString := foo("copied")
105//	// Go will garbage collect this string
106//
107//	// Manually, handle allocations
108//	var foo2 func(b string) *byte
109//	mustFree := foo2("not copied\x00")
110//	defer free(mustFree)
111//
112// [Cgo rules]: https://pkg.go.dev/cmd/cgo#hdr-Go_references_to_C
113func RegisterFunc(fptr any, cfn uintptr) {
114	fn := reflect.ValueOf(fptr).Elem()
115	ty := fn.Type()
116	if ty.Kind() != reflect.Func {
117		panic("purego: fptr must be a function pointer")
118	}
119	if ty.NumOut() > 1 {
120		panic("purego: function can only return zero or one values")
121	}
122	if cfn == 0 {
123		panic("purego: cfn is nil")
124	}
125	if ty.NumOut() == 1 && (ty.Out(0).Kind() == reflect.Float32 || ty.Out(0).Kind() == reflect.Float64) &&
126		runtime.GOARCH != "arm64" && runtime.GOARCH != "amd64" {
127		panic("purego: float returns are not supported")
128	}
129	{
130		// this code checks how many registers and stack this function will use
131		// to avoid crashing with too many arguments
132		var ints int
133		var floats int
134		var stack int
135		for i := 0; i < ty.NumIn(); i++ {
136			arg := ty.In(i)
137			switch arg.Kind() {
138			case reflect.Func:
139				// This only does preliminary testing to ensure the CDecl argument
140				// is the first argument. Full testing is done when the callback is actually
141				// created in NewCallback.
142				for j := 0; j < arg.NumIn(); j++ {
143					in := arg.In(j)
144					if !in.AssignableTo(reflect.TypeOf(CDecl{})) {
145						continue
146					}
147					if j != 0 {
148						panic("purego: CDecl must be the first argument")
149					}
150				}
151			case reflect.String, reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
152				reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Ptr, reflect.UnsafePointer,
153				reflect.Slice, reflect.Bool:
154				if ints < numOfIntegerRegisters() {
155					ints++
156				} else {
157					stack++
158				}
159			case reflect.Float32, reflect.Float64:
160				const is32bit = unsafe.Sizeof(uintptr(0)) == 4
161				if is32bit {
162					panic("purego: floats only supported on 64bit platforms")
163				}
164				if floats < numOfFloats {
165					floats++
166				} else {
167					stack++
168				}
169			case reflect.Struct:
170				if runtime.GOOS != "darwin" || (runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64") {
171					panic("purego: struct arguments are only supported on darwin amd64 & arm64")
172				}
173				if arg.Size() == 0 {
174					continue
175				}
176				addInt := func(u uintptr) {
177					ints++
178				}
179				addFloat := func(u uintptr) {
180					floats++
181				}
182				addStack := func(u uintptr) {
183					stack++
184				}
185				_ = addStruct(reflect.New(arg).Elem(), &ints, &floats, &stack, addInt, addFloat, addStack, nil)
186			default:
187				panic("purego: unsupported kind " + arg.Kind().String())
188			}
189		}
190		if ty.NumOut() == 1 && ty.Out(0).Kind() == reflect.Struct {
191			if runtime.GOOS != "darwin" {
192				panic("purego: struct return values only supported on darwin arm64 & amd64")
193			}
194			outType := ty.Out(0)
195			checkStructFieldsSupported(outType)
196			if runtime.GOARCH == "amd64" && outType.Size() > maxRegAllocStructSize {
197				// on amd64 if struct is bigger than 16 bytes allocate the return struct
198				// and pass it in as a hidden first argument.
199				ints++
200			}
201		}
202		sizeOfStack := maxArgs - numOfIntegerRegisters()
203		if stack > sizeOfStack {
204			panic("purego: too many arguments")
205		}
206	}
207	v := reflect.MakeFunc(ty, func(args []reflect.Value) (results []reflect.Value) {
208		var sysargs [maxArgs]uintptr
209		stack := sysargs[numOfIntegerRegisters():]
210		var floats [numOfFloats]uintptr
211		var numInts int
212		var numFloats int
213		var numStack int
214		var addStack, addInt, addFloat func(x uintptr)
215		if runtime.GOARCH == "arm64" || runtime.GOOS != "windows" {
216			// Windows arm64 uses the same calling convention as macOS and Linux
217			addStack = func(x uintptr) {
218				stack[numStack] = x
219				numStack++
220			}
221			addInt = func(x uintptr) {
222				if numInts >= numOfIntegerRegisters() {
223					addStack(x)
224				} else {
225					sysargs[numInts] = x
226					numInts++
227				}
228			}
229			addFloat = func(x uintptr) {
230				if numFloats < len(floats) {
231					floats[numFloats] = x
232					numFloats++
233				} else {
234					addStack(x)
235				}
236			}
237		} else {
238			// On Windows amd64 the arguments are passed in the numbered registered.
239			// So the first int is in the first integer register and the first float
240			// is in the second floating register if there is already a first int.
241			// This is in contrast to how macOS and Linux pass arguments which
242			// tries to use as many registers as possible in the calling convention.
243			addStack = func(x uintptr) {
244				sysargs[numStack] = x
245				numStack++
246			}
247			addInt = addStack
248			addFloat = addStack
249		}
250
251		var keepAlive []any
252		defer func() {
253			runtime.KeepAlive(keepAlive)
254			runtime.KeepAlive(args)
255		}()
256
257		var arm64_r8 uintptr
258		if ty.NumOut() == 1 && ty.Out(0).Kind() == reflect.Struct {
259			outType := ty.Out(0)
260			if runtime.GOARCH == "amd64" && outType.Size() > maxRegAllocStructSize {
261				val := reflect.New(outType)
262				keepAlive = append(keepAlive, val)
263				addInt(val.Pointer())
264			} else if runtime.GOARCH == "arm64" && outType.Size() > maxRegAllocStructSize {
265				isAllFloats, numFields := isAllSameFloat(outType)
266				if !isAllFloats || numFields > 4 {
267					val := reflect.New(outType)
268					keepAlive = append(keepAlive, val)
269					arm64_r8 = val.Pointer()
270				}
271			}
272		}
273		for i, v := range args {
274			if variadic, ok := args[i].Interface().([]any); ok {
275				if i != len(args)-1 {
276					panic("purego: can only expand last parameter")
277				}
278				for _, x := range variadic {
279					keepAlive = addValue(reflect.ValueOf(x), keepAlive, addInt, addFloat, addStack, &numInts, &numFloats, &numStack)
280				}
281				continue
282			}
283			keepAlive = addValue(v, keepAlive, addInt, addFloat, addStack, &numInts, &numFloats, &numStack)
284		}
285
286		syscall := thePool.Get().(*syscall15Args)
287		defer thePool.Put(syscall)
288
289		if runtime.GOARCH == "arm64" || runtime.GOOS != "windows" {
290			// Use the normal arm64 calling convention even on Windows
291			*syscall = syscall15Args{
292				cfn,
293				sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4], sysargs[5],
294				sysargs[6], sysargs[7], sysargs[8], sysargs[9], sysargs[10], sysargs[11],
295				sysargs[12], sysargs[13], sysargs[14],
296				floats[0], floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[7],
297				arm64_r8,
298			}
299			runtime_cgocall(syscall15XABI0, unsafe.Pointer(syscall))
300		} else {
301			*syscall = syscall15Args{}
302			// This is a fallback for Windows amd64, 386, and arm. Note this may not support floats
303			syscall.a1, syscall.a2, _ = syscall_syscall15X(cfn, sysargs[0], sysargs[1], sysargs[2], sysargs[3], sysargs[4],
304				sysargs[5], sysargs[6], sysargs[7], sysargs[8], sysargs[9], sysargs[10], sysargs[11],
305				sysargs[12], sysargs[13], sysargs[14])
306			syscall.f1 = syscall.a2 // on amd64 a2 stores the float return. On 32bit platforms floats aren't support
307		}
308		if ty.NumOut() == 0 {
309			return nil
310		}
311		outType := ty.Out(0)
312		v := reflect.New(outType).Elem()
313		switch outType.Kind() {
314		case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
315			v.SetUint(uint64(syscall.a1))
316		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
317			v.SetInt(int64(syscall.a1))
318		case reflect.Bool:
319			v.SetBool(byte(syscall.a1) != 0)
320		case reflect.UnsafePointer:
321			// We take the address and then dereference it to trick go vet from creating a possible miss-use of unsafe.Pointer
322			v.SetPointer(*(*unsafe.Pointer)(unsafe.Pointer(&syscall.a1)))
323		case reflect.Ptr:
324			v = reflect.NewAt(outType, unsafe.Pointer(&syscall.a1)).Elem()
325		case reflect.Func:
326			// wrap this C function in a nicely typed Go function
327			v = reflect.New(outType)
328			RegisterFunc(v.Interface(), syscall.a1)
329		case reflect.String:
330			v.SetString(strings.GoString(syscall.a1))
331		case reflect.Float32:
332			// NOTE: syscall.r2 is only the floating return value on 64bit platforms.
333			// On 32bit platforms syscall.r2 is the upper part of a 64bit return.
334			v.SetFloat(float64(math.Float32frombits(uint32(syscall.f1))))
335		case reflect.Float64:
336			// NOTE: syscall.r2 is only the floating return value on 64bit platforms.
337			// On 32bit platforms syscall.r2 is the upper part of a 64bit return.
338			v.SetFloat(math.Float64frombits(uint64(syscall.f1)))
339		case reflect.Struct:
340			v = getStruct(outType, *syscall)
341		default:
342			panic("purego: unsupported return kind: " + outType.Kind().String())
343		}
344		if len(args) > 0 {
345			// reuse args slice instead of allocating one when possible
346			args[0] = v
347			return args[:1]
348		} else {
349			return []reflect.Value{v}
350		}
351	})
352	fn.Set(v)
353}
354
355func addValue(v reflect.Value, keepAlive []any, addInt func(x uintptr), addFloat func(x uintptr), addStack func(x uintptr), numInts *int, numFloats *int, numStack *int) []any {
356	switch v.Kind() {
357	case reflect.String:
358		ptr := strings.CString(v.String())
359		keepAlive = append(keepAlive, ptr)
360		addInt(uintptr(unsafe.Pointer(ptr)))
361	case reflect.Uintptr, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
362		addInt(uintptr(v.Uint()))
363	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
364		addInt(uintptr(v.Int()))
365	case reflect.Ptr, reflect.UnsafePointer, reflect.Slice:
366		// There is no need to keepAlive this pointer separately because it is kept alive in the args variable
367		addInt(v.Pointer())
368	case reflect.Func:
369		addInt(NewCallback(v.Interface()))
370	case reflect.Bool:
371		if v.Bool() {
372			addInt(1)
373		} else {
374			addInt(0)
375		}
376	case reflect.Float32:
377		addFloat(uintptr(math.Float32bits(float32(v.Float()))))
378	case reflect.Float64:
379		addFloat(uintptr(math.Float64bits(v.Float())))
380	case reflect.Struct:
381		keepAlive = addStruct(v, numInts, numFloats, numStack, addInt, addFloat, addStack, keepAlive)
382	default:
383		panic("purego: unsupported kind: " + v.Kind().String())
384	}
385	return keepAlive
386}
387
388// maxRegAllocStructSize is the biggest a struct can be while still fitting in registers.
389// if it is bigger than this than enough space must be allocated on the heap and then passed into
390// the function as the first parameter on amd64 or in R8 on arm64.
391//
392// If you change this make sure to update it in objc_runtime_darwin.go
393const maxRegAllocStructSize = 16
394
395func isAllSameFloat(ty reflect.Type) (allFloats bool, numFields int) {
396	allFloats = true
397	root := ty.Field(0).Type
398	for root.Kind() == reflect.Struct {
399		root = root.Field(0).Type
400	}
401	first := root.Kind()
402	if first != reflect.Float32 && first != reflect.Float64 {
403		allFloats = false
404	}
405	for i := 0; i < ty.NumField(); i++ {
406		f := ty.Field(i).Type
407		if f.Kind() == reflect.Struct {
408			var structNumFields int
409			allFloats, structNumFields = isAllSameFloat(f)
410			numFields += structNumFields
411			continue
412		}
413		numFields++
414		if f.Kind() != first {
415			allFloats = false
416		}
417	}
418	return allFloats, numFields
419}
420
421func checkStructFieldsSupported(ty reflect.Type) {
422	for i := 0; i < ty.NumField(); i++ {
423		f := ty.Field(i).Type
424		if f.Kind() == reflect.Array {
425			f = f.Elem()
426		} else if f.Kind() == reflect.Struct {
427			checkStructFieldsSupported(f)
428			continue
429		}
430		switch f.Kind() {
431		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
432			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
433			reflect.Uintptr, reflect.Ptr, reflect.UnsafePointer, reflect.Float64, reflect.Float32:
434		default:
435			panic(fmt.Sprintf("purego: struct field type %s is not supported", f))
436		}
437	}
438}
439
440func roundUpTo8(val uintptr) uintptr {
441	return (val + 7) &^ 7
442}
443
444func numOfIntegerRegisters() int {
445	switch runtime.GOARCH {
446	case "arm64":
447		return 8
448	case "amd64":
449		return 6
450	default:
451		// since this platform isn't supported and can therefore only access
452		// integer registers it is fine to return the maxArgs
453		return maxArgs
454	}
455}

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