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.
29 var gopathInstallDir, gorootInstallDir string
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"
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")
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...)
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:]...)
49 c.Env = append(os.Environ(), env...)
51 if output, err := c.CombinedOutput(); err != nil {
52 t.Errorf("executing %s (%s) failed %s:\n%s", strings.Join(args, " "), msg, err, output)
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")
63 newargs = append(newargs, args[1:]...)
64 c := exec.Command(filepath.Join(oldGOROOT, "bin", "go"), newargs...)
65 stderr := new(strings.Builder)
68 if testing.Verbose() && t == nil {
69 fmt.Fprintf(os.Stderr, "+ go %s\n", strings.Join(args, " "))
72 output, err := c.Output()
77 t.Fatalf("executing %s failed %v:\n%s", strings.Join(c.Args, " "), err, stderr)
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)
83 if testing.Verbose() && t != nil {
84 t.Logf("go %s", strings.Join(args, " "))
89 return string(bytes.TrimSpace(output))
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()
98 oldGOROOT = filepath.Join(cwd, "../../..")
100 workDir, err := os.MkdirTemp("", "shared_test")
104 if *testWork || testing.Verbose() {
105 fmt.Printf("+ mkdir -p %s\n", workDir)
108 defer os.RemoveAll(workDir)
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")
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)
127 if testing.Verbose() {
128 fmt.Printf("+ export GOPATH=%s\n", gopath)
129 fmt.Printf("+ cd %s\n", modRoot)
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"))
135 os.Setenv("PWD", modRoot)
137 // The test also needs to install libraries into GOROOT/pkg, so copy the
138 // subset of GOROOT that we need.
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 {
146 if testing.Verbose() {
147 fmt.Fprintf(os.Stderr, "+ export GOROOT=%s\n", goroot)
149 os.Setenv("GOROOT", goroot)
151 myContext := build.Default
152 myContext.GOROOT = goroot
153 myContext.GOPATH = gopath
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
158 goCmd(nil, append([]string{"install", "-buildmode=shared"}, minpkgs...)...)
160 shlib := goCmd(nil, "list", "-linkshared", "-f={{.Shlib}}", "runtime")
162 gorootInstallDir = filepath.Dir(shlib)
165 myContext.InstallSuffix = "_dynlink"
166 depP, err := myContext.Import("./depBase", ".", build.ImportComment)
168 return 0, fmt.Errorf("import failed: %v", err)
170 if depP.PkgTargetRoot == "" {
171 gopathInstallDir = filepath.Dir(goCmd(nil, "list", "-buildmode=shared", "-f", "{{.Target}}", "./depBase"))
173 gopathInstallDir = filepath.Join(depP.PkgTargetRoot, "testshared")
178 func TestMain(m *testing.M) {
179 log.SetFlags(log.Lshortfile)
182 exitCode, err := testMain(m)
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 {
196 if err := os.WriteFile(filepath.Join(modRoot, "go.mod"), []byte("module testshared\n"), 0644); err != nil {
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{
210 "-f", "{{if and .Standard (not .ForTest)}}{{.ImportPath}}{{end}}",
212 stdDeps := goCmd(nil, append(listArgs, minpkgs...)...)
213 testdataDeps := goCmd(nil, append(listArgs, "-test", "./...")...)
215 pkgs := append(strings.Split(strings.TrimSpace(stdDeps), "\n"),
216 strings.Split(strings.TrimSpace(testdataDeps), "\n")...)
218 var pkgRoots []string
219 for _, pkg := range pkgs {
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.
229 pkgRoots = append(pkgRoots, pkg)
233 gorootDirs := []string{
237 for _, pkg := range pkgRoots {
238 gorootDirs = append(gorootDirs, filepath.Join("src", pkg))
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))
245 if err := overlayDir(filepath.Join(goroot, dir), filepath.Join(oldGOROOT, dir)); err != nil {
253 // The shared library was built at the expected location.
254 func TestSOBuilt(t *testing.T) {
255 _, err := os.Stat(filepath.Join(gorootInstallDir, soname))
261 func hasDynTag(f *elf.File, tag elf.DynTag) bool {
262 ds := f.SectionByType(elf.SHT_DYNAMIC)
274 t = elf.DynTag(f.ByteOrder.Uint32(d[0:4]))
277 t = elf.DynTag(f.ByteOrder.Uint64(d[0:8]))
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)
292 t.Fatal("elf.Open failed: ", err)
295 if hasDynTag(f, elf.DT_TEXTREL) {
296 t.Errorf("%s has DT_TEXTREL set", soname)
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)
306 t.Fatal("elf.Open failed: ", err)
309 syms, err := f.Symbols()
311 t.Errorf("error reading symbols %v", err)
314 for _, s := range syms {
315 if s.Name == ".dup" {
316 t.Fatalf("%s contains symbol called .dup", sopath)
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")
330 for _, pkg := range pkgs {
331 shlibnamefile := filepath.Join(gorootInstallDir, pkg+".shlibname")
332 contentsb, err := os.ReadFile(shlibnamefile)
334 t.Errorf("error reading shlibnamefile for %s: %v", pkg, err)
337 contents := strings.TrimSpace(string(contentsb))
338 if contents != soname {
339 t.Errorf("shlibnamefile for %s has wrong contents: %q", pkg, contents)
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 {
356 func rnd(v int32, r int32) int32 {
369 func readwithpad(r io.Reader, sz int32) ([]byte, error) {
370 data := make([]byte, rnd(sz, 4))
371 _, err := io.ReadFull(r, data)
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) {
391 for _, sect := range f.Sections {
392 if sect.Type != elf.SHT_NOTE {
397 var namesize, descsize, tag int32
398 err := binary.Read(r, f.ByteOrder, &namesize)
403 return nil, fmt.Errorf("read namesize failed: %v", err)
405 err = binary.Read(r, f.ByteOrder, &descsize)
407 return nil, fmt.Errorf("read descsize failed: %v", err)
409 err = binary.Read(r, f.ByteOrder, &tag)
411 return nil, fmt.Errorf("read type failed: %v", err)
413 name, err := readwithpad(r, namesize)
415 return nil, fmt.Errorf("read name failed: %v", err)
417 desc, err := readwithpad(r, descsize)
419 return nil, fmt.Errorf("read desc failed: %v", err)
421 notes = append(notes, ¬e{name: string(name), tag: tag, desc: string(desc), section: sect})
427 func dynStrings(t *testing.T, path string, flag elf.DynTag) []string {
429 f, err := elf.Open(path)
431 t.Fatalf("elf.Open(%q) failed: %v", path, err)
434 dynstrings, err := f.DynString(flag)
436 t.Fatalf("DynString(%s) failed on %s: %v", flag, path, err)
441 func AssertIsLinkedToRegexp(t *testing.T, path string, re *regexp.Regexp) {
443 for _, dynstring := range dynStrings(t, path, elf.DT_NEEDED) {
444 if re.MatchString(dynstring) {
448 t.Errorf("%s is not linked to anything matching %v", path, re)
451 func AssertIsLinkedTo(t *testing.T, path, lib string) {
453 AssertIsLinkedToRegexp(t, path, regexp.MustCompile(regexp.QuoteMeta(lib)))
456 func AssertHasRPath(t *testing.T, path, dir string) {
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) {
467 t.Errorf("%s does not have rpath %s", path, dir)
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)
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)
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)
496 t.Fatalf("stat failed: %v", err)
498 if sz := fi.Size(); sz > limit {
499 t.Errorf("file too large: got %d, want <= %d", sz, limit)
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")
509 // Build an executable that uses cgo linked against the shared runtime and check it
511 func TestCgoExecutable(t *testing.T) {
512 goCmd(t, "install", "-linkshared", "./execgo")
513 run(t, "cgo executable", "../../bin/execgo")
516 func checkPIE(t *testing.T, name string) {
517 f, err := elf.Open(name)
519 t.Fatal("elf.Open failed: ", err)
522 if f.Type != elf.ET_DYN {
523 t.Errorf("%s has type %v, want ET_DYN", name, f.Type)
525 if hasDynTag(f, elf.DT_TEXTREL) {
526 t.Errorf("%s has DT_TEXTREL set", name)
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")
534 name := "trivial_pie"
535 goCmd(t, "build", "-buildmode=pie", "-o="+name, "./trivial")
536 defer os.Remove(name)
537 run(t, name, "./"+name)
541 func TestCgoPIE(t *testing.T) {
543 goCmd(t, "build", "-buildmode=pie", "-o="+name, "./execgo")
544 defer os.Remove(name)
545 run(t, name, "./"+name)
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")
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)
570 if isOffsetLoaded(f, note.section.Offset) {
571 t.Errorf("package list section contained in PT_LOAD segment")
573 if note.desc != "testshared/depBase\n" {
574 t.Errorf("incorrect package list %q, want %q", note.desc, "testshared/depBase\n")
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
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)
585 if !isOffsetLoaded(f, note.section.Offset) {
586 t.Errorf("abihash section not contained in PT_LOAD segment")
588 var hashbytes elf.Symbol
589 symbols, err := f.Symbols()
591 t.Errorf("error reading symbols %v", err)
594 for _, sym := range symbols {
595 if sym.Name == "go:link.abihashbytes" {
599 if hashbytes.Name == "" {
600 t.Errorf("no symbol called go:link.abihashbytes")
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))
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)
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)
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)
620 if isOffsetLoaded(f, note.section.Offset) {
621 t.Errorf("package list section contained in PT_LOAD segment")
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)
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)
638 notes, err := readNotes(f)
642 pkgListNoteFound := false
643 abiHashNoteFound := false
644 depsNoteFound := false
645 for _, note := range notes {
646 if note.name != "Go\x00\x00" {
650 case 1: // ELF_NOTE_GOPKGLIST_TAG
651 if pkgListNoteFound {
652 t.Error("multiple package list notes")
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")
660 testABIHashNote(t, f, note)
661 abiHashNoteFound = true
662 case 3: // ELF_NOTE_GODEPS_TAG
664 t.Error("multiple dependency list notes")
666 testDepsNote(t, f, note)
670 if !pkgListNoteFound {
671 t.Error("package list note not found")
673 if !abiHashNoteFound {
674 t.Error("abi hash note not found")
677 t.Error("deps note not found")
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")
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")
699 // If gccgo is not available or not new enough, call t.Skip.
700 func requireGccgo(t *testing.T) {
703 gccgoName := os.Getenv("GCCGO")
707 gccgoPath, err := exec.LookPath(gccgoName)
709 t.Skip("gccgo not found")
711 cmd := exec.Command(gccgoPath, "-dumpversion")
712 output, err := cmd.CombinedOutput()
714 t.Fatalf("%s -dumpversion failed: %v\n%s", gccgoPath, err, output)
716 dot := bytes.Index(output, []byte{'.'})
718 output = output[:dot]
720 major, err := strconv.Atoi(string(output))
722 t.Skipf("can't parse gccgo version number %s", output)
725 t.Skipf("gccgo too old (%s)", strings.TrimSpace(string(output)))
728 gomod, err := exec.Command("go", "env", "GOMOD").Output()
730 t.Fatalf("go env GOMOD: %v", err)
732 if len(bytes.TrimSpace(gomod)) > 0 {
733 t.Skipf("gccgo not supported in module mode; see golang.org/issue/30344")
737 // Build a GOPATH package into a shared library with gccgo and an executable that
739 func TestGoPathShlibGccgo(t *testing.T) {
742 libgoRE := regexp.MustCompile("libgo.so.[0-9]+")
744 goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "./depBase")
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")
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")
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) {
765 libgoRE := regexp.MustCompile("libgo.so.[0-9]+")
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")
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")
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))
783 // And check it runs.
784 run(t, "gccgo-built", "../../bin/exe2")
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)
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)
804 reset := func(path string) {
805 if err := filepath.Walk(path, chtime); err != nil {
806 log.Panicf("resetFileStamps failed: %v", err)
813 reset(gorootInstallDir)
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()) {
820 data, err := os.ReadFile(path)
824 old := make([]byte, len(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))
832 t.Fatal("cannot find build id in archive")
834 j := bytes.IndexByte(data[i+len(marker):], '"')
836 t.Fatal("cannot find build id in archive")
838 i += len(marker) + j - 1
845 // assume it's a text file
846 data = append(data, '\n')
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 {
862 // If we're replacing a symlink to a read-only file, make the new file
864 perm := fi.Mode().Perm() | 0200
866 if err := os.WriteFile(path, data, perm); err != nil {
869 if err := os.Chtimes(path, nearlyNew, nearlyNew); err != nil {
873 if err := os.WriteFile(path, old, perm); err != nil {
879 // isNew returns if the path is newer than the time stamp used by touch.
880 func isNew(t *testing.T, path string) bool {
882 fi, err := os.Stat(path)
886 return fi.ModTime().After(stampTime)
889 // Fail unless path has been rebuilt (i.e. is newer than the time stamp used by
891 func AssertRebuilt(t *testing.T, msg, path string) {
894 t.Errorf("%s was not rebuilt (%s)", msg, path)
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) {
902 t.Errorf("%s was rebuilt (%s)", msg, path)
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"))
911 t.Fatalf("go list failed to report Target and/or Shlib")
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) {
919 cleanup := touch(t, "./depBase/dep.go")
922 goCmd(t, "install", "-linkshared", "./exe")
924 goCmd(t, "install", "-linkshared", "./exe")
925 AssertRebuilt(t, "new source", target)
926 AssertRebuilt(t, "new source", shlib)
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) {
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)
938 goCmd(t, "install", "-v", "-linkshared", "./exe")
940 goCmd(t, "install", "-v", "-linkshared", "./exe")
941 AssertNotRebuilt(t, "new .a file", target)
942 AssertRebuilt(t, "new .a file", shlib)
946 func appendFile(t *testing.T, path, content string) {
948 f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0660)
950 t.Fatalf("os.OpenFile failed: %v", err)
955 t.Fatalf("f.Close failed: %v", err)
958 _, err = f.WriteString(content)
960 t.Fatalf("f.WriteString failed: %v", err)
964 func createFile(t *testing.T, path, content string) {
966 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
968 t.Fatalf("os.OpenFile failed: %v", err)
970 _, err = f.WriteString(content)
971 if closeErr := f.Close(); err == nil {
975 t.Fatalf("WriteString failed: %v", err)
979 func TestABIChecking(t *testing.T) {
980 goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
981 goCmd(t, "install", "-linkshared", "./exe")
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.
990 createFile(t, "./depBase/break.go", "package depBase\nfunc ABIBreak() {}\n")
991 defer os.Remove("./depBase/break.go")
993 goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
994 c := exec.Command("../../bin/exe")
995 output, err := c.CombinedOutput()
997 t.Fatal("executing exe did not fail after ABI break")
999 scanner := bufio.NewScanner(bytes.NewReader(output))
1001 const wantPrefix = "abi mismatch detected between the executable and lib"
1002 for scanner.Scan() {
1003 if strings.HasPrefix(scanner.Text(), wantPrefix) {
1008 if err = scanner.Err(); err != nil {
1009 t.Errorf("scanner encountered error: %v", err)
1012 t.Fatalf("exe failed, but without line %q; got output:\n%s", wantPrefix, output)
1015 // Rebuilding exe makes it work again.
1016 goCmd(t, "install", "-linkshared", "./exe")
1017 run(t, "rebuilt exe", "../../bin/exe")
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.
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")
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")
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")
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)
1060 // Run a test using -linkshared of an installed shared package.
1062 func TestTestInstalledShared(t *testing.T) {
1063 goCmd(t, "test", "-linkshared", "-test.short", "sync/atomic")
1066 // Test generated pointer method with -linkshared.
1068 func TestGeneratedMethod(t *testing.T) {
1069 goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue25065")
1072 // Test use of shared library struct with generated hash function.
1074 func TestGeneratedHash(t *testing.T) {
1075 goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue30768/issue30768lib")
1076 goCmd(t, "test", "-linkshared", "./issue30768")
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")
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")
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")
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")
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")
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")
1122 runWithEnv(t, "testing issue #58966", []string{"GOROOT=" + oldGOROOT},
1123 filepath.Join(oldGOROOT, "bin", "go"), "run", "-linkshared", "-pkgdir="+tmpDir, "./issue58966/main.go")