1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2023 The Ebitengine Authors
3
4package purego_test
5
6import (
7 "errors"
8 "fmt"
9 "os/exec"
10 "path/filepath"
11 "runtime"
12 "strings"
13 "testing"
14 "unsafe"
15
16 "github.com/ebitengine/purego"
17 "github.com/ebitengine/purego/internal/load"
18)
19
20func getSystemLibrary() (string, error) {
21 switch runtime.GOOS {
22 case "darwin":
23 return "/usr/lib/libSystem.B.dylib", nil
24 case "freebsd":
25 return "libc.so.7", nil
26 case "linux":
27 return "libc.so.6", nil
28 case "netbsd":
29 return "libc.so", nil
30 case "windows":
31 return "ucrtbase.dll", nil
32 default:
33 return "", fmt.Errorf("GOOS=%s is not supported", runtime.GOOS)
34 }
35}
36
37func TestRegisterFunc(t *testing.T) {
38 library, err := getSystemLibrary()
39 if err != nil {
40 t.Fatalf("couldn't get system library: %s", err)
41 }
42 libc, err := load.OpenLibrary(library)
43 if err != nil {
44 t.Fatalf("failed to dlopen: %s", err)
45 }
46 var puts func(string)
47 purego.RegisterLibFunc(&puts, libc, "puts")
48 puts("Calling C from from Go without Cgo!")
49}
50
51func Test_qsort(t *testing.T) {
52 if runtime.GOARCH != "arm64" && runtime.GOARCH != "amd64" && runtime.GOARCH != "loong64" {
53 t.Skip("Platform doesn't support Floats")
54 return
55 }
56 library, err := getSystemLibrary()
57 if err != nil {
58 t.Fatalf("couldn't get system library: %s", err)
59 }
60 libc, err := load.OpenLibrary(library)
61 if err != nil {
62 t.Fatalf("failed to dlopen: %s", err)
63 }
64
65 data := []int{88, 56, 100, 2, 25}
66 sorted := []int{2, 25, 56, 88, 100}
67 compare := func(_ purego.CDecl, a, b *int) int {
68 return *a - *b
69 }
70 var qsort func(data []int, nitms uintptr, size uintptr, compar func(_ purego.CDecl, a, b *int) int)
71 purego.RegisterLibFunc(&qsort, libc, "qsort")
72 qsort(data, uintptr(len(data)), unsafe.Sizeof(int(0)), compare)
73 for i := range data {
74 if data[i] != sorted[i] {
75 t.Errorf("got %d wanted %d at %d", data[i], sorted[i], i)
76 }
77 }
78}
79
80func TestRegisterFunc_Floats(t *testing.T) {
81 if runtime.GOARCH != "arm64" && runtime.GOARCH != "amd64" && runtime.GOARCH != "loong64" {
82 t.Skip("Platform doesn't support Floats")
83 return
84 }
85 library, err := getSystemLibrary()
86 if err != nil {
87 t.Fatalf("couldn't get system library: %s", err)
88 }
89 libc, err := load.OpenLibrary(library)
90 if err != nil {
91 t.Fatalf("failed to dlopen: %s", err)
92 }
93 {
94 var strtof func(arg string) float32
95 purego.RegisterLibFunc(&strtof, libc, "strtof")
96 const (
97 arg = "2"
98 )
99 got := strtof(arg)
100 expected := float32(2)
101 if got != expected {
102 t.Errorf("strtof failed. got %f but wanted %f", got, expected)
103 }
104 }
105 {
106 var strtod func(arg string, ptr **byte) float64
107 purego.RegisterLibFunc(&strtod, libc, "strtod")
108 const (
109 arg = "1"
110 )
111 got := strtod(arg, nil)
112 expected := float64(1)
113 if got != expected {
114 t.Errorf("strtod failed. got %f but wanted %f", got, expected)
115 }
116 }
117}
118
119func TestRegisterLibFunc_Bool(t *testing.T) {
120 if runtime.GOARCH != "arm64" && runtime.GOARCH != "amd64" && runtime.GOARCH != "loong64" {
121 t.Skip("Platform doesn't support callbacks")
122 return
123 }
124 // this callback recreates the state where the return register
125 // contains other information but the least significant byte is false
126 cbFalse := purego.NewCallback(func() uintptr {
127 x := uint64(0x7F5948AE9A00)
128 return uintptr(x)
129 })
130 var runFalse func() bool
131 purego.RegisterFunc(&runFalse, cbFalse)
132 expected := false
133 if got := runFalse(); got != expected {
134 t.Errorf("runFalse failed. got %t but wanted %t", got, expected)
135 }
136}
137
138func TestABI(t *testing.T) {
139 if runtime.GOOS == "windows" && runtime.GOARCH == "386" {
140 t.Skip("need a 32bit gcc to run this test") // TODO: find 32bit gcc for test
141 }
142 libFileName := filepath.Join(t.TempDir(), "abitest.so")
143 t.Logf("Build %v", libFileName)
144
145 if err := buildSharedLib("CC", libFileName, filepath.Join("testdata", "abitest", "abi_test.c")); err != nil {
146 t.Fatal(err)
147 }
148
149 lib, err := load.OpenLibrary(libFileName)
150 if err != nil {
151 t.Fatalf("Dlopen(%q) failed: %v", libFileName, err)
152 }
153 defer func() {
154 if err := load.CloseLibrary(lib); err != nil {
155 t.Fatalf("failed to close library: %s", err)
156 }
157 }()
158 {
159 const cName = "stack_uint8_t"
160 const expect = 2047
161 var fn func(a, b, c, d, e, f, g, h uint32, i, j uint8, k uint32) uint32
162 purego.RegisterLibFunc(&fn, lib, cName)
163 res := fn(256, 512, 4, 8, 16, 32, 64, 128, 1, 2, 1024)
164 if res != expect {
165 t.Fatalf("%s: got %d, want %d", cName, res, expect)
166 }
167 }
168 {
169 const cName = "reg_uint8_t"
170 const expect = 1027
171 var fn func(a, b uint8, c uint32) uint32
172 purego.RegisterLibFunc(&fn, lib, cName)
173 res := fn(1, 2, 1024)
174 if res != expect {
175 t.Fatalf("%s: got %d, want %d", cName, res, expect)
176 }
177 }
178 {
179 const cName = "stack_string"
180 const expect = 255
181 var fn func(a, b, c, d, e, f, g, h uint32, i string) uint32
182 purego.RegisterLibFunc(&fn, lib, cName)
183 res := fn(1, 2, 4, 8, 16, 32, 64, 128, "test")
184 if res != expect {
185 t.Fatalf("%s: got %d, want %d", cName, res, expect)
186 }
187 }
188 {
189 const cName = "stack_8i32_3strings"
190 var fn func(*byte, uintptr, int32, int32, int32, int32, int32, int32, int32, int32, string, string, string)
191 purego.RegisterLibFunc(&fn, lib, cName)
192 buf := make([]byte, 256)
193 fn(&buf[0], uintptr(len(buf)), 1, 2, 3, 4, 5, 6, 7, 8, "foo", "bar", "baz")
194 res := string(buf[:strings.IndexByte(string(buf), 0)])
195 const want = "1:2:3:4:5:6:7:8:foo:bar:baz"
196 if res != want {
197 t.Fatalf("%s: got %q, want %q", cName, res, want)
198 }
199 }
200}
201
202func buildSharedLib(compilerEnv, libFile string, sources ...string) error {
203 out, err := exec.Command("go", "env", compilerEnv).Output()
204 if err != nil {
205 return fmt.Errorf("go env %s error: %w", compilerEnv, err)
206 }
207
208 compiler := strings.TrimSpace(string(out))
209 if compiler == "" {
210 return errors.New("compiler not found")
211 }
212
213 args := []string{"-shared", "-Wall", "-Werror", "-fPIC", "-o", libFile}
214 if runtime.GOARCH == "386" {
215 args = append(args, "-m32")
216 }
217 // macOS arm64 can run amd64 tests through Rossetta.
218 // Build the shared library based on the GOARCH and not
219 // the default behavior of the compiler.
220 if runtime.GOOS == "darwin" {
221 var arch string
222 switch runtime.GOARCH {
223 case "arm64":
224 arch = "arm64"
225 case "amd64":
226 arch = "x86_64"
227 default:
228 return fmt.Errorf("unknown macOS architecture %s", runtime.GOARCH)
229 }
230 args = append(args, "-arch", arch)
231 }
232 cmd := exec.Command(compiler, append(args, sources...)...)
233 if out, err := cmd.CombinedOutput(); err != nil {
234 return fmt.Errorf("compile lib: %w\n%q\n%s", err, cmd, string(out))
235 }
236
237 return nil
238}