]> Cypherpunks.ru repositories - gostls13.git/blob - misc/cgo/testshared/shared_test.go
e300e20e2008053b0cfc04aeff329e35252d9696
[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
155         // All tests depend on runtime being built into a shared library. Because
156         // that takes a few seconds, do it here and have all tests use the version
157         // built here.
158         goCmd(nil, append([]string{"install", "-buildmode=shared"}, minpkgs...)...)
159
160         shlib := goCmd(nil, "list", "-linkshared", "-f={{.Shlib}}", "runtime")
161         if shlib != "" {
162                 gorootInstallDir = filepath.Dir(shlib)
163         }
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         if strings.HasSuffix(os.Getenv("GO_BUILDER_NAME"), "-alpine") {
532                 t.Skip("skipping on alpine until issue #54354 resolved")
533         }
534         name := "trivial_pie"
535         goCmd(t, "build", "-buildmode=pie", "-o="+name, "./trivial")
536         defer os.Remove(name)
537         run(t, name, "./"+name)
538         checkPIE(t, name)
539 }
540
541 func TestCgoPIE(t *testing.T) {
542         name := "cgo_pie"
543         goCmd(t, "build", "-buildmode=pie", "-o="+name, "./execgo")
544         defer os.Remove(name)
545         run(t, name, "./"+name)
546         checkPIE(t, name)
547 }
548
549 // Build a GOPATH package into a shared library that links against the goroot runtime
550 // and an executable that links against both.
551 func TestGopathShlib(t *testing.T) {
552         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
553         shlib := goCmd(t, "list", "-f", "{{.Shlib}}", "-buildmode=shared", "-linkshared", "./depBase")
554         AssertIsLinkedTo(t, shlib, soname)
555         goCmd(t, "install", "-linkshared", "./exe")
556         AssertIsLinkedTo(t, "../../bin/exe", soname)
557         AssertIsLinkedTo(t, "../../bin/exe", filepath.Base(shlib))
558         AssertHasRPath(t, "../../bin/exe", gorootInstallDir)
559         AssertHasRPath(t, "../../bin/exe", filepath.Dir(gopathInstallDir))
560         // And check it runs.
561         run(t, "executable linked to GOPATH library", "../../bin/exe")
562 }
563
564 // The shared library contains a note listing the packages it contains in a section
565 // that is not mapped into memory.
566 func testPkgListNote(t *testing.T, f *elf.File, note *note) {
567         if note.section.Flags != 0 {
568                 t.Errorf("package list section has flags %v, want 0", note.section.Flags)
569         }
570         if isOffsetLoaded(f, note.section.Offset) {
571                 t.Errorf("package list section contained in PT_LOAD segment")
572         }
573         if note.desc != "testshared/depBase\n" {
574                 t.Errorf("incorrect package list %q, want %q", note.desc, "testshared/depBase\n")
575         }
576 }
577
578 // The shared library contains a note containing the ABI hash that is mapped into
579 // memory and there is a local symbol called go.link.abihashbytes that points 16
580 // bytes into it.
581 func testABIHashNote(t *testing.T, f *elf.File, note *note) {
582         if note.section.Flags != elf.SHF_ALLOC {
583                 t.Errorf("abi hash section has flags %v, want SHF_ALLOC", note.section.Flags)
584         }
585         if !isOffsetLoaded(f, note.section.Offset) {
586                 t.Errorf("abihash section not contained in PT_LOAD segment")
587         }
588         var hashbytes elf.Symbol
589         symbols, err := f.Symbols()
590         if err != nil {
591                 t.Errorf("error reading symbols %v", err)
592                 return
593         }
594         for _, sym := range symbols {
595                 if sym.Name == "go:link.abihashbytes" {
596                         hashbytes = sym
597                 }
598         }
599         if hashbytes.Name == "" {
600                 t.Errorf("no symbol called go:link.abihashbytes")
601                 return
602         }
603         if elf.ST_BIND(hashbytes.Info) != elf.STB_LOCAL {
604                 t.Errorf("%s has incorrect binding %v, want STB_LOCAL", hashbytes.Name, elf.ST_BIND(hashbytes.Info))
605         }
606         if f.Sections[hashbytes.Section] != note.section {
607                 t.Errorf("%s has incorrect section %v, want %s", hashbytes.Name, f.Sections[hashbytes.Section].Name, note.section.Name)
608         }
609         if hashbytes.Value-note.section.Addr != 16 {
610                 t.Errorf("%s has incorrect offset into section %d, want 16", hashbytes.Name, hashbytes.Value-note.section.Addr)
611         }
612 }
613
614 // A Go shared library contains a note indicating which other Go shared libraries it
615 // was linked against in an unmapped section.
616 func testDepsNote(t *testing.T, f *elf.File, note *note) {
617         if note.section.Flags != 0 {
618                 t.Errorf("package list section has flags %v, want 0", note.section.Flags)
619         }
620         if isOffsetLoaded(f, note.section.Offset) {
621                 t.Errorf("package list section contained in PT_LOAD segment")
622         }
623         // libdepBase.so just links against the lib containing the runtime.
624         if note.desc != soname {
625                 t.Errorf("incorrect dependency list %q, want %q", note.desc, soname)
626         }
627 }
628
629 // The shared library contains notes with defined contents; see above.
630 func TestNotes(t *testing.T) {
631         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
632         shlib := goCmd(t, "list", "-f", "{{.Shlib}}", "-buildmode=shared", "-linkshared", "./depBase")
633         f, err := elf.Open(shlib)
634         if err != nil {
635                 t.Fatal(err)
636         }
637         defer f.Close()
638         notes, err := readNotes(f)
639         if err != nil {
640                 t.Fatal(err)
641         }
642         pkgListNoteFound := false
643         abiHashNoteFound := false
644         depsNoteFound := false
645         for _, note := range notes {
646                 if note.name != "Go\x00\x00" {
647                         continue
648                 }
649                 switch note.tag {
650                 case 1: // ELF_NOTE_GOPKGLIST_TAG
651                         if pkgListNoteFound {
652                                 t.Error("multiple package list notes")
653                         }
654                         testPkgListNote(t, f, note)
655                         pkgListNoteFound = true
656                 case 2: // ELF_NOTE_GOABIHASH_TAG
657                         if abiHashNoteFound {
658                                 t.Error("multiple abi hash notes")
659                         }
660                         testABIHashNote(t, f, note)
661                         abiHashNoteFound = true
662                 case 3: // ELF_NOTE_GODEPS_TAG
663                         if depsNoteFound {
664                                 t.Error("multiple dependency list notes")
665                         }
666                         testDepsNote(t, f, note)
667                         depsNoteFound = true
668                 }
669         }
670         if !pkgListNoteFound {
671                 t.Error("package list note not found")
672         }
673         if !abiHashNoteFound {
674                 t.Error("abi hash note not found")
675         }
676         if !depsNoteFound {
677                 t.Error("deps note not found")
678         }
679 }
680
681 // Build a GOPATH package (depBase) into a shared library that links against the goroot
682 // runtime, another package (dep2) that links against the first, and an
683 // executable that links against dep2.
684 func TestTwoGopathShlibs(t *testing.T) {
685         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
686         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./dep2")
687         goCmd(t, "install", "-linkshared", "./exe2")
688         run(t, "executable linked to GOPATH library", "../../bin/exe2")
689 }
690
691 func TestThreeGopathShlibs(t *testing.T) {
692         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
693         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./dep2")
694         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./dep3")
695         goCmd(t, "install", "-linkshared", "./exe3")
696         run(t, "executable linked to GOPATH library", "../../bin/exe3")
697 }
698
699 // If gccgo is not available or not new enough, call t.Skip.
700 func requireGccgo(t *testing.T) {
701         t.Helper()
702
703         gccgoName := os.Getenv("GCCGO")
704         if gccgoName == "" {
705                 gccgoName = "gccgo"
706         }
707         gccgoPath, err := exec.LookPath(gccgoName)
708         if err != nil {
709                 t.Skip("gccgo not found")
710         }
711         cmd := exec.Command(gccgoPath, "-dumpversion")
712         output, err := cmd.CombinedOutput()
713         if err != nil {
714                 t.Fatalf("%s -dumpversion failed: %v\n%s", gccgoPath, err, output)
715         }
716         dot := bytes.Index(output, []byte{'.'})
717         if dot > 0 {
718                 output = output[:dot]
719         }
720         major, err := strconv.Atoi(string(output))
721         if err != nil {
722                 t.Skipf("can't parse gccgo version number %s", output)
723         }
724         if major < 5 {
725                 t.Skipf("gccgo too old (%s)", strings.TrimSpace(string(output)))
726         }
727
728         gomod, err := exec.Command("go", "env", "GOMOD").Output()
729         if err != nil {
730                 t.Fatalf("go env GOMOD: %v", err)
731         }
732         if len(bytes.TrimSpace(gomod)) > 0 {
733                 t.Skipf("gccgo not supported in module mode; see golang.org/issue/30344")
734         }
735 }
736
737 // Build a GOPATH package into a shared library with gccgo and an executable that
738 // links against it.
739 func TestGoPathShlibGccgo(t *testing.T) {
740         requireGccgo(t)
741
742         libgoRE := regexp.MustCompile("libgo.so.[0-9]+")
743
744         goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "./depBase")
745
746         // Run 'go list' after 'go install': with gccgo, we apparently don't know the
747         // shlib location until after we've installed it.
748         shlib := goCmd(t, "list", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "-f", "{{.Shlib}}", "./depBase")
749
750         AssertIsLinkedToRegexp(t, shlib, libgoRE)
751         goCmd(t, "install", "-compiler=gccgo", "-linkshared", "./exe")
752         AssertIsLinkedToRegexp(t, "../../bin/exe", libgoRE)
753         AssertIsLinkedTo(t, "../../bin/exe", filepath.Base(shlib))
754         AssertHasRPath(t, "../../bin/exe", filepath.Dir(shlib))
755         // And check it runs.
756         run(t, "gccgo-built", "../../bin/exe")
757 }
758
759 // The gccgo version of TestTwoGopathShlibs: build a GOPATH package into a shared
760 // library with gccgo, another GOPATH package that depends on the first and an
761 // executable that links the second library.
762 func TestTwoGopathShlibsGccgo(t *testing.T) {
763         requireGccgo(t)
764
765         libgoRE := regexp.MustCompile("libgo.so.[0-9]+")
766
767         goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "./depBase")
768         goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "./dep2")
769         goCmd(t, "install", "-compiler=gccgo", "-linkshared", "./exe2")
770
771         // Run 'go list' after 'go install': with gccgo, we apparently don't know the
772         // shlib location until after we've installed it.
773         dep2 := goCmd(t, "list", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "-f", "{{.Shlib}}", "./dep2")
774         depBase := goCmd(t, "list", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "-f", "{{.Shlib}}", "./depBase")
775
776         AssertIsLinkedToRegexp(t, depBase, libgoRE)
777         AssertIsLinkedToRegexp(t, dep2, libgoRE)
778         AssertIsLinkedTo(t, dep2, filepath.Base(depBase))
779         AssertIsLinkedToRegexp(t, "../../bin/exe2", libgoRE)
780         AssertIsLinkedTo(t, "../../bin/exe2", filepath.Base(dep2))
781         AssertIsLinkedTo(t, "../../bin/exe2", filepath.Base(depBase))
782
783         // And check it runs.
784         run(t, "gccgo-built", "../../bin/exe2")
785 }
786
787 // Testing rebuilding of shared libraries when they are stale is a bit more
788 // complicated that it seems like it should be. First, we make everything "old": but
789 // only a few seconds old, or it might be older than gc (or the runtime source) and
790 // everything will get rebuilt. Then define a timestamp slightly newer than this
791 // time, which is what we set the mtime to of a file to cause it to be seen as new,
792 // and finally another slightly even newer one that we can compare files against to
793 // see if they have been rebuilt.
794 var oldTime = time.Now().Add(-9 * time.Second)
795 var nearlyNew = time.Now().Add(-6 * time.Second)
796 var stampTime = time.Now().Add(-3 * time.Second)
797
798 // resetFileStamps makes "everything" (bin, src, pkg from GOPATH and the
799 // test-specific parts of GOROOT) appear old.
800 func resetFileStamps() {
801         chtime := func(path string, info os.FileInfo, err error) error {
802                 return os.Chtimes(path, oldTime, oldTime)
803         }
804         reset := func(path string) {
805                 if err := filepath.Walk(path, chtime); err != nil {
806                         log.Panicf("resetFileStamps failed: %v", err)
807                 }
808
809         }
810         reset("../../bin")
811         reset("../../pkg")
812         reset("../../src")
813         reset(gorootInstallDir)
814 }
815
816 // touch changes path and returns a function that changes it back.
817 // It also sets the time of the file, so that we can see if it is rewritten.
818 func touch(t *testing.T, path string) (cleanup func()) {
819         t.Helper()
820         data, err := os.ReadFile(path)
821         if err != nil {
822                 t.Fatal(err)
823         }
824         old := make([]byte, len(data))
825         copy(old, data)
826         if bytes.HasPrefix(data, []byte("!<arch>\n")) {
827                 // Change last digit of build ID.
828                 // (Content ID in the new content-based build IDs.)
829                 const marker = `build id "`
830                 i := bytes.Index(data, []byte(marker))
831                 if i < 0 {
832                         t.Fatal("cannot find build id in archive")
833                 }
834                 j := bytes.IndexByte(data[i+len(marker):], '"')
835                 if j < 0 {
836                         t.Fatal("cannot find build id in archive")
837                 }
838                 i += len(marker) + j - 1
839                 if data[i] == 'a' {
840                         data[i] = 'b'
841                 } else {
842                         data[i] = 'a'
843                 }
844         } else {
845                 // assume it's a text file
846                 data = append(data, '\n')
847         }
848
849         // If the file is still a symlink from an overlay, delete it so that we will
850         // replace it with a regular file instead of overwriting the symlinked one.
851         fi, err := os.Lstat(path)
852         if err == nil && !fi.Mode().IsRegular() {
853                 fi, err = os.Stat(path)
854                 if err := os.Remove(path); err != nil {
855                         t.Fatal(err)
856                 }
857         }
858         if err != nil {
859                 t.Fatal(err)
860         }
861
862         // If we're replacing a symlink to a read-only file, make the new file
863         // user-writable.
864         perm := fi.Mode().Perm() | 0200
865
866         if err := os.WriteFile(path, data, perm); err != nil {
867                 t.Fatal(err)
868         }
869         if err := os.Chtimes(path, nearlyNew, nearlyNew); err != nil {
870                 t.Fatal(err)
871         }
872         return func() {
873                 if err := os.WriteFile(path, old, perm); err != nil {
874                         t.Fatal(err)
875                 }
876         }
877 }
878
879 // isNew returns if the path is newer than the time stamp used by touch.
880 func isNew(t *testing.T, path string) bool {
881         t.Helper()
882         fi, err := os.Stat(path)
883         if err != nil {
884                 t.Fatal(err)
885         }
886         return fi.ModTime().After(stampTime)
887 }
888
889 // Fail unless path has been rebuilt (i.e. is newer than the time stamp used by
890 // isNew)
891 func AssertRebuilt(t *testing.T, msg, path string) {
892         t.Helper()
893         if !isNew(t, path) {
894                 t.Errorf("%s was not rebuilt (%s)", msg, path)
895         }
896 }
897
898 // Fail if path has been rebuilt (i.e. is newer than the time stamp used by isNew)
899 func AssertNotRebuilt(t *testing.T, msg, path string) {
900         t.Helper()
901         if isNew(t, path) {
902                 t.Errorf("%s was rebuilt (%s)", msg, path)
903         }
904 }
905
906 func TestRebuilding(t *testing.T) {
907         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
908         goCmd(t, "install", "-linkshared", "./exe")
909         info := strings.Fields(goCmd(t, "list", "-buildmode=shared", "-linkshared", "-f", "{{.Target}} {{.Shlib}}", "./depBase"))
910         if len(info) != 2 {
911                 t.Fatalf("go list failed to report Target and/or Shlib")
912         }
913         target := info[0]
914         shlib := info[1]
915
916         // If the source is newer than both the .a file and the .so, both are rebuilt.
917         t.Run("newsource", func(t *testing.T) {
918                 resetFileStamps()
919                 cleanup := touch(t, "./depBase/dep.go")
920                 defer func() {
921                         cleanup()
922                         goCmd(t, "install", "-linkshared", "./exe")
923                 }()
924                 goCmd(t, "install", "-linkshared", "./exe")
925                 AssertRebuilt(t, "new source", target)
926                 AssertRebuilt(t, "new source", shlib)
927         })
928
929         // If the .a file is newer than the .so, the .so is rebuilt (but not the .a)
930         t.Run("newarchive", func(t *testing.T) {
931                 resetFileStamps()
932                 AssertNotRebuilt(t, "new .a file before build", target)
933                 goCmd(t, "list", "-linkshared", "-f={{.ImportPath}} {{.Stale}} {{.StaleReason}} {{.Target}}", "./depBase")
934                 AssertNotRebuilt(t, "new .a file before build", target)
935                 cleanup := touch(t, target)
936                 defer func() {
937                         cleanup()
938                         goCmd(t, "install", "-v", "-linkshared", "./exe")
939                 }()
940                 goCmd(t, "install", "-v", "-linkshared", "./exe")
941                 AssertNotRebuilt(t, "new .a file", target)
942                 AssertRebuilt(t, "new .a file", shlib)
943         })
944 }
945
946 func appendFile(t *testing.T, path, content string) {
947         t.Helper()
948         f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0660)
949         if err != nil {
950                 t.Fatalf("os.OpenFile failed: %v", err)
951         }
952         defer func() {
953                 err := f.Close()
954                 if err != nil {
955                         t.Fatalf("f.Close failed: %v", err)
956                 }
957         }()
958         _, err = f.WriteString(content)
959         if err != nil {
960                 t.Fatalf("f.WriteString failed: %v", err)
961         }
962 }
963
964 func createFile(t *testing.T, path, content string) {
965         t.Helper()
966         f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
967         if err != nil {
968                 t.Fatalf("os.OpenFile failed: %v", err)
969         }
970         _, err = f.WriteString(content)
971         if closeErr := f.Close(); err == nil {
972                 err = closeErr
973         }
974         if err != nil {
975                 t.Fatalf("WriteString failed: %v", err)
976         }
977 }
978
979 func TestABIChecking(t *testing.T) {
980         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
981         goCmd(t, "install", "-linkshared", "./exe")
982
983         // If we make an ABI-breaking change to depBase and rebuild libp.so but not exe,
984         // exe will abort with a complaint on startup.
985         // This assumes adding an exported function breaks ABI, which is not true in
986         // some senses but suffices for the narrow definition of ABI compatibility the
987         // toolchain uses today.
988         resetFileStamps()
989
990         createFile(t, "./depBase/break.go", "package depBase\nfunc ABIBreak() {}\n")
991         defer os.Remove("./depBase/break.go")
992
993         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
994         c := exec.Command("../../bin/exe")
995         output, err := c.CombinedOutput()
996         if err == nil {
997                 t.Fatal("executing exe did not fail after ABI break")
998         }
999         scanner := bufio.NewScanner(bytes.NewReader(output))
1000         foundMsg := false
1001         const wantPrefix = "abi mismatch detected between the executable and lib"
1002         for scanner.Scan() {
1003                 if strings.HasPrefix(scanner.Text(), wantPrefix) {
1004                         foundMsg = true
1005                         break
1006                 }
1007         }
1008         if err = scanner.Err(); err != nil {
1009                 t.Errorf("scanner encountered error: %v", err)
1010         }
1011         if !foundMsg {
1012                 t.Fatalf("exe failed, but without line %q; got output:\n%s", wantPrefix, output)
1013         }
1014
1015         // Rebuilding exe makes it work again.
1016         goCmd(t, "install", "-linkshared", "./exe")
1017         run(t, "rebuilt exe", "../../bin/exe")
1018
1019         // If we make a change which does not break ABI (such as adding an unexported
1020         // function) and rebuild libdepBase.so, exe still works, even if new function
1021         // is in a file by itself.
1022         resetFileStamps()
1023         createFile(t, "./depBase/dep2.go", "package depBase\nfunc noABIBreak() {}\n")
1024         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
1025         run(t, "after non-ABI breaking change", "../../bin/exe")
1026 }
1027
1028 // If a package 'explicit' imports a package 'implicit', building
1029 // 'explicit' into a shared library implicitly includes implicit in
1030 // the shared library. Building an executable that imports both
1031 // explicit and implicit builds the code from implicit into the
1032 // executable rather than fetching it from the shared library. The
1033 // link still succeeds and the executable still runs though.
1034 func TestImplicitInclusion(t *testing.T) {
1035         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./explicit")
1036         goCmd(t, "install", "-linkshared", "./implicitcmd")
1037         run(t, "running executable linked against library that contains same package as it", "../../bin/implicitcmd")
1038 }
1039
1040 // Tests to make sure that the type fields of empty interfaces and itab
1041 // fields of nonempty interfaces are unique even across modules,
1042 // so that interface equality works correctly.
1043 func TestInterface(t *testing.T) {
1044         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./iface_a")
1045         // Note: iface_i gets installed implicitly as a dependency of iface_a.
1046         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./iface_b")
1047         goCmd(t, "install", "-linkshared", "./iface")
1048         run(t, "running type/itab uniqueness tester", "../../bin/iface")
1049 }
1050
1051 // Access a global variable from a library.
1052 func TestGlobal(t *testing.T) {
1053         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./globallib")
1054         goCmd(t, "install", "-linkshared", "./global")
1055         run(t, "global executable", "../../bin/global")
1056         AssertIsLinkedTo(t, "../../bin/global", soname)
1057         AssertHasRPath(t, "../../bin/global", gorootInstallDir)
1058 }
1059
1060 // Run a test using -linkshared of an installed shared package.
1061 // Issue 26400.
1062 func TestTestInstalledShared(t *testing.T) {
1063         goCmd(t, "test", "-linkshared", "-test.short", "sync/atomic")
1064 }
1065
1066 // Test generated pointer method with -linkshared.
1067 // Issue 25065.
1068 func TestGeneratedMethod(t *testing.T) {
1069         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue25065")
1070 }
1071
1072 // Test use of shared library struct with generated hash function.
1073 // Issue 30768.
1074 func TestGeneratedHash(t *testing.T) {
1075         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue30768/issue30768lib")
1076         goCmd(t, "test", "-linkshared", "./issue30768")
1077 }
1078
1079 // Test that packages can be added not in dependency order (here a depends on b, and a adds
1080 // before b). This could happen with e.g. go build -buildmode=shared std. See issue 39777.
1081 func TestPackageOrder(t *testing.T) {
1082         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue39777/a", "./issue39777/b")
1083 }
1084
1085 // Test that GC data are generated correctly by the linker when it needs a type defined in
1086 // a shared library. See issue 39927.
1087 func TestGCData(t *testing.T) {
1088         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./gcdata/p")
1089         goCmd(t, "build", "-linkshared", "./gcdata/main")
1090         runWithEnv(t, "running gcdata/main", []string{"GODEBUG=clobberfree=1"}, "./main")
1091 }
1092
1093 // Test that we don't decode type symbols from shared libraries (which has no data,
1094 // causing panic). See issue 44031.
1095 func TestIssue44031(t *testing.T) {
1096         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue44031/a")
1097         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue44031/b")
1098         goCmd(t, "run", "-linkshared", "./issue44031/main")
1099 }
1100
1101 // Test that we use a variable from shared libraries (which implement an
1102 // interface in shared libraries.). A weak reference is used in the itab
1103 // in main process. It can cause unreachable panic. See issue 47873.
1104 func TestIssue47873(t *testing.T) {
1105         goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue47837/a")
1106         goCmd(t, "run", "-linkshared", "./issue47837/main")
1107 }
1108
1109 // Test that we can build std in shared mode.
1110 func TestStd(t *testing.T) {
1111         if testing.Short() {
1112                 t.Skip("skip in short mode")
1113         }
1114         t.Parallel()
1115         tmpDir := t.TempDir()
1116         // Use a temporary pkgdir to not interfere with other tests, and not write to GOROOT.
1117         // Cannot use goCmd as it runs with cloned GOROOT which is incomplete.
1118         runWithEnv(t, "building std", []string{"GOROOT=" + oldGOROOT},
1119                 filepath.Join(oldGOROOT, "bin", "go"), "install", "-buildmode=shared", "-pkgdir="+tmpDir, "std")
1120
1121         // Issue #58966.
1122         runWithEnv(t, "testing issue #58966", []string{"GOROOT=" + oldGOROOT},
1123                 filepath.Join(oldGOROOT, "bin", "go"), "run", "-linkshared", "-pkgdir="+tmpDir, "./issue58966/main.go")
1124 }