]> Cypherpunks.ru repositories - gostls13.git/blob - misc/cgo/testshared/shared_test.go
634d7556a8f9d8073adcf6fd23f1677616b401bd
[gostls13.git] / misc / cgo / testshared / shared_test.go
1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package shared_test
6
7 import (
8         "bufio"
9         "bytes"
10         "debug/elf"
11         "encoding/binary"
12         "flag"
13         "fmt"
14         "go/build"
15         "io"
16         "log"
17         "os"
18         "os/exec"
19         "path/filepath"
20         "regexp"
21         "runtime"
22         "sort"
23         "strconv"
24         "strings"
25         "testing"
26         "time"
27 )
28
29 var gopathInstallDir, gorootInstallDir string
30 var oldGOROOT string
31
32 // This is the smallest set of packages we can link into a shared
33 // library (runtime/cgo is built implicitly).
34 var minpkgs = []string{"runtime", "sync/atomic"}
35 var soname = "libruntime,sync-atomic.so"
36
37 var testX = flag.Bool("testx", false, "if true, pass -x to 'go' subcommands invoked by the test")
38 var testWork = flag.Bool("testwork", false, "if true, log and do not delete the temporary working directory")
39
40 // run runs a command and calls t.Errorf if it fails.
41 func run(t *testing.T, msg string, args ...string) {
42         runWithEnv(t, msg, nil, args...)
43 }
44
45 // runWithEnv runs a command under the given environment and calls t.Errorf if it fails.
46 func runWithEnv(t *testing.T, msg string, env []string, args ...string) {
47         c := exec.Command(args[0], args[1:]...)
48         if len(env) != 0 {
49                 c.Env = append(os.Environ(), env...)
50         }
51         if output, err := c.CombinedOutput(); err != nil {
52                 t.Errorf("executing %s (%s) failed %s:\n%s", strings.Join(args, " "), msg, err, output)
53         }
54 }
55
56 // goCmd invokes the go tool with the installsuffix set up by TestMain. It calls
57 // t.Fatalf if the command fails.
58 func goCmd(t *testing.T, args ...string) string {
59         newargs := []string{args[0]}
60         if *testX && args[0] != "env" {
61                 newargs = append(newargs, "-x", "-ldflags=-v")
62         }
63         newargs = append(newargs, args[1:]...)
64         c := exec.Command(filepath.Join(oldGOROOT, "bin", "go"), newargs...)
65         stderr := new(strings.Builder)
66         c.Stderr = stderr
67
68         if testing.Verbose() && t == nil {
69                 fmt.Fprintf(os.Stderr, "+ go %s\n", strings.Join(args, " "))
70                 c.Stderr = os.Stderr
71         }
72         output, err := c.Output()
73
74         if err != nil {
75                 if t != nil {
76                         t.Helper()
77                         t.Fatalf("executing %s failed %v:\n%s", strings.Join(c.Args, " "), err, stderr)
78                 } else {
79                         // Panic instead of using log.Fatalf so that deferred cleanup may run in testMain.
80                         log.Panicf("executing %s failed %v:\n%s", strings.Join(c.Args, " "), err, stderr)
81                 }
82         }
83         if testing.Verbose() && t != nil {
84                 t.Logf("go %s", strings.Join(args, " "))
85                 if stderr.Len() > 0 {
86                         t.Logf("%s", stderr)
87                 }
88         }
89         return string(bytes.TrimSpace(output))
90 }
91
92 // TestMain calls testMain so that the latter can use defer (TestMain exits with os.Exit).
93 func testMain(m *testing.M) (int, error) {
94         cwd, err := os.Getwd()
95         if err != nil {
96                 log.Fatal(err)
97         }
98         oldGOROOT = filepath.Join(cwd, "../../..")
99
100         workDir, err := os.MkdirTemp("", "shared_test")
101         if err != nil {
102                 return 0, err
103         }
104         if *testWork || testing.Verbose() {
105                 fmt.Printf("+ mkdir -p %s\n", workDir)
106         }
107         if !*testWork {
108                 defer os.RemoveAll(workDir)
109         }
110
111         // -buildmode=shared fundamentally does not work in module mode.
112         // (It tries to share package dependencies across builds, but in module mode
113         // each module has its own distinct set of dependency versions.)
114         // We would like to eliminate it (see https://go.dev/issue/47788),
115         // but first need to figure out a replacement that covers the small subset
116         // of use-cases where -buildmode=shared still works today.
117         // For now, run the tests in GOPATH mode only.
118         os.Setenv("GO111MODULE", "off")
119
120         // Some tests need to edit the source in GOPATH, so copy this directory to a
121         // temporary directory and chdir to that.
122         gopath := filepath.Join(workDir, "gopath")
123         modRoot, err := cloneTestdataModule(gopath)
124         if err != nil {
125                 return 0, err
126         }
127         if testing.Verbose() {
128                 fmt.Printf("+ export GOPATH=%s\n", gopath)
129                 fmt.Printf("+ cd %s\n", modRoot)
130         }
131         os.Setenv("GOPATH", gopath)
132         // Explicitly override GOBIN as well, in case it was set through a GOENV file.
133         os.Setenv("GOBIN", filepath.Join(gopath, "bin"))
134         os.Chdir(modRoot)
135         os.Setenv("PWD", modRoot)
136
137         // The test also needs to install libraries into GOROOT/pkg, so copy the
138         // subset of GOROOT that we need.
139         //
140         // TODO(golang.org/issue/28553): Rework -buildmode=shared so that it does not
141         // need to write to GOROOT.
142         goroot := filepath.Join(workDir, "goroot")
143         if err := cloneGOROOTDeps(goroot); err != nil {
144                 return 0, err
145         }
146         if testing.Verbose() {
147                 fmt.Fprintf(os.Stderr, "+ export GOROOT=%s\n", goroot)
148         }
149         os.Setenv("GOROOT", goroot)
150
151         myContext := build.Default
152         myContext.GOROOT = goroot
153         myContext.GOPATH = gopath
154         runtimeP, err := myContext.Import("runtime", ".", build.ImportComment)
155         if err != nil {
156                 return 0, fmt.Errorf("import failed: %v", err)
157         }
158         gorootInstallDir = runtimeP.PkgTargetRoot + "_dynlink"
159
160         // All tests depend on runtime being built into a shared library. Because
161         // that takes a few seconds, do it here and have all tests use the version
162         // built here.
163         goCmd(nil, append([]string{"install", "-buildmode=shared"}, minpkgs...)...)
164
165         myContext.InstallSuffix = "_dynlink"
166         depP, err := myContext.Import("./depBase", ".", build.ImportComment)
167         if err != nil {
168                 return 0, fmt.Errorf("import failed: %v", err)
169         }
170         if depP.PkgTargetRoot == "" {
171                 gopathInstallDir = filepath.Dir(goCmd(nil, "list", "-buildmode=shared", "-f", "{{.Target}}", "./depBase"))
172         } else {
173                 gopathInstallDir = filepath.Join(depP.PkgTargetRoot, "testshared")
174         }
175         return m.Run(), nil
176 }
177
178 func TestMain(m *testing.M) {
179         log.SetFlags(log.Lshortfile)
180         flag.Parse()
181
182         exitCode, err := testMain(m)
183         if err != nil {
184                 log.Fatal(err)
185         }
186         os.Exit(exitCode)
187 }
188
189 // cloneTestdataModule clones the packages from src/testshared into gopath.
190 // It returns the directory within gopath at which the module root is located.
191 func cloneTestdataModule(gopath string) (string, error) {
192         modRoot := filepath.Join(gopath, "src", "testshared")
193         if err := overlayDir(modRoot, "testdata"); err != nil {
194                 return "", err
195         }
196         if err := os.WriteFile(filepath.Join(modRoot, "go.mod"), []byte("module testshared\n"), 0644); err != nil {
197                 return "", err
198         }
199         return modRoot, nil
200 }
201
202 // cloneGOROOTDeps copies (or symlinks) the portions of GOROOT/src and
203 // GOROOT/pkg relevant to this test into the given directory.
204 // It must be run from within the testdata module.
205 func cloneGOROOTDeps(goroot string) error {
206         // Before we clone GOROOT, figure out which packages we need to copy over.
207         listArgs := []string{
208                 "list",
209                 "-deps",
210                 "-f", "{{if and .Standard (not .ForTest)}}{{.ImportPath}}{{end}}",
211         }
212         stdDeps := goCmd(nil, append(listArgs, minpkgs...)...)
213         testdataDeps := goCmd(nil, append(listArgs, "-test", "./...")...)
214
215         pkgs := append(strings.Split(strings.TrimSpace(stdDeps), "\n"),
216                 strings.Split(strings.TrimSpace(testdataDeps), "\n")...)
217         sort.Strings(pkgs)
218         var pkgRoots []string
219         for _, pkg := range pkgs {
220                 parentFound := false
221                 for _, prev := range pkgRoots {
222                         if strings.HasPrefix(pkg, prev) {
223                                 // We will copy in the source for pkg when we copy in prev.
224                                 parentFound = true
225                                 break
226                         }
227                 }
228                 if !parentFound {
229                         pkgRoots = append(pkgRoots, pkg)
230                 }
231         }
232
233         gorootDirs := []string{
234                 "pkg/tool",
235                 "pkg/include",
236         }
237         for _, pkg := range pkgRoots {
238                 gorootDirs = append(gorootDirs, filepath.Join("src", pkg))
239         }
240
241         for _, dir := range gorootDirs {
242                 if testing.Verbose() {
243                         fmt.Fprintf(os.Stderr, "+ cp -r %s %s\n", filepath.Join(oldGOROOT, dir), filepath.Join(goroot, dir))
244                 }
245                 if err := overlayDir(filepath.Join(goroot, dir), filepath.Join(oldGOROOT, dir)); err != nil {
246                         return err
247                 }
248         }
249
250         return nil
251 }
252
253 // The shared library was built at the expected location.
254 func TestSOBuilt(t *testing.T) {
255         _, err := os.Stat(filepath.Join(gorootInstallDir, soname))
256         if err != nil {
257                 t.Error(err)
258         }
259 }
260
261 func hasDynTag(f *elf.File, tag elf.DynTag) bool {
262         ds := f.SectionByType(elf.SHT_DYNAMIC)
263         if ds == nil {
264                 return false
265         }
266         d, err := ds.Data()
267         if err != nil {
268                 return false
269         }
270         for len(d) > 0 {
271                 var t elf.DynTag
272                 switch f.Class {
273                 case elf.ELFCLASS32:
274                         t = elf.DynTag(f.ByteOrder.Uint32(d[0:4]))
275                         d = d[8:]
276                 case elf.ELFCLASS64:
277                         t = elf.DynTag(f.ByteOrder.Uint64(d[0:8]))
278                         d = d[16:]
279                 }
280                 if t == tag {
281                         return true
282                 }
283         }
284         return false
285 }
286
287 // The shared library does not have relocations against the text segment.
288 func TestNoTextrel(t *testing.T) {
289         sopath := filepath.Join(gorootInstallDir, soname)
290         f, err := elf.Open(sopath)
291         if err != nil {
292                 t.Fatal("elf.Open failed: ", err)
293         }
294         defer f.Close()
295         if hasDynTag(f, elf.DT_TEXTREL) {
296                 t.Errorf("%s has DT_TEXTREL set", soname)
297         }
298 }
299
300 // The shared library does not contain symbols called ".dup"
301 // (See golang.org/issue/14841.)
302 func TestNoDupSymbols(t *testing.T) {
303         sopath := filepath.Join(gorootInstallDir, soname)
304         f, err := elf.Open(sopath)
305         if err != nil {
306                 t.Fatal("elf.Open failed: ", err)
307         }
308         defer f.Close()
309         syms, err := f.Symbols()
310         if err != nil {
311                 t.Errorf("error reading symbols %v", err)
312                 return
313         }
314         for _, s := range syms {
315                 if s.Name == ".dup" {
316                         t.Fatalf("%s contains symbol called .dup", sopath)
317                 }
318         }
319 }
320
321 // The install command should have created a "shlibname" file for the
322 // listed packages (and runtime/cgo, and math on arm) indicating the
323 // name of the shared library containing it.
324 func TestShlibnameFiles(t *testing.T) {
325         pkgs := append([]string{}, minpkgs...)
326         pkgs = append(pkgs, "runtime/cgo")
327         if runtime.GOARCH == "arm" {
328                 pkgs = append(pkgs, "math")
329         }
330         for _, pkg := range pkgs {
331                 shlibnamefile := filepath.Join(gorootInstallDir, pkg+".shlibname")
332                 contentsb, err := os.ReadFile(shlibnamefile)
333                 if err != nil {
334                         t.Errorf("error reading shlibnamefile for %s: %v", pkg, err)
335                         continue
336                 }
337                 contents := strings.TrimSpace(string(contentsb))
338                 if contents != soname {
339                         t.Errorf("shlibnamefile for %s has wrong contents: %q", pkg, contents)
340                 }
341         }
342 }
343
344 // Is a given offset into the file contained in a loaded segment?
345 func isOffsetLoaded(f *elf.File, offset uint64) bool {
346         for _, prog := range f.Progs {
347                 if prog.Type == elf.PT_LOAD {
348                         if prog.Off <= offset && offset < prog.Off+prog.Filesz {
349                                 return true
350                         }
351                 }
352         }
353         return false
354 }
355
356 func rnd(v int32, r int32) int32 {
357         if r <= 0 {
358                 return v
359         }
360         v += r - 1
361         c := v % r
362         if c < 0 {
363                 c += r
364         }
365         v -= c
366         return v
367 }
368
369 func readwithpad(r io.Reader, sz int32) ([]byte, error) {
370         data := make([]byte, rnd(sz, 4))
371         _, err := io.ReadFull(r, data)
372         if err != nil {
373                 return nil, err
374         }
375         data = data[:sz]
376         return data, nil
377 }
378
379 type note struct {
380         name    string
381         tag     int32
382         desc    string
383         section *elf.Section
384 }
385
386 // Read all notes from f. As ELF section names are not supposed to be special, one
387 // looks for a particular note by scanning all SHT_NOTE sections looking for a note
388 // with a particular "name" and "tag".
389 func readNotes(f *elf.File) ([]*note, error) {
390         var notes []*note
391         for _, sect := range f.Sections {
392                 if sect.Type != elf.SHT_NOTE {
393                         continue
394                 }
395                 r := sect.Open()
396                 for {
397                         var namesize, descsize, tag int32
398                         err := binary.Read(r, f.ByteOrder, &namesize)
399                         if err != nil {
400                                 if err == io.EOF {
401                                         break
402                                 }
403                                 return nil, fmt.Errorf("read namesize failed: %v", err)
404                         }
405                         err = binary.Read(r, f.ByteOrder, &descsize)
406                         if err != nil {
407                                 return nil, fmt.Errorf("read descsize failed: %v", err)
408                         }
409                         err = binary.Read(r, f.ByteOrder, &tag)
410                         if err != nil {
411                                 return nil, fmt.Errorf("read type failed: %v", err)
412                         }
413                         name, err := readwithpad(r, namesize)
414                         if err != nil {
415                                 return nil, fmt.Errorf("read name failed: %v", err)
416                         }
417                         desc, err := readwithpad(r, descsize)
418                         if err != nil {
419                                 return nil, fmt.Errorf("read desc failed: %v", err)
420                         }
421                         notes = append(notes, &note{name: string(name), tag: tag, desc: string(desc), section: sect})
422                 }
423         }
424         return notes, nil
425 }
426
427 func dynStrings(t *testing.T, path string, flag elf.DynTag) []string {
428         t.Helper()
429         f, err := elf.Open(path)
430         if err != nil {
431                 t.Fatalf("elf.Open(%q) failed: %v", path, err)
432         }
433         defer f.Close()
434         dynstrings, err := f.DynString(flag)
435         if err != nil {
436                 t.Fatalf("DynString(%s) failed on %s: %v", flag, path, err)
437         }
438         return dynstrings
439 }
440
441 func AssertIsLinkedToRegexp(t *testing.T, path string, re *regexp.Regexp) {
442         t.Helper()
443         for _, dynstring := range dynStrings(t, path, elf.DT_NEEDED) {
444                 if re.MatchString(dynstring) {
445                         return
446                 }
447         }
448         t.Errorf("%s is not linked to anything matching %v", path, re)
449 }
450
451 func AssertIsLinkedTo(t *testing.T, path, lib string) {
452         t.Helper()
453         AssertIsLinkedToRegexp(t, path, regexp.MustCompile(regexp.QuoteMeta(lib)))
454 }
455
456 func AssertHasRPath(t *testing.T, path, dir string) {
457         t.Helper()
458         for _, tag := range []elf.DynTag{elf.DT_RPATH, elf.DT_RUNPATH} {
459                 for _, dynstring := range dynStrings(t, path, tag) {
460                         for _, rpath := range strings.Split(dynstring, ":") {
461                                 if filepath.Clean(rpath) == filepath.Clean(dir) {
462                                         return
463                                 }
464                         }
465                 }
466         }
467         t.Errorf("%s does not have rpath %s", path, dir)
468 }
469
470 // Build a trivial program that links against the shared runtime and check it runs.
471 func TestTrivialExecutable(t *testing.T) {
472         goCmd(t, "install", "-linkshared", "./trivial")
473         run(t, "trivial executable", "../../bin/trivial")
474         AssertIsLinkedTo(t, "../../bin/trivial", soname)
475         AssertHasRPath(t, "../../bin/trivial", gorootInstallDir)
476         // It is 19K on linux/amd64, with separate-code in binutils ld and 64k being most common alignment
477         // 4*64k should be enough, but this might need revision eventually.
478         checkSize(t, "../../bin/trivial", 256000)
479 }
480
481 // Build a trivial program in PIE mode that links against the shared runtime and check it runs.
482 func TestTrivialExecutablePIE(t *testing.T) {
483         goCmd(t, "build", "-buildmode=pie", "-o", "trivial.pie", "-linkshared", "./trivial")
484         run(t, "trivial executable", "./trivial.pie")
485         AssertIsLinkedTo(t, "./trivial.pie", soname)
486         AssertHasRPath(t, "./trivial.pie", gorootInstallDir)
487         // It is 19K on linux/amd64, with separate-code in binutils ld and 64k being most common alignment
488         // 4*64k should be enough, but this might need revision eventually.
489         checkSize(t, "./trivial.pie", 256000)
490 }
491
492 // Check that the file size does not exceed a limit.
493 func checkSize(t *testing.T, f string, limit int64) {
494         fi, err := os.Stat(f)
495         if err != nil {
496                 t.Fatalf("stat failed: %v", err)
497         }
498         if sz := fi.Size(); sz > limit {
499                 t.Errorf("file too large: got %d, want <= %d", sz, limit)
500         }
501 }
502
503 // Build a division test program and check it runs.
504 func TestDivisionExecutable(t *testing.T) {
505         goCmd(t, "install", "-linkshared", "./division")
506         run(t, "division executable", "../../bin/division")
507 }
508
509 // Build an executable that uses cgo linked against the shared runtime and check it
510 // runs.
511 func TestCgoExecutable(t *testing.T) {
512         goCmd(t, "install", "-linkshared", "./execgo")
513         run(t, "cgo executable", "../../bin/execgo")
514 }
515
516 func checkPIE(t *testing.T, name string) {
517         f, err := elf.Open(name)
518         if err != nil {
519                 t.Fatal("elf.Open failed: ", err)
520         }
521         defer f.Close()
522         if f.Type != elf.ET_DYN {
523                 t.Errorf("%s has type %v, want ET_DYN", name, f.Type)
524         }
525         if hasDynTag(f, elf.DT_TEXTREL) {
526                 t.Errorf("%s has DT_TEXTREL set", name)
527         }
528 }
529
530 func TestTrivialPIE(t *testing.T) {
531         name := "trivial_pie"
532         goCmd(t, "build", "-buildmode=pie", "-o="+name, "./trivial")
533         defer os.Remove(name)
534         run(t, name, "./"+name)
535         checkPIE(t, name)
536 }
537
538 func TestCgoPIE(t *testing.T) {
539         name := "cgo_pie"
540         goCmd(t, "build", "-buildmode=pie", "-o="+name, "./execgo")
541         defer os.Remove(name)
542         run(t, name, "./"+name)
543         checkPIE(t, name)
544 }
545
546 // Build a GOPATH package into a shared library that links against the goroot runtime
547 // and an executable that links against both.
548 func TestGopathShlib(t *testing.T) {
549         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
550         shlib := goCmd(t, "list", "-f", "{{.Shlib}}", "-buildmode=shared", "-linkshared", "./depBase")
551         AssertIsLinkedTo(t, shlib, soname)
552         goCmd(t, "install", "-linkshared", "./exe")
553         AssertIsLinkedTo(t, "../../bin/exe", soname)
554         AssertIsLinkedTo(t, "../../bin/exe", filepath.Base(shlib))
555         AssertHasRPath(t, "../../bin/exe", gorootInstallDir)
556         AssertHasRPath(t, "../../bin/exe", filepath.Dir(gopathInstallDir))
557         // And check it runs.
558         run(t, "executable linked to GOPATH library", "../../bin/exe")
559 }
560
561 // The shared library contains a note listing the packages it contains in a section
562 // that is not mapped into memory.
563 func testPkgListNote(t *testing.T, f *elf.File, note *note) {
564         if note.section.Flags != 0 {
565                 t.Errorf("package list section has flags %v, want 0", note.section.Flags)
566         }
567         if isOffsetLoaded(f, note.section.Offset) {
568                 t.Errorf("package list section contained in PT_LOAD segment")
569         }
570         if note.desc != "testshared/depBase\n" {
571                 t.Errorf("incorrect package list %q, want %q", note.desc, "testshared/depBase\n")
572         }
573 }
574
575 // The shared library contains a note containing the ABI hash that is mapped into
576 // memory and there is a local symbol called go.link.abihashbytes that points 16
577 // bytes into it.
578 func testABIHashNote(t *testing.T, f *elf.File, note *note) {
579         if note.section.Flags != elf.SHF_ALLOC {
580                 t.Errorf("abi hash section has flags %v, want SHF_ALLOC", note.section.Flags)
581         }
582         if !isOffsetLoaded(f, note.section.Offset) {
583                 t.Errorf("abihash section not contained in PT_LOAD segment")
584         }
585         var hashbytes elf.Symbol
586         symbols, err := f.Symbols()
587         if err != nil {
588                 t.Errorf("error reading symbols %v", err)
589                 return
590         }
591         for _, sym := range symbols {
592                 if sym.Name == "go:link.abihashbytes" {
593                         hashbytes = sym
594                 }
595         }
596         if hashbytes.Name == "" {
597                 t.Errorf("no symbol called go:link.abihashbytes")
598                 return
599         }
600         if elf.ST_BIND(hashbytes.Info) != elf.STB_LOCAL {
601                 t.Errorf("%s has incorrect binding %v, want STB_LOCAL", hashbytes.Name, elf.ST_BIND(hashbytes.Info))
602         }
603         if f.Sections[hashbytes.Section] != note.section {
604                 t.Errorf("%s has incorrect section %v, want %s", hashbytes.Name, f.Sections[hashbytes.Section].Name, note.section.Name)
605         }
606         if hashbytes.Value-note.section.Addr != 16 {
607                 t.Errorf("%s has incorrect offset into section %d, want 16", hashbytes.Name, hashbytes.Value-note.section.Addr)
608         }
609 }
610
611 // A Go shared library contains a note indicating which other Go shared libraries it
612 // was linked against in an unmapped section.
613 func testDepsNote(t *testing.T, f *elf.File, note *note) {
614         if note.section.Flags != 0 {
615                 t.Errorf("package list section has flags %v, want 0", note.section.Flags)
616         }
617         if isOffsetLoaded(f, note.section.Offset) {
618                 t.Errorf("package list section contained in PT_LOAD segment")
619         }
620         // libdepBase.so just links against the lib containing the runtime.
621         if note.desc != soname {
622                 t.Errorf("incorrect dependency list %q, want %q", note.desc, soname)
623         }
624 }
625
626 // The shared library contains notes with defined contents; see above.
627 func TestNotes(t *testing.T) {
628         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
629         shlib := goCmd(t, "list", "-f", "{{.Shlib}}", "-buildmode=shared", "-linkshared", "./depBase")
630         f, err := elf.Open(shlib)
631         if err != nil {
632                 t.Fatal(err)
633         }
634         defer f.Close()
635         notes, err := readNotes(f)
636         if err != nil {
637                 t.Fatal(err)
638         }
639         pkgListNoteFound := false
640         abiHashNoteFound := false
641         depsNoteFound := false
642         for _, note := range notes {
643                 if note.name != "Go\x00\x00" {
644                         continue
645                 }
646                 switch note.tag {
647                 case 1: // ELF_NOTE_GOPKGLIST_TAG
648                         if pkgListNoteFound {
649                                 t.Error("multiple package list notes")
650                         }
651                         testPkgListNote(t, f, note)
652                         pkgListNoteFound = true
653                 case 2: // ELF_NOTE_GOABIHASH_TAG
654                         if abiHashNoteFound {
655                                 t.Error("multiple abi hash notes")
656                         }
657                         testABIHashNote(t, f, note)
658                         abiHashNoteFound = true
659                 case 3: // ELF_NOTE_GODEPS_TAG
660                         if depsNoteFound {
661                                 t.Error("multiple dependency list notes")
662                         }
663                         testDepsNote(t, f, note)
664                         depsNoteFound = true
665                 }
666         }
667         if !pkgListNoteFound {
668                 t.Error("package list note not found")
669         }
670         if !abiHashNoteFound {
671                 t.Error("abi hash note not found")
672         }
673         if !depsNoteFound {
674                 t.Error("deps note not found")
675         }
676 }
677
678 // Build a GOPATH package (depBase) into a shared library that links against the goroot
679 // runtime, another package (dep2) that links against the first, and an
680 // executable that links against dep2.
681 func TestTwoGopathShlibs(t *testing.T) {
682         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
683         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./dep2")
684         goCmd(t, "install", "-linkshared", "./exe2")
685         run(t, "executable linked to GOPATH library", "../../bin/exe2")
686 }
687
688 func TestThreeGopathShlibs(t *testing.T) {
689         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
690         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./dep2")
691         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./dep3")
692         goCmd(t, "install", "-linkshared", "./exe3")
693         run(t, "executable linked to GOPATH library", "../../bin/exe3")
694 }
695
696 // If gccgo is not available or not new enough, call t.Skip.
697 func requireGccgo(t *testing.T) {
698         t.Helper()
699
700         gccgoName := os.Getenv("GCCGO")
701         if gccgoName == "" {
702                 gccgoName = "gccgo"
703         }
704         gccgoPath, err := exec.LookPath(gccgoName)
705         if err != nil {
706                 t.Skip("gccgo not found")
707         }
708         cmd := exec.Command(gccgoPath, "-dumpversion")
709         output, err := cmd.CombinedOutput()
710         if err != nil {
711                 t.Fatalf("%s -dumpversion failed: %v\n%s", gccgoPath, err, output)
712         }
713         dot := bytes.Index(output, []byte{'.'})
714         if dot > 0 {
715                 output = output[:dot]
716         }
717         major, err := strconv.Atoi(string(output))
718         if err != nil {
719                 t.Skipf("can't parse gccgo version number %s", output)
720         }
721         if major < 5 {
722                 t.Skipf("gccgo too old (%s)", strings.TrimSpace(string(output)))
723         }
724
725         gomod, err := exec.Command("go", "env", "GOMOD").Output()
726         if err != nil {
727                 t.Fatalf("go env GOMOD: %v", err)
728         }
729         if len(bytes.TrimSpace(gomod)) > 0 {
730                 t.Skipf("gccgo not supported in module mode; see golang.org/issue/30344")
731         }
732 }
733
734 // Build a GOPATH package into a shared library with gccgo and an executable that
735 // links against it.
736 func TestGoPathShlibGccgo(t *testing.T) {
737         requireGccgo(t)
738
739         libgoRE := regexp.MustCompile("libgo.so.[0-9]+")
740
741         goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "./depBase")
742
743         // Run 'go list' after 'go install': with gccgo, we apparently don't know the
744         // shlib location until after we've installed it.
745         shlib := goCmd(t, "list", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "-f", "{{.Shlib}}", "./depBase")
746
747         AssertIsLinkedToRegexp(t, shlib, libgoRE)
748         goCmd(t, "install", "-compiler=gccgo", "-linkshared", "./exe")
749         AssertIsLinkedToRegexp(t, "../../bin/exe", libgoRE)
750         AssertIsLinkedTo(t, "../../bin/exe", filepath.Base(shlib))
751         AssertHasRPath(t, "../../bin/exe", filepath.Dir(shlib))
752         // And check it runs.
753         run(t, "gccgo-built", "../../bin/exe")
754 }
755
756 // The gccgo version of TestTwoGopathShlibs: build a GOPATH package into a shared
757 // library with gccgo, another GOPATH package that depends on the first and an
758 // executable that links the second library.
759 func TestTwoGopathShlibsGccgo(t *testing.T) {
760         requireGccgo(t)
761
762         libgoRE := regexp.MustCompile("libgo.so.[0-9]+")
763
764         goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "./depBase")
765         goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "./dep2")
766         goCmd(t, "install", "-compiler=gccgo", "-linkshared", "./exe2")
767
768         // Run 'go list' after 'go install': with gccgo, we apparently don't know the
769         // shlib location until after we've installed it.
770         dep2 := goCmd(t, "list", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "-f", "{{.Shlib}}", "./dep2")
771         depBase := goCmd(t, "list", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "-f", "{{.Shlib}}", "./depBase")
772
773         AssertIsLinkedToRegexp(t, depBase, libgoRE)
774         AssertIsLinkedToRegexp(t, dep2, libgoRE)
775         AssertIsLinkedTo(t, dep2, filepath.Base(depBase))
776         AssertIsLinkedToRegexp(t, "../../bin/exe2", libgoRE)
777         AssertIsLinkedTo(t, "../../bin/exe2", filepath.Base(dep2))
778         AssertIsLinkedTo(t, "../../bin/exe2", filepath.Base(depBase))
779
780         // And check it runs.
781         run(t, "gccgo-built", "../../bin/exe2")
782 }
783
784 // Testing rebuilding of shared libraries when they are stale is a bit more
785 // complicated that it seems like it should be. First, we make everything "old": but
786 // only a few seconds old, or it might be older than gc (or the runtime source) and
787 // everything will get rebuilt. Then define a timestamp slightly newer than this
788 // time, which is what we set the mtime to of a file to cause it to be seen as new,
789 // and finally another slightly even newer one that we can compare files against to
790 // see if they have been rebuilt.
791 var oldTime = time.Now().Add(-9 * time.Second)
792 var nearlyNew = time.Now().Add(-6 * time.Second)
793 var stampTime = time.Now().Add(-3 * time.Second)
794
795 // resetFileStamps makes "everything" (bin, src, pkg from GOPATH and the
796 // test-specific parts of GOROOT) appear old.
797 func resetFileStamps() {
798         chtime := func(path string, info os.FileInfo, err error) error {
799                 return os.Chtimes(path, oldTime, oldTime)
800         }
801         reset := func(path string) {
802                 if err := filepath.Walk(path, chtime); err != nil {
803                         log.Panicf("resetFileStamps failed: %v", err)
804                 }
805
806         }
807         reset("../../bin")
808         reset("../../pkg")
809         reset("../../src")
810         reset(gorootInstallDir)
811 }
812
813 // touch changes path and returns a function that changes it back.
814 // It also sets the time of the file, so that we can see if it is rewritten.
815 func touch(t *testing.T, path string) (cleanup func()) {
816         t.Helper()
817         data, err := os.ReadFile(path)
818         if err != nil {
819                 t.Fatal(err)
820         }
821         old := make([]byte, len(data))
822         copy(old, data)
823         if bytes.HasPrefix(data, []byte("!<arch>\n")) {
824                 // Change last digit of build ID.
825                 // (Content ID in the new content-based build IDs.)
826                 const marker = `build id "`
827                 i := bytes.Index(data, []byte(marker))
828                 if i < 0 {
829                         t.Fatal("cannot find build id in archive")
830                 }
831                 j := bytes.IndexByte(data[i+len(marker):], '"')
832                 if j < 0 {
833                         t.Fatal("cannot find build id in archive")
834                 }
835                 i += len(marker) + j - 1
836                 if data[i] == 'a' {
837                         data[i] = 'b'
838                 } else {
839                         data[i] = 'a'
840                 }
841         } else {
842                 // assume it's a text file
843                 data = append(data, '\n')
844         }
845
846         // If the file is still a symlink from an overlay, delete it so that we will
847         // replace it with a regular file instead of overwriting the symlinked one.
848         fi, err := os.Lstat(path)
849         if err == nil && !fi.Mode().IsRegular() {
850                 fi, err = os.Stat(path)
851                 if err := os.Remove(path); err != nil {
852                         t.Fatal(err)
853                 }
854         }
855         if err != nil {
856                 t.Fatal(err)
857         }
858
859         // If we're replacing a symlink to a read-only file, make the new file
860         // user-writable.
861         perm := fi.Mode().Perm() | 0200
862
863         if err := os.WriteFile(path, data, perm); err != nil {
864                 t.Fatal(err)
865         }
866         if err := os.Chtimes(path, nearlyNew, nearlyNew); err != nil {
867                 t.Fatal(err)
868         }
869         return func() {
870                 if err := os.WriteFile(path, old, perm); err != nil {
871                         t.Fatal(err)
872                 }
873         }
874 }
875
876 // isNew returns if the path is newer than the time stamp used by touch.
877 func isNew(t *testing.T, path string) bool {
878         t.Helper()
879         fi, err := os.Stat(path)
880         if err != nil {
881                 t.Fatal(err)
882         }
883         return fi.ModTime().After(stampTime)
884 }
885
886 // Fail unless path has been rebuilt (i.e. is newer than the time stamp used by
887 // isNew)
888 func AssertRebuilt(t *testing.T, msg, path string) {
889         t.Helper()
890         if !isNew(t, path) {
891                 t.Errorf("%s was not rebuilt (%s)", msg, path)
892         }
893 }
894
895 // Fail if path has been rebuilt (i.e. is newer than the time stamp used by isNew)
896 func AssertNotRebuilt(t *testing.T, msg, path string) {
897         t.Helper()
898         if isNew(t, path) {
899                 t.Errorf("%s was rebuilt (%s)", msg, path)
900         }
901 }
902
903 func TestRebuilding(t *testing.T) {
904         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
905         goCmd(t, "install", "-linkshared", "./exe")
906         info := strings.Fields(goCmd(t, "list", "-buildmode=shared", "-linkshared", "-f", "{{.Target}} {{.Shlib}}", "./depBase"))
907         if len(info) != 2 {
908                 t.Fatalf("go list failed to report Target and/or Shlib")
909         }
910         target := info[0]
911         shlib := info[1]
912
913         // If the source is newer than both the .a file and the .so, both are rebuilt.
914         t.Run("newsource", func(t *testing.T) {
915                 resetFileStamps()
916                 cleanup := touch(t, "./depBase/dep.go")
917                 defer func() {
918                         cleanup()
919                         goCmd(t, "install", "-linkshared", "./exe")
920                 }()
921                 goCmd(t, "install", "-linkshared", "./exe")
922                 AssertRebuilt(t, "new source", target)
923                 AssertRebuilt(t, "new source", shlib)
924         })
925
926         // If the .a file is newer than the .so, the .so is rebuilt (but not the .a)
927         t.Run("newarchive", func(t *testing.T) {
928                 resetFileStamps()
929                 AssertNotRebuilt(t, "new .a file before build", target)
930                 goCmd(t, "list", "-linkshared", "-f={{.ImportPath}} {{.Stale}} {{.StaleReason}} {{.Target}}", "./depBase")
931                 AssertNotRebuilt(t, "new .a file before build", target)
932                 cleanup := touch(t, target)
933                 defer func() {
934                         cleanup()
935                         goCmd(t, "install", "-v", "-linkshared", "./exe")
936                 }()
937                 goCmd(t, "install", "-v", "-linkshared", "./exe")
938                 AssertNotRebuilt(t, "new .a file", target)
939                 AssertRebuilt(t, "new .a file", shlib)
940         })
941 }
942
943 func appendFile(t *testing.T, path, content string) {
944         t.Helper()
945         f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0660)
946         if err != nil {
947                 t.Fatalf("os.OpenFile failed: %v", err)
948         }
949         defer func() {
950                 err := f.Close()
951                 if err != nil {
952                         t.Fatalf("f.Close failed: %v", err)
953                 }
954         }()
955         _, err = f.WriteString(content)
956         if err != nil {
957                 t.Fatalf("f.WriteString failed: %v", err)
958         }
959 }
960
961 func createFile(t *testing.T, path, content string) {
962         t.Helper()
963         f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
964         if err != nil {
965                 t.Fatalf("os.OpenFile failed: %v", err)
966         }
967         _, err = f.WriteString(content)
968         if closeErr := f.Close(); err == nil {
969                 err = closeErr
970         }
971         if err != nil {
972                 t.Fatalf("WriteString failed: %v", err)
973         }
974 }
975
976 func TestABIChecking(t *testing.T) {
977         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
978         goCmd(t, "install", "-linkshared", "./exe")
979
980         // If we make an ABI-breaking change to depBase and rebuild libp.so but not exe,
981         // exe will abort with a complaint on startup.
982         // This assumes adding an exported function breaks ABI, which is not true in
983         // some senses but suffices for the narrow definition of ABI compatibility the
984         // toolchain uses today.
985         resetFileStamps()
986
987         createFile(t, "./depBase/break.go", "package depBase\nfunc ABIBreak() {}\n")
988         defer os.Remove("./depBase/break.go")
989
990         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
991         c := exec.Command("../../bin/exe")
992         output, err := c.CombinedOutput()
993         if err == nil {
994                 t.Fatal("executing exe did not fail after ABI break")
995         }
996         scanner := bufio.NewScanner(bytes.NewReader(output))
997         foundMsg := false
998         const wantPrefix = "abi mismatch detected between the executable and lib"
999         for scanner.Scan() {
1000                 if strings.HasPrefix(scanner.Text(), wantPrefix) {
1001                         foundMsg = true
1002                         break
1003                 }
1004         }
1005         if err = scanner.Err(); err != nil {
1006                 t.Errorf("scanner encountered error: %v", err)
1007         }
1008         if !foundMsg {
1009                 t.Fatalf("exe failed, but without line %q; got output:\n%s", wantPrefix, output)
1010         }
1011
1012         // Rebuilding exe makes it work again.
1013         goCmd(t, "install", "-linkshared", "./exe")
1014         run(t, "rebuilt exe", "../../bin/exe")
1015
1016         // If we make a change which does not break ABI (such as adding an unexported
1017         // function) and rebuild libdepBase.so, exe still works, even if new function
1018         // is in a file by itself.
1019         resetFileStamps()
1020         createFile(t, "./depBase/dep2.go", "package depBase\nfunc noABIBreak() {}\n")
1021         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
1022         run(t, "after non-ABI breaking change", "../../bin/exe")
1023 }
1024
1025 // If a package 'explicit' imports a package 'implicit', building
1026 // 'explicit' into a shared library implicitly includes implicit in
1027 // the shared library. Building an executable that imports both
1028 // explicit and implicit builds the code from implicit into the
1029 // executable rather than fetching it from the shared library. The
1030 // link still succeeds and the executable still runs though.
1031 func TestImplicitInclusion(t *testing.T) {
1032         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./explicit")
1033         goCmd(t, "install", "-linkshared", "./implicitcmd")
1034         run(t, "running executable linked against library that contains same package as it", "../../bin/implicitcmd")
1035 }
1036
1037 // Tests to make sure that the type fields of empty interfaces and itab
1038 // fields of nonempty interfaces are unique even across modules,
1039 // so that interface equality works correctly.
1040 func TestInterface(t *testing.T) {
1041         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./iface_a")
1042         // Note: iface_i gets installed implicitly as a dependency of iface_a.
1043         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./iface_b")
1044         goCmd(t, "install", "-linkshared", "./iface")
1045         run(t, "running type/itab uniqueness tester", "../../bin/iface")
1046 }
1047
1048 // Access a global variable from a library.
1049 func TestGlobal(t *testing.T) {
1050         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./globallib")
1051         goCmd(t, "install", "-linkshared", "./global")
1052         run(t, "global executable", "../../bin/global")
1053         AssertIsLinkedTo(t, "../../bin/global", soname)
1054         AssertHasRPath(t, "../../bin/global", gorootInstallDir)
1055 }
1056
1057 // Run a test using -linkshared of an installed shared package.
1058 // Issue 26400.
1059 func TestTestInstalledShared(t *testing.T) {
1060         goCmd(t, "test", "-linkshared", "-test.short", "sync/atomic")
1061 }
1062
1063 // Test generated pointer method with -linkshared.
1064 // Issue 25065.
1065 func TestGeneratedMethod(t *testing.T) {
1066         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue25065")
1067 }
1068
1069 // Test use of shared library struct with generated hash function.
1070 // Issue 30768.
1071 func TestGeneratedHash(t *testing.T) {
1072         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue30768/issue30768lib")
1073         goCmd(t, "test", "-linkshared", "./issue30768")
1074 }
1075
1076 // Test that packages can be added not in dependency order (here a depends on b, and a adds
1077 // before b). This could happen with e.g. go build -buildmode=shared std. See issue 39777.
1078 func TestPackageOrder(t *testing.T) {
1079         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue39777/a", "./issue39777/b")
1080 }
1081
1082 // Test that GC data are generated correctly by the linker when it needs a type defined in
1083 // a shared library. See issue 39927.
1084 func TestGCData(t *testing.T) {
1085         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./gcdata/p")
1086         goCmd(t, "build", "-linkshared", "./gcdata/main")
1087         runWithEnv(t, "running gcdata/main", []string{"GODEBUG=clobberfree=1"}, "./main")
1088 }
1089
1090 // Test that we don't decode type symbols from shared libraries (which has no data,
1091 // causing panic). See issue 44031.
1092 func TestIssue44031(t *testing.T) {
1093         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue44031/a")
1094         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue44031/b")
1095         goCmd(t, "run", "-linkshared", "./issue44031/main")
1096 }
1097
1098 // Test that we use a variable from shared libraries (which implement an
1099 // interface in shared libraries.). A weak reference is used in the itab
1100 // in main process. It can cause unreacheble panic. See issue 47873.
1101 func TestIssue47873(t *testing.T) {
1102         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue47837/a")
1103         goCmd(t, "run", "-linkshared", "./issue47837/main")
1104 }