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
154 runtimeP, err := myContext.Import("runtime", ".", build.ImportComment)
156 return 0, fmt.Errorf("import failed: %v", err)
158 gorootInstallDir = runtimeP.PkgTargetRoot + "_dynlink"
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
163 goCmd(nil, append([]string{"install", "-buildmode=shared"}, minpkgs...)...)
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 name := "trivial_pie"
532 goCmd(t, "build", "-buildmode=pie", "-o="+name, "./trivial")
533 defer os.Remove(name)
534 run(t, name, "./"+name)
538 func TestCgoPIE(t *testing.T) {
540 goCmd(t, "build", "-buildmode=pie", "-o="+name, "./execgo")
541 defer os.Remove(name)
542 run(t, name, "./"+name)
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")
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)
567 if isOffsetLoaded(f, note.section.Offset) {
568 t.Errorf("package list section contained in PT_LOAD segment")
570 if note.desc != "testshared/depBase\n" {
571 t.Errorf("incorrect package list %q, want %q", note.desc, "testshared/depBase\n")
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
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)
582 if !isOffsetLoaded(f, note.section.Offset) {
583 t.Errorf("abihash section not contained in PT_LOAD segment")
585 var hashbytes elf.Symbol
586 symbols, err := f.Symbols()
588 t.Errorf("error reading symbols %v", err)
591 for _, sym := range symbols {
592 if sym.Name == "go:link.abihashbytes" {
596 if hashbytes.Name == "" {
597 t.Errorf("no symbol called go:link.abihashbytes")
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))
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)
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)
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)
617 if isOffsetLoaded(f, note.section.Offset) {
618 t.Errorf("package list section contained in PT_LOAD segment")
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)
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)
635 notes, err := readNotes(f)
639 pkgListNoteFound := false
640 abiHashNoteFound := false
641 depsNoteFound := false
642 for _, note := range notes {
643 if note.name != "Go\x00\x00" {
647 case 1: // ELF_NOTE_GOPKGLIST_TAG
648 if pkgListNoteFound {
649 t.Error("multiple package list notes")
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")
657 testABIHashNote(t, f, note)
658 abiHashNoteFound = true
659 case 3: // ELF_NOTE_GODEPS_TAG
661 t.Error("multiple dependency list notes")
663 testDepsNote(t, f, note)
667 if !pkgListNoteFound {
668 t.Error("package list note not found")
670 if !abiHashNoteFound {
671 t.Error("abi hash note not found")
674 t.Error("deps note not found")
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")
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")
696 // If gccgo is not available or not new enough, call t.Skip.
697 func requireGccgo(t *testing.T) {
700 gccgoName := os.Getenv("GCCGO")
704 gccgoPath, err := exec.LookPath(gccgoName)
706 t.Skip("gccgo not found")
708 cmd := exec.Command(gccgoPath, "-dumpversion")
709 output, err := cmd.CombinedOutput()
711 t.Fatalf("%s -dumpversion failed: %v\n%s", gccgoPath, err, output)
713 dot := bytes.Index(output, []byte{'.'})
715 output = output[:dot]
717 major, err := strconv.Atoi(string(output))
719 t.Skipf("can't parse gccgo version number %s", output)
722 t.Skipf("gccgo too old (%s)", strings.TrimSpace(string(output)))
725 gomod, err := exec.Command("go", "env", "GOMOD").Output()
727 t.Fatalf("go env GOMOD: %v", err)
729 if len(bytes.TrimSpace(gomod)) > 0 {
730 t.Skipf("gccgo not supported in module mode; see golang.org/issue/30344")
734 // Build a GOPATH package into a shared library with gccgo and an executable that
736 func TestGoPathShlibGccgo(t *testing.T) {
739 libgoRE := regexp.MustCompile("libgo.so.[0-9]+")
741 goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "./depBase")
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")
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")
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) {
762 libgoRE := regexp.MustCompile("libgo.so.[0-9]+")
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")
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")
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))
780 // And check it runs.
781 run(t, "gccgo-built", "../../bin/exe2")
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)
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)
801 reset := func(path string) {
802 if err := filepath.Walk(path, chtime); err != nil {
803 log.Panicf("resetFileStamps failed: %v", err)
810 reset(gorootInstallDir)
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()) {
817 data, err := os.ReadFile(path)
821 old := make([]byte, len(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))
829 t.Fatal("cannot find build id in archive")
831 j := bytes.IndexByte(data[i+len(marker):], '"')
833 t.Fatal("cannot find build id in archive")
835 i += len(marker) + j - 1
842 // assume it's a text file
843 data = append(data, '\n')
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 {
859 // If we're replacing a symlink to a read-only file, make the new file
861 perm := fi.Mode().Perm() | 0200
863 if err := os.WriteFile(path, data, perm); err != nil {
866 if err := os.Chtimes(path, nearlyNew, nearlyNew); err != nil {
870 if err := os.WriteFile(path, old, perm); err != nil {
876 // isNew returns if the path is newer than the time stamp used by touch.
877 func isNew(t *testing.T, path string) bool {
879 fi, err := os.Stat(path)
883 return fi.ModTime().After(stampTime)
886 // Fail unless path has been rebuilt (i.e. is newer than the time stamp used by
888 func AssertRebuilt(t *testing.T, msg, path string) {
891 t.Errorf("%s was not rebuilt (%s)", msg, path)
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) {
899 t.Errorf("%s was rebuilt (%s)", msg, path)
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"))
908 t.Fatalf("go list failed to report Target and/or Shlib")
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) {
916 cleanup := touch(t, "./depBase/dep.go")
919 goCmd(t, "install", "-linkshared", "./exe")
921 goCmd(t, "install", "-linkshared", "./exe")
922 AssertRebuilt(t, "new source", target)
923 AssertRebuilt(t, "new source", shlib)
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) {
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)
935 goCmd(t, "install", "-v", "-linkshared", "./exe")
937 goCmd(t, "install", "-v", "-linkshared", "./exe")
938 AssertNotRebuilt(t, "new .a file", target)
939 AssertRebuilt(t, "new .a file", shlib)
943 func appendFile(t *testing.T, path, content string) {
945 f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0660)
947 t.Fatalf("os.OpenFile failed: %v", err)
952 t.Fatalf("f.Close failed: %v", err)
955 _, err = f.WriteString(content)
957 t.Fatalf("f.WriteString failed: %v", err)
961 func createFile(t *testing.T, path, content string) {
963 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
965 t.Fatalf("os.OpenFile failed: %v", err)
967 _, err = f.WriteString(content)
968 if closeErr := f.Close(); err == nil {
972 t.Fatalf("WriteString failed: %v", err)
976 func TestABIChecking(t *testing.T) {
977 goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
978 goCmd(t, "install", "-linkshared", "./exe")
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.
987 createFile(t, "./depBase/break.go", "package depBase\nfunc ABIBreak() {}\n")
988 defer os.Remove("./depBase/break.go")
990 goCmd(t, "install", "-buildmode=shared", "-linkshared", "./depBase")
991 c := exec.Command("../../bin/exe")
992 output, err := c.CombinedOutput()
994 t.Fatal("executing exe did not fail after ABI break")
996 scanner := bufio.NewScanner(bytes.NewReader(output))
998 const wantPrefix = "abi mismatch detected between the executable and lib"
1000 if strings.HasPrefix(scanner.Text(), wantPrefix) {
1005 if err = scanner.Err(); err != nil {
1006 t.Errorf("scanner encountered error: %v", err)
1009 t.Fatalf("exe failed, but without line %q; got output:\n%s", wantPrefix, output)
1012 // Rebuilding exe makes it work again.
1013 goCmd(t, "install", "-linkshared", "./exe")
1014 run(t, "rebuilt exe", "../../bin/exe")
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.
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")
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")
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")
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)
1057 // Run a test using -linkshared of an installed shared package.
1059 func TestTestInstalledShared(t *testing.T) {
1060 goCmd(t, "test", "-linkshared", "-test.short", "sync/atomic")
1063 // Test generated pointer method with -linkshared.
1065 func TestGeneratedMethod(t *testing.T) {
1066 goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue25065")
1069 // Test use of shared library struct with generated hash function.
1071 func TestGeneratedHash(t *testing.T) {
1072 goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue30768/issue30768lib")
1073 goCmd(t, "test", "-linkshared", "./issue30768")
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")
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")
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")
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")