Repository navigation
Expand file tree
/
Copy pathslow_test.go
More file actions
596 lines (501 loc) · 13.4 KB
/
Copy pathslow_test.go
File metadata and controls
596 lines (501 loc) · 13.4 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
// Copyright (C) 2019-2026 GoRE Authors.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build slow_test
package gore
import (
"bytes"
"fmt"
goversion "go/version"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var dynResources = []struct {
os string
arch string
}{
{"linux", "386"},
{"linux", "amd64"},
{"windows", "386"},
{"windows", "amd64"},
{"darwin", "arm64"},
}
var dynResourceFiles *testFiles
type testFiles struct {
files sync.Map
}
func (f *testFiles) get(os, arch string, pie, stripped bool) string {
name := os + "-" + arch
if pie {
name += "-pie"
}
if !stripped {
name += "-nostrip"
}
exe, ok := f.files.Load(name)
if !ok {
return ""
}
return exe.(string)
}
// pass nil to check means all combinations
func getMatrix(t *testing.T, checkPie, checkStrip *bool, prefix string, cb func(*testing.T, string)) {
t.Helper()
for _, r := range dynResources {
var pieCases []bool
if checkPie != nil {
pieCases = append(pieCases, *checkPie)
} else {
pieCases = append(pieCases, true, false)
}
for _, pie := range pieCases {
var strippedCases []bool
if checkStrip != nil {
strippedCases = append(strippedCases, *checkStrip)
} else {
strippedCases = append(strippedCases, true, false)
}
for _, stripped := range strippedCases {
exe := dynResourceFiles.get(r.os, r.arch, pie, stripped)
name := r.os + "-" + r.arch
if pie {
name += "-pie"
}
if !stripped {
name += "-nostrip"
}
t.Run(prefix+"-"+name, func(tt *testing.T) {
tt.Parallel()
if exe == "" {
tt.Skip("no executable available")
}
cb(tt, exe)
})
}
}
}
}
func TestMain(m *testing.M) {
fmt.Println("Creating test resources, this can take some time...")
var tmpDirs []string
resultChan := make(chan buildResult)
wg := &sync.WaitGroup{}
dynResourceFiles = &testFiles{files: sync.Map{}}
go func() {
for r := range resultChan {
tmpDirs = append(tmpDirs, r.dir)
name := r.os + "-" + r.arch
if r.pie {
name += "-pie"
}
if !r.strip {
name += "-nostrip"
}
dynResourceFiles.files.Store(name, r.exe)
}
}()
for _, r := range dynResources {
fmt.Printf("Building resource file for %s_%s\n", r.os, r.arch)
for _, pie := range []bool{false, true} {
for _, stripped := range []bool{false, true} {
if pie && r.arch == "386" && r.os == "linux" {
// seems impossible
continue
}
wg.Add(1)
go buildTestResource(testresourcesrc, r.os, r.arch, pie, stripped, wg, resultChan)
}
}
}
wg.Wait()
close(resultChan)
fmt.Println("Launching tests")
code := m.Run()
fmt.Println("Clean up test resources")
for _, d := range tmpDirs {
os.RemoveAll(d)
}
os.Exit(code)
}
func TestOpenAndCloseFile(t *testing.T) {
getMatrix(t, nil, nil, "open", func(t *testing.T, exe string) {
a := assert.New(t)
f, err := Open(exe)
a.NoError(err)
a.NotNil(f)
a.NoError(f.Close())
})
}
func TestWasmOpen(t *testing.T) {
for _, goos := range []string{"js", "wasip1"} {
t.Run(goos, func(t *testing.T) {
wasmPath := filepath.Join(t.TempDir(), "gore-test.wasm")
cmd := exec.Command("go", "build", "-o", wasmPath, "./testdata/wasm")
cmd.Env = append(os.Environ(), "GOOS="+goos, "GOARCH=wasm", "CGO_ENABLED=0")
output, err := cmd.CombinedOutput()
require.NoError(t, err, string(output))
file, err := Open(wasmPath)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, file.Close()) })
require.Equal(t, ArchWASM, file.FileInfo.Arch)
require.Equal(t, goos, file.FileInfo.OS)
require.Equal(t, intSize64, file.FileInfo.WordSize)
require.NotEmpty(t, file.BuildID)
version, err := file.GetCompilerVersion()
require.NoError(t, err)
require.NotNil(t, version)
require.True(t, goversion.IsValid(version.Name), "invalid Go version %q", version.Name)
require.NotNil(t, file.BuildInfo)
require.NotNil(t, file.BuildInfo.ModInfo)
require.Equal(t, version.Name, file.BuildInfo.ModInfo.GoVersion)
packages, err := file.GetPackages()
require.NoError(t, err)
require.NotEmpty(t, packages)
standardLibrary, err := file.GetSTDLib()
require.NoError(t, err)
require.NotEmpty(t, standardLibrary)
types, err := file.GetTypes()
require.NoError(t, err)
require.NotEmpty(t, types)
moduledata, err := file.Moduledata()
require.NoError(t, err)
typeLinks, err := moduledata.TypeLinkData()
require.NoError(t, err)
require.NotEmpty(t, typeLinks)
parsed, ok := file.GetParsedFile().(WasmInfo)
require.True(t, ok)
require.NotNil(t, parsed.Module)
require.NotEmpty(t, parsed.Memory)
_, err = file.fh.getDwarf()
require.ErrorIs(t, err, ErrUnsupportedDwarf)
raw, err := os.ReadFile(wasmPath)
require.NoError(t, err)
readerFile, err := OpenReader(bytes.NewReader(raw))
require.NoError(t, err)
require.NoError(t, readerFile.Close())
})
}
}
func TestGetPackages(t *testing.T) {
getMatrix(t, nil, nil, "getPackages", func(t *testing.T, exe string) {
a := assert.New(t)
r := require.New(t)
f, err := Open(exe)
r.NoError(err)
r.NotNil(f)
defer f.Close()
std, err := f.GetSTDLib()
a.NoError(err)
a.NotEmpty(std, "Should have a list of standard library packages.")
_, err = f.GetGeneratedPackages()
a.NoError(err)
// XXX: This check appears to be unstable. Sometimes files for unknown reason.
// assert.NotEmpty(gen, "Should have a list of generated packages.")
ven, err := f.GetVendors()
a.NoError(err)
a.Empty(ven, "Should not have a list of vendor packages.")
_, err = f.GetUnknown()
a.NoError(err)
// XXX: This check appears to be unstable. Sometimes files for unknown reason.
// assert.Empty(unk, "Should not have a list of unknown packages")
pkgs, err := f.GetPackages()
a.NoError(err)
var mainpkg *Package
for _, p := range pkgs {
if p.Name == "main" {
mainpkg = p
break
}
}
mainPackageFound := false
getDataFuncFound := false
a.NotNil(mainpkg, "Should include main package")
for _, f := range mainpkg.Functions {
if f.Name == "main" {
mainPackageFound = true
} else if f.Name == "getData" {
getDataFuncFound = true
} else {
a.Fail("Unexpected function")
}
}
a.True(mainPackageFound, "No main function found")
a.True(getDataFuncFound, "getData function not found")
})
}
func TestGetTypesFromDynamicBuiltResources(t *testing.T) {
getMatrix(t, nil, nil, "getTypes", func(t *testing.T, exe string) {
a := assert.New(t)
r := require.New(t)
f, err := Open(exe)
r.NoError(err)
r.NotNil(f)
defer f.Close()
typs, err := f.GetTypes()
r.NoError(err)
var stringer *GoType
for _, t := range typs {
if t.PackagePath == "runtime" && t.Name == "runtime.g" {
stringer = t
break
}
}
a.NotNil(stringer, "the g type from runtime not found")
})
}
func TestSwissMapTypes(t *testing.T) {
testVersion := testCompilerVersion()
if GoVersionCompare(testVersion, "go1.24") < 0 {
t.Skipf("current Go toolchain %s does not support swiss maps", testVersion)
}
build := buildSingleTestResource(t, go126SwissMapTestSrc)
f, err := Open(build.exe)
require.NoError(t, err)
defer f.Close()
typs, err := f.GetTypes()
require.NoError(t, err)
for _, typ := range typs {
if typ.Name != "main.namedMap" || typ.Kind != reflect.Map {
continue
}
require.NotNil(t, typ.Key)
require.NotNil(t, typ.Element)
assert.Equal(t, reflect.String, typ.Key.Kind)
assert.Equal(t, reflect.Int, typ.Element.Kind)
require.Len(t, typ.Methods, 1)
assert.Equal(t, "Touch", typ.Methods[0].Name)
return
}
t.Fatal("main.namedMap was not found")
}
func TestGo127TypeLinkOffsetsMatchRuntime(t *testing.T) {
if !usesGo127TypeLayout(testCompilerVersion()) {
t.Skip("type descriptors were introduced in Go 1.27")
}
build := buildSingleTestResource(t, go127TypeLinksTestSrc)
output, err := exec.Command(build.exe).Output()
require.NoError(t, err)
rawOffsets := strings.Split(strings.TrimSpace(string(output)), ",")
expected := make([]int32, 0, len(rawOffsets))
for _, raw := range rawOffsets {
offset, err := strconv.ParseInt(raw, 10, 32)
require.NoError(t, err)
expected = append(expected, int32(offset))
}
require.NotEmpty(t, expected)
file, err := Open(build.exe)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, file.Close()) })
moduledata, err := file.Moduledata()
require.NoError(t, err)
actual, err := moduledata.TypeLinkData()
require.NoError(t, err)
require.Equal(t, expected, actual)
}
func TestGetCompilerVersion(t *testing.T) {
testVersion := testCompilerVersion()
expectedVersion := ResolveGoVersion(testVersion)
// If the version could not be resolved, the version is new
// and the library doesn't know about it. Use the version string
// to create a new version.
if expectedVersion == nil {
expectedVersion = &GoVersion{Name: testVersion}
}
getMatrix(t, nil, nil, "compiler-version", func(t *testing.T, exe string) {
a := assert.New(t)
r := require.New(t)
f, err := Open(exe)
r.NoError(err)
r.NotNil(f)
defer f.Close()
// Test
version, err := f.GetCompilerVersion()
a.NoError(err)
a.Equal(expectedVersion, version)
})
}
func TestGetBuildID(t *testing.T) {
getMatrix(t, nil, nil, "buildID", func(t *testing.T, exe string) {
a := assert.New(t)
r := require.New(t)
f, err := Open(exe)
r.NoError(err)
r.NotNil(f)
defer f.Close()
a.Equal(fixedBuildID, f.BuildID, "BuildID extracted doesn't match expected value.")
})
}
func TestSourceInfo(t *testing.T) {
getMatrix(t, nil, nil, "sourceInfo", func(t *testing.T, exe string) {
a := assert.New(t)
r := require.New(t)
f, err := Open(exe)
r.NoError(err)
r.NotNil(f)
defer f.Close()
var testFn *Function
pkgs, err := f.GetPackages()
r.NoError(err)
for _, pkg := range pkgs {
if pkg.Name != "main" {
continue
}
for _, fn := range pkg.Functions {
if fn.Name != "getData" {
continue
}
testFn = fn
break
}
}
r.NotNil(testFn)
file, start, end := f.SourceInfo(testFn)
a.NotEqual(0, start)
a.NotEqual(0, end)
a.NotEqual("", file)
})
}
func TestDwarfString(t *testing.T) {
noStrip := false
getMatrix(t, nil, &noStrip, "dwarfString", func(t *testing.T, exe string) {
r := require.New(t)
f, err := Open(exe)
r.NoError(err)
r.NotNil(f)
defer f.Close()
gover, ok := getBuildVersionFromDwarf(f.fh)
r.True(ok)
r.Equal(gover, runtime.Version())
goroot, ok := getGoRootFromDwarf(f.fh)
r.True(ok)
r.Equal(goroot, runtime.GOROOT())
})
}
type buildResult struct {
exe string
dir string
strip bool
pie bool
os string
arch string
}
func buildTestResource(body, goos, arch string, pie, stripped bool, wg *sync.WaitGroup, result chan buildResult) {
defer wg.Done()
goBin, err := exec.LookPath("go")
if err != nil {
panic("No go tool chain found: " + err.Error())
}
tmpdir, err := os.MkdirTemp("", "gore-test")
if err != nil {
panic(err)
}
src := filepath.Join(tmpdir, "a.go")
err = os.WriteFile(src, []byte(body), 0644)
if err != nil {
panic(err)
}
exe := filepath.Join(tmpdir, "a")
if runtime.GOOS == "windows" {
exe += ".exe"
}
var ldFlags string
if stripped {
ldFlags = "-s -w "
}
ldFlags += "-buildid=" + fixedBuildID
args := []string{"build", "-o", exe, "-ldflags", ldFlags}
if pie {
args = append(args, "-buildmode=pie")
} else {
// Windows use pie by default
args = append(args, "-buildmode=exe")
}
args = append(args, src)
cmd := exec.Command(goBin, args...)
gopath := os.Getenv("GOPATH")
if gopath == "" {
gopath = tmpdir
}
cmd.Env = append(cmd.Env, "GOCACHE="+tmpdir, "GOARCH="+arch, "GOOS="+goos, "GOPATH="+gopath, "GOTMPDIR="+gopath, "PATH="+os.Getenv("PATH"))
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Printf("building test executable failed: %s\n", string(out))
os.Exit(1)
}
result <- buildResult{exe: exe, dir: tmpdir, strip: stripped, pie: pie, os: goos, arch: arch}
}
func buildSingleTestResource(t *testing.T, body string) buildResult {
t.Helper()
resultChan := make(chan buildResult, 1)
wg := &sync.WaitGroup{}
wg.Add(1)
go buildTestResource(body, runtime.GOOS, runtime.GOARCH, false, false, wg, resultChan)
wg.Wait()
close(resultChan)
result, ok := <-resultChan
require.True(t, ok, "no test resource was built")
t.Cleanup(func() {
os.RemoveAll(result.dir)
})
return result
}
func testCompilerVersion() string {
goBin, err := exec.LookPath("go")
if err != nil {
panic("No go tool chain found: " + err.Error())
}
out, err := exec.Command(goBin, "version").CombinedOutput()
if err != nil {
panic("Getting compiler version failed: " + string(out))
}
return strings.Split(string(out), " ")[2]
}
const go126SwissMapTestSrc = `package main
import "reflect"
type namedMap map[string]int
func (m namedMap) Touch() int {
return m["answer"]
}
type mapHolder struct {
M namedMap
}
var sink any
func main() {
h := mapHolder{M: namedMap{"answer": 42}}
sink = reflect.TypeOf(h)
sink = reflect.TypeOf(h.M)
sink = h.M.Touch()
}
`
const go127TypeLinksTestSrc = `package main
import (
"fmt"
_ "reflect"
"unsafe"
)
//go:linkname typeLinks reflect.typelinks
func typeLinks() ([]unsafe.Pointer, [][]int32)
func main() {
_, modules := typeLinks()
first := true
for _, offsets := range modules {
for _, offset := range offsets {
if !first {
fmt.Print(",")
}
first = false
fmt.Print(offset)
}
}
}
`