diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 825df892..c64734aa 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -418,6 +418,7 @@ jobs: "$CC" -shared -Wall -Werror -fPIC -o prebuilt/structtest.so testdata/structtest/struct_test.c "$CC" -shared -Wall -Werror -fPIC -o prebuilt/structreturntest.so testdata/structtest/structreturn_test.c "$CC" -shared -Wall -Werror -fPIC -o prebuilt/libcbtest.so testdata/libcbtest/callback_test.c + "$CC" -shared -Wall -Werror -fPIC -pthread -o prebuilt/libwordcbtest.so testdata/libcbtest/word_callback_test.c "$CC" -shared -Wall -Werror -fPIC -o prebuilt/abitest.so testdata/abitest/abi_test.c env GOOS=android GOARCH=amd64 CGO_ENABLED=1 CC="$CC" go test -c -o purego.test . diff --git a/callback_word_test.go b/callback_word_test.go new file mode 100644 index 00000000..75baa92d --- /dev/null +++ b/callback_word_test.go @@ -0,0 +1,362 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2026 The Ebitengine Authors + +//go:build darwin || freebsd || illumos || netbsd || (linux && (386 || amd64 || arm || arm64 || loong64 || ppc64le || riscv64 || s390x)) + +package purego_test + +import ( + "fmt" + "path/filepath" + "runtime" + "sync" + "testing" + + "github.com/ebitengine/purego" + "github.com/ebitengine/purego/internal/testlib" +) + +type wordCallbackCaller func(uintptr, int32, *uintptr, uintptr) uintptr + +type wordCallbackLibrary struct { + call wordCallbackCaller + thread func(uintptr, *uintptr) int32 + caller uintptr +} + +func loadWordCallbackLibrary(t testing.TB) wordCallbackLibrary { + t.Helper() + path := filepath.Join(t.TempDir(), "libwordcbtest.so") + if err := testlib.BuildSharedLib(t, "CC", path, "testdata/libcbtest/word_callback_test.c", "-pthread"); err != nil { + t.Fatal(err) + } + library, err := purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_LOCAL) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := purego.Dlclose(library); err != nil { + t.Error(err) + } + }) + caller, err := purego.Dlsym(library, "callWordCallback") + if err != nil { + t.Fatal(err) + } + lib := wordCallbackLibrary{caller: caller} + purego.RegisterFunc(&lib.call, caller) + purego.RegisterLibFunc(&lib.thread, library, "callWordCallbackOnThread") + return lib +} + +func hashWords(values ...uintptr) uintptr { + hash := uintptr(0x9e37) + for i, value := range values { + hash = (hash^value)*33 + uintptr(i) + } + return hash +} + +func wordCallbacks() []any { + return []any{ + func() uintptr { return hashWords() }, + func(a uintptr) uintptr { return hashWords(a) }, + func(a, b uintptr) uintptr { return hashWords(a, b) }, + func(a, b, c uintptr) uintptr { return hashWords(a, b, c) }, + func(a, b, c, d uintptr) uintptr { return hashWords(a, b, c, d) }, + func(a, b, c, d, e uintptr) uintptr { return hashWords(a, b, c, d, e) }, + func(a, b, c, d, e, f uintptr) uintptr { return hashWords(a, b, c, d, e, f) }, + func(a, b, c, d, e, f, g uintptr) uintptr { return hashWords(a, b, c, d, e, f, g) }, + func(a, b, c, d, e, f, g, h uintptr) uintptr { return hashWords(a, b, c, d, e, f, g, h) }, + func(a, b, c, d, e, f, g, h, i uintptr) uintptr { return hashWords(a, b, c, d, e, f, g, h, i) }, + } +} + +// NewCallback owns its slots for the process lifetime. Reuse test callbacks +// across tests, benchmark calibration, and repeated -count runs. +var registeredWordCallbacks = sync.OnceValue(func() []uintptr { + var callbacks []uintptr + for _, fn := range wordCallbacks() { + callbacks = append(callbacks, purego.NewCallback(fn)) + } + return callbacks +}) + +func TestWordCallbacks(t *testing.T) { + call := loadWordCallbackLibrary(t).call + for count, callback := range registeredWordCallbacks() { + t.Run(fmt.Sprintf("%dargs", count), func(t *testing.T) { + for _, highBits := range []uintptr{0, ^uintptr(0)} { + var args [9]uintptr + for i := range args { + args[i] = highBits ^ uintptr(1< 1: panic("purego: callbacks can only have one return") } + call := tryFastPath(fn) + if call == nil { + call = func(a *callbackArgs) { + callbackWrapReflect(a, val) + } + } cbs.lock.Lock() defer cbs.lock.Unlock() if cbs.numFn >= maxCB { panic("purego: the maximum number of callbacks has been reached") } - cbs.funcs[cbs.numFn] = val + // Publish an immutable invoker before exposing its native address. Readers + // need no registration lock, and the slot keeps the Go closure alive. + cbs.funcs[cbs.numFn].Store(&call) cbs.numFn++ return callbackasmAddr(cbs.numFn - 1) } +// tryFastPath avoids reflect.Call for common callbacks whose arguments +// and result are uintptr. Select the typed call once at registration, leaving +// all other signatures on the existing reflection path. Do not reinterpret +// function types: pointers require garbage collector metadata, and narrow +// integers can have different ABI layouts. +func tryFastPath(fn any) func(*callbackArgs) { + switch f := fn.(type) { + case func() uintptr: + return func(a *callbackArgs) { + a.result[0] = f() + } + case func(uintptr) uintptr: + return func(a *callbackArgs) { + a.result[0] = f(a.word(0)) + } + case func(uintptr, uintptr) uintptr: + return func(a *callbackArgs) { + a.result[0] = f(a.word(0), a.word(1)) + } + case func(uintptr, uintptr, uintptr) uintptr: + return func(a *callbackArgs) { + a.result[0] = f(a.word(0), a.word(1), a.word(2)) + } + case func(uintptr, uintptr, uintptr, uintptr) uintptr: + return func(a *callbackArgs) { + a.result[0] = f(a.word(0), a.word(1), a.word(2), a.word(3)) + } + case func(uintptr, uintptr, uintptr, uintptr, uintptr) uintptr: + return func(a *callbackArgs) { + a.result[0] = f(a.word(0), a.word(1), a.word(2), a.word(3), a.word(4)) + } + case func(uintptr, uintptr, uintptr, uintptr, uintptr, uintptr) uintptr: + return func(a *callbackArgs) { + a.result[0] = f(a.word(0), a.word(1), a.word(2), a.word(3), a.word(4), a.word(5)) + } + case func(uintptr, uintptr, uintptr, uintptr, uintptr, uintptr, uintptr) uintptr: + return func(a *callbackArgs) { + a.result[0] = f(a.word(0), a.word(1), a.word(2), a.word(3), a.word(4), a.word(5), a.word(6)) + } + case func(uintptr, uintptr, uintptr, uintptr, uintptr, uintptr, uintptr, uintptr) uintptr: + return func(a *callbackArgs) { + a.result[0] = f(a.word(0), a.word(1), a.word(2), a.word(3), a.word(4), a.word(5), a.word(6), a.word(7)) + } + case func(uintptr, uintptr, uintptr, uintptr, uintptr, uintptr, uintptr, uintptr, uintptr) uintptr: + return func(a *callbackArgs) { + a.result[0] = f(a.word(0), a.word(1), a.word(2), a.word(3), a.word(4), a.word(5), a.word(6), a.word(7), a.word(8)) + } + default: + return nil + } +} + +// word reads a pointer-sized integer argument from the saved C frame. +// Such arguments occupy one full slot even on big-endian targets and Apple's +// packed stack ABI. PPC64 and S390X keep stack arguments in a separate block. +func (a *callbackArgs) word(i int) uintptr { + if i < numOfIntegerRegisters() { + return *(*uintptr)(a.integerRegister(i)) + } + if stack := a.stackFrame(); stack != nil { + return *(*uintptr)(unsafe.Add(stack, uintptr(i-numOfIntegerRegisters())*ptrSize)) + } + return *(*uintptr)(unsafe.Add(a.args, uintptr(numOfFloatRegisters()+i)*ptrSize)) +} + const ptrSize = unsafe.Sizeof((*int)(nil)) const callbackMaxFrame = 64 * ptrSize @@ -129,25 +207,30 @@ var callbackasmAddrs [maxCB]uintptr var callbackWrap_call = callbackWrap // callbackWrap is called by assembly code which determines which Go function to call. -// This function takes the arguments and passes them to the Go function and returns the result. +// It dispatches to the invoker registered for a.index, which is either a typed fast +// path from tryFastPath or callbackWrapReflect. func callbackWrap(a *callbackArgs) { - cbs.lock.Lock() - fn := cbs.funcs[a.index] - cbs.lock.Unlock() + (*cbs.funcs[a.index].Load())(a) +} + +// integerRegister locates a saved integer register for both dispatch paths. +func (a *callbackArgs) integerRegister(i int) unsafe.Pointer { + return unsafe.Add(a.args, uintptr(numOfFloatRegisters()+i)*ptrSize) +} + +// callbackWrapReflect reads the arguments from the saved C frame, calls fn through +// reflection, and stores the result in a. +func callbackWrapReflect(a *callbackArgs, fn reflect.Value) { fnType := fn.Type() args := make([]reflect.Value, fnType.NumIn()) frame := (*[callbackMaxFrame]uintptr)(a.args) // stackFrame points to stack-passed arguments. On most architectures this is // contiguous with frame (after register args), but on ppc64le it's separate. var stackFrame *[callbackMaxFrame]uintptr - var intFrame *[callbackMaxFrame]uintptr if sf := a.stackFrame(); sf != nil { // Only ppc64le uses separate stackArgs pointer due to NOSPLIT constraints stackFrame = (*[callbackMaxFrame]uintptr)(sf) } - if intf := a.intFrame(); intf != nil { - intFrame = (*[callbackMaxFrame]uintptr)(intf) - } // floatsN and intsN track the number of register slots used, not argument count. // This distinction matters on ARM32 where float64 uses 2 slots (32-bit registers). var floatsN int @@ -270,17 +353,12 @@ func callbackWrap(a *callbackArgs) { stackSlot += slots } } else { - if intFrame != nil { - args[i] = reflect.NewAt(inType, unsafe.Pointer(&intFrame[intsN])).Elem() + ptr := a.integerRegister(intsN) + if runtime.GOARCH == "s390x" { + // s390x big-endian: sub-8-byte values are right-justified in GPR slot. + args[i] = callbackArgFromSlotBigEndian(ptr, inType) } else { - // the integers begin after the floats in frame - pos := intsN + numOfFloatRegisters() - if runtime.GOARCH == "s390x" { - // s390x big-endian: sub-8-byte values are right-justified in GPR slot - args[i] = callbackArgFromSlotBigEndian(unsafe.Pointer(&frame[pos]), inType) - } else { - args[i] = reflect.NewAt(inType, unsafe.Pointer(&frame[pos])).Elem() - } + args[i] = reflect.NewAt(inType, ptr).Elem() } } intsN += slots diff --git a/testdata/libcbtest/word_callback_test.c b/testdata/libcbtest/word_callback_test.c new file mode 100644 index 00000000..0f3459b2 --- /dev/null +++ b/testdata/libcbtest/word_callback_test.c @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: 2026 The Ebitengine Authors + +#include +#include + +// Invoke callbacks with enough arguments to exercise both integer registers and +// stack arguments. Keeping the loop in C isolates native-to-Go callback costs. +uintptr_t callWordCallback(uintptr_t callback, int count, + const uintptr_t *args, uintptr_t iterations) { + uintptr_t result = 0; + for (uintptr_t i = 0; i < iterations; i++) { + switch (count) { + case 0: + result += ((uintptr_t (*)(void))callback)(); + break; + case 1: + result += ((uintptr_t (*)(uintptr_t))callback)(args[0]); + break; + case 2: + result += ((uintptr_t (*)(uintptr_t, uintptr_t))callback)(args[0], args[1]); + break; + case 3: + result += ((uintptr_t (*)(uintptr_t, uintptr_t, uintptr_t))callback)(args[0], args[1], args[2]); + break; + case 4: + result += ((uintptr_t (*)(uintptr_t, uintptr_t, uintptr_t, uintptr_t))callback)( + args[0], args[1], args[2], args[3]); + break; + case 5: + result += ((uintptr_t (*)(uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t))callback)( + args[0], args[1], args[2], args[3], args[4]); + break; + case 6: + result += ((uintptr_t (*)(uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t))callback)( + args[0], args[1], args[2], args[3], args[4], args[5]); + break; + case 7: + result += ((uintptr_t (*)(uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t))callback)( + args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + case 8: + result += ((uintptr_t (*)(uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t))callback)( + args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); + break; + case 9: + result += ((uintptr_t (*)(uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t))callback)( + args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); + break; + } + } + return result; +} + +struct word_callback_thread { + uintptr_t callback; + uintptr_t result; +}; + +static void *runWordCallback(void *arg) { + struct word_callback_thread *state = arg; + state->result = ((uintptr_t (*)(void))state->callback)(); + return NULL; +} + +int callWordCallbackOnThread(uintptr_t callback, uintptr_t *result) { + struct word_callback_thread state = {callback, 0}; + pthread_t thread; + int rc = pthread_create(&thread, NULL, runWordCallback, &state); + if (rc != 0) { + return rc; + } + rc = pthread_join(thread, NULL); + if (rc == 0) { + *result = state.result; + } + return rc; +}