github.com/muesli/go@v0.0.0-20170208044820-e410d2a81ef2/misc/cgo/testshared/shared_test.go (about)

     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  	"errors"
    13  	"fmt"
    14  	"go/build"
    15  	"io"
    16  	"io/ioutil"
    17  	"log"
    18  	"math/rand"
    19  	"os"
    20  	"os/exec"
    21  	"path/filepath"
    22  	"regexp"
    23  	"runtime"
    24  	"strings"
    25  	"testing"
    26  	"time"
    27  )
    28  
    29  var gopathInstallDir, gorootInstallDir, suffix string
    30  
    31  // This is the smallest set of packages we can link into a shared
    32  // library (runtime/cgo is built implicitly).
    33  var minpkgs = []string{"runtime", "sync/atomic"}
    34  var soname = "libruntime,sync-atomic.so"
    35  
    36  // run runs a command and calls t.Errorf if it fails.
    37  func run(t *testing.T, msg string, args ...string) {
    38  	c := exec.Command(args[0], args[1:]...)
    39  	if output, err := c.CombinedOutput(); err != nil {
    40  		t.Errorf("executing %s (%s) failed %s:\n%s", strings.Join(args, " "), msg, err, output)
    41  	}
    42  }
    43  
    44  // goCmd invokes the go tool with the installsuffix set up by TestMain. It calls
    45  // t.Fatalf if the command fails.
    46  func goCmd(t *testing.T, args ...string) {
    47  	newargs := []string{args[0], "-installsuffix=" + suffix}
    48  	if testing.Verbose() {
    49  		newargs = append(newargs, "-v")
    50  	}
    51  	newargs = append(newargs, args[1:]...)
    52  	c := exec.Command("go", newargs...)
    53  	var output []byte
    54  	var err error
    55  	if testing.Verbose() {
    56  		fmt.Printf("+ go %s\n", strings.Join(newargs, " "))
    57  		c.Stdout = os.Stdout
    58  		c.Stderr = os.Stderr
    59  		err = c.Run()
    60  	} else {
    61  		output, err = c.CombinedOutput()
    62  	}
    63  	if err != nil {
    64  		if t != nil {
    65  			t.Fatalf("executing %s failed %v:\n%s", strings.Join(c.Args, " "), err, output)
    66  		} else {
    67  			log.Fatalf("executing %s failed %v:\n%s", strings.Join(c.Args, " "), err, output)
    68  		}
    69  	}
    70  }
    71  
    72  // TestMain calls testMain so that the latter can use defer (TestMain exits with os.Exit).
    73  func testMain(m *testing.M) (int, error) {
    74  	// Because go install -buildmode=shared $standard_library_package always
    75  	// installs into $GOROOT, here are some gymnastics to come up with a unique
    76  	// installsuffix to use in this test that we can clean up afterwards.
    77  	myContext := build.Default
    78  	runtimeP, err := myContext.Import("runtime", ".", build.ImportComment)
    79  	if err != nil {
    80  		return 0, fmt.Errorf("import failed: %v", err)
    81  	}
    82  	for i := 0; i < 10000; i++ {
    83  		try := fmt.Sprintf("%s_%d_dynlink", runtimeP.PkgTargetRoot, rand.Int63())
    84  		err = os.Mkdir(try, 0700)
    85  		if os.IsExist(err) {
    86  			continue
    87  		}
    88  		if err == nil {
    89  			gorootInstallDir = try
    90  		}
    91  		break
    92  	}
    93  	if err != nil {
    94  		return 0, fmt.Errorf("can't create temporary directory: %v", err)
    95  	}
    96  	if gorootInstallDir == "" {
    97  		return 0, errors.New("could not create temporary directory after 10000 tries")
    98  	}
    99  	if testing.Verbose() {
   100  		fmt.Printf("+ mkdir -p %s\n", gorootInstallDir)
   101  	}
   102  	defer os.RemoveAll(gorootInstallDir)
   103  
   104  	// Some tests need to edit the source in GOPATH, so copy this directory to a
   105  	// temporary directory and chdir to that.
   106  	scratchDir, err := ioutil.TempDir("", "testshared")
   107  	if err != nil {
   108  		return 0, fmt.Errorf("TempDir failed: %v", err)
   109  	}
   110  	if testing.Verbose() {
   111  		fmt.Printf("+ mkdir -p %s\n", scratchDir)
   112  	}
   113  	defer os.RemoveAll(scratchDir)
   114  	err = filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
   115  		scratchPath := filepath.Join(scratchDir, path)
   116  		if info.IsDir() {
   117  			if path == "." {
   118  				return nil
   119  			}
   120  			if testing.Verbose() {
   121  				fmt.Printf("+ mkdir -p %s\n", scratchPath)
   122  			}
   123  			return os.Mkdir(scratchPath, info.Mode())
   124  		} else {
   125  			fromBytes, err := ioutil.ReadFile(path)
   126  			if err != nil {
   127  				return err
   128  			}
   129  			if testing.Verbose() {
   130  				fmt.Printf("+ cp %s %s\n", path, scratchPath)
   131  			}
   132  			return ioutil.WriteFile(scratchPath, fromBytes, info.Mode())
   133  		}
   134  	})
   135  	if err != nil {
   136  		return 0, fmt.Errorf("walk failed: %v", err)
   137  	}
   138  	os.Setenv("GOPATH", scratchDir)
   139  	if testing.Verbose() {
   140  		fmt.Printf("+ export GOPATH=%s\n", scratchDir)
   141  	}
   142  	myContext.GOPATH = scratchDir
   143  	if testing.Verbose() {
   144  		fmt.Printf("+ cd %s\n", scratchDir)
   145  	}
   146  	os.Chdir(scratchDir)
   147  
   148  	// All tests depend on runtime being built into a shared library. Because
   149  	// that takes a few seconds, do it here and have all tests use the version
   150  	// built here.
   151  	suffix = strings.Split(filepath.Base(gorootInstallDir), "_")[2]
   152  	goCmd(nil, append([]string{"install", "-buildmode=shared"}, minpkgs...)...)
   153  
   154  	myContext.InstallSuffix = suffix + "_dynlink"
   155  	depP, err := myContext.Import("depBase", ".", build.ImportComment)
   156  	if err != nil {
   157  		return 0, fmt.Errorf("import failed: %v", err)
   158  	}
   159  	gopathInstallDir = depP.PkgTargetRoot
   160  	return m.Run(), nil
   161  }
   162  
   163  func TestMain(m *testing.M) {
   164  	// Some of the tests install binaries into a custom GOPATH.
   165  	// That won't work if GOBIN is set.
   166  	os.Unsetenv("GOBIN")
   167  
   168  	exitCode, err := testMain(m)
   169  	if err != nil {
   170  		log.Fatal(err)
   171  	}
   172  	os.Exit(exitCode)
   173  }
   174  
   175  // The shared library was built at the expected location.
   176  func TestSOBuilt(t *testing.T) {
   177  	_, err := os.Stat(filepath.Join(gorootInstallDir, soname))
   178  	if err != nil {
   179  		t.Error(err)
   180  	}
   181  }
   182  
   183  func hasDynTag(f *elf.File, tag elf.DynTag) bool {
   184  	ds := f.SectionByType(elf.SHT_DYNAMIC)
   185  	if ds == nil {
   186  		return false
   187  	}
   188  	d, err := ds.Data()
   189  	if err != nil {
   190  		return false
   191  	}
   192  	for len(d) > 0 {
   193  		var t elf.DynTag
   194  		switch f.Class {
   195  		case elf.ELFCLASS32:
   196  			t = elf.DynTag(f.ByteOrder.Uint32(d[0:4]))
   197  			d = d[8:]
   198  		case elf.ELFCLASS64:
   199  			t = elf.DynTag(f.ByteOrder.Uint64(d[0:8]))
   200  			d = d[16:]
   201  		}
   202  		if t == tag {
   203  			return true
   204  		}
   205  	}
   206  	return false
   207  }
   208  
   209  // The shared library does not have relocations against the text segment.
   210  func TestNoTextrel(t *testing.T) {
   211  	sopath := filepath.Join(gorootInstallDir, soname)
   212  	f, err := elf.Open(sopath)
   213  	if err != nil {
   214  		t.Fatal("elf.Open failed: ", err)
   215  	}
   216  	defer f.Close()
   217  	if hasDynTag(f, elf.DT_TEXTREL) {
   218  		t.Errorf("%s has DT_TEXTREL set", soname)
   219  	}
   220  }
   221  
   222  // The shared library does not contain symbols called ".dup"
   223  func TestNoDupSymbols(t *testing.T) {
   224  	sopath := filepath.Join(gorootInstallDir, soname)
   225  	f, err := elf.Open(sopath)
   226  	if err != nil {
   227  		t.Fatal("elf.Open failed: ", err)
   228  	}
   229  	defer f.Close()
   230  	syms, err := f.Symbols()
   231  	if err != nil {
   232  		t.Errorf("error reading symbols %v", err)
   233  		return
   234  	}
   235  	for _, s := range syms {
   236  		if s.Name == ".dup" {
   237  			t.Fatalf("%s contains symbol called .dup", sopath)
   238  		}
   239  	}
   240  }
   241  
   242  // The install command should have created a "shlibname" file for the
   243  // listed packages (and runtime/cgo, and math on arm) indicating the
   244  // name of the shared library containing it.
   245  func TestShlibnameFiles(t *testing.T) {
   246  	pkgs := append([]string{}, minpkgs...)
   247  	pkgs = append(pkgs, "runtime/cgo")
   248  	if runtime.GOARCH == "arm" {
   249  		pkgs = append(pkgs, "math")
   250  	}
   251  	for _, pkg := range pkgs {
   252  		shlibnamefile := filepath.Join(gorootInstallDir, pkg+".shlibname")
   253  		contentsb, err := ioutil.ReadFile(shlibnamefile)
   254  		if err != nil {
   255  			t.Errorf("error reading shlibnamefile for %s: %v", pkg, err)
   256  			continue
   257  		}
   258  		contents := strings.TrimSpace(string(contentsb))
   259  		if contents != soname {
   260  			t.Errorf("shlibnamefile for %s has wrong contents: %q", pkg, contents)
   261  		}
   262  	}
   263  }
   264  
   265  // Is a given offset into the file contained in a loaded segment?
   266  func isOffsetLoaded(f *elf.File, offset uint64) bool {
   267  	for _, prog := range f.Progs {
   268  		if prog.Type == elf.PT_LOAD {
   269  			if prog.Off <= offset && offset < prog.Off+prog.Filesz {
   270  				return true
   271  			}
   272  		}
   273  	}
   274  	return false
   275  }
   276  
   277  func rnd(v int32, r int32) int32 {
   278  	if r <= 0 {
   279  		return v
   280  	}
   281  	v += r - 1
   282  	c := v % r
   283  	if c < 0 {
   284  		c += r
   285  	}
   286  	v -= c
   287  	return v
   288  }
   289  
   290  func readwithpad(r io.Reader, sz int32) ([]byte, error) {
   291  	data := make([]byte, rnd(sz, 4))
   292  	_, err := io.ReadFull(r, data)
   293  	if err != nil {
   294  		return nil, err
   295  	}
   296  	data = data[:sz]
   297  	return data, nil
   298  }
   299  
   300  type note struct {
   301  	name    string
   302  	tag     int32
   303  	desc    string
   304  	section *elf.Section
   305  }
   306  
   307  // Read all notes from f. As ELF section names are not supposed to be special, one
   308  // looks for a particular note by scanning all SHT_NOTE sections looking for a note
   309  // with a particular "name" and "tag".
   310  func readNotes(f *elf.File) ([]*note, error) {
   311  	var notes []*note
   312  	for _, sect := range f.Sections {
   313  		if sect.Type != elf.SHT_NOTE {
   314  			continue
   315  		}
   316  		r := sect.Open()
   317  		for {
   318  			var namesize, descsize, tag int32
   319  			err := binary.Read(r, f.ByteOrder, &namesize)
   320  			if err != nil {
   321  				if err == io.EOF {
   322  					break
   323  				}
   324  				return nil, fmt.Errorf("read namesize failed: %v", err)
   325  			}
   326  			err = binary.Read(r, f.ByteOrder, &descsize)
   327  			if err != nil {
   328  				return nil, fmt.Errorf("read descsize failed: %v", err)
   329  			}
   330  			err = binary.Read(r, f.ByteOrder, &tag)
   331  			if err != nil {
   332  				return nil, fmt.Errorf("read type failed: %v", err)
   333  			}
   334  			name, err := readwithpad(r, namesize)
   335  			if err != nil {
   336  				return nil, fmt.Errorf("read name failed: %v", err)
   337  			}
   338  			desc, err := readwithpad(r, descsize)
   339  			if err != nil {
   340  				return nil, fmt.Errorf("read desc failed: %v", err)
   341  			}
   342  			notes = append(notes, &note{name: string(name), tag: tag, desc: string(desc), section: sect})
   343  		}
   344  	}
   345  	return notes, nil
   346  }
   347  
   348  func dynStrings(t *testing.T, path string, flag elf.DynTag) []string {
   349  	f, err := elf.Open(path)
   350  	defer f.Close()
   351  	if err != nil {
   352  		t.Fatalf("elf.Open(%q) failed: %v", path, err)
   353  	}
   354  	dynstrings, err := f.DynString(flag)
   355  	if err != nil {
   356  		t.Fatalf("DynString(%s) failed on %s: %v", flag, path, err)
   357  	}
   358  	return dynstrings
   359  }
   360  
   361  func AssertIsLinkedToRegexp(t *testing.T, path string, re *regexp.Regexp) {
   362  	for _, dynstring := range dynStrings(t, path, elf.DT_NEEDED) {
   363  		if re.MatchString(dynstring) {
   364  			return
   365  		}
   366  	}
   367  	t.Errorf("%s is not linked to anything matching %v", path, re)
   368  }
   369  
   370  func AssertIsLinkedTo(t *testing.T, path, lib string) {
   371  	AssertIsLinkedToRegexp(t, path, regexp.MustCompile(regexp.QuoteMeta(lib)))
   372  }
   373  
   374  func AssertHasRPath(t *testing.T, path, dir string) {
   375  	for _, tag := range []elf.DynTag{elf.DT_RPATH, elf.DT_RUNPATH} {
   376  		for _, dynstring := range dynStrings(t, path, tag) {
   377  			for _, rpath := range strings.Split(dynstring, ":") {
   378  				if filepath.Clean(rpath) == filepath.Clean(dir) {
   379  					return
   380  				}
   381  			}
   382  		}
   383  	}
   384  	t.Errorf("%s does not have rpath %s", path, dir)
   385  }
   386  
   387  // Build a trivial program that links against the shared runtime and check it runs.
   388  func TestTrivialExecutable(t *testing.T) {
   389  	goCmd(t, "install", "-linkshared", "trivial")
   390  	run(t, "trivial executable", "./bin/trivial")
   391  	AssertIsLinkedTo(t, "./bin/trivial", soname)
   392  	AssertHasRPath(t, "./bin/trivial", gorootInstallDir)
   393  }
   394  
   395  // Build a trivial program in PIE mode that links against the shared runtime and check it runs.
   396  func TestTrivialExecutablePIE(t *testing.T) {
   397  	goCmd(t, "build", "-buildmode=pie", "-o", "trivial.pie", "-linkshared", "trivial")
   398  	run(t, "trivial executable", "./trivial.pie")
   399  	AssertIsLinkedTo(t, "./trivial.pie", soname)
   400  	AssertHasRPath(t, "./trivial.pie", gorootInstallDir)
   401  }
   402  
   403  // Build an executable that uses cgo linked against the shared runtime and check it
   404  // runs.
   405  func TestCgoExecutable(t *testing.T) {
   406  	goCmd(t, "install", "-linkshared", "execgo")
   407  	run(t, "cgo executable", "./bin/execgo")
   408  }
   409  
   410  func checkPIE(t *testing.T, name string) {
   411  	f, err := elf.Open(name)
   412  	if err != nil {
   413  		t.Fatal("elf.Open failed: ", err)
   414  	}
   415  	defer f.Close()
   416  	if f.Type != elf.ET_DYN {
   417  		t.Errorf("%s has type %v, want ET_DYN", name, f.Type)
   418  	}
   419  	if hasDynTag(f, elf.DT_TEXTREL) {
   420  		t.Errorf("%s has DT_TEXTREL set", name)
   421  	}
   422  }
   423  
   424  func TestTrivialPIE(t *testing.T) {
   425  	name := "trivial_pie"
   426  	goCmd(t, "build", "-buildmode=pie", "-o="+name, "trivial")
   427  	defer os.Remove(name)
   428  	run(t, name, "./"+name)
   429  	checkPIE(t, name)
   430  }
   431  
   432  func TestCgoPIE(t *testing.T) {
   433  	name := "cgo_pie"
   434  	goCmd(t, "build", "-buildmode=pie", "-o="+name, "execgo")
   435  	defer os.Remove(name)
   436  	run(t, name, "./"+name)
   437  	checkPIE(t, name)
   438  }
   439  
   440  // Build a GOPATH package into a shared library that links against the goroot runtime
   441  // and an executable that links against both.
   442  func TestGopathShlib(t *testing.T) {
   443  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "depBase")
   444  	AssertIsLinkedTo(t, filepath.Join(gopathInstallDir, "libdepBase.so"), soname)
   445  	goCmd(t, "install", "-linkshared", "exe")
   446  	AssertIsLinkedTo(t, "./bin/exe", soname)
   447  	AssertIsLinkedTo(t, "./bin/exe", "libdepBase.so")
   448  	AssertHasRPath(t, "./bin/exe", gorootInstallDir)
   449  	AssertHasRPath(t, "./bin/exe", gopathInstallDir)
   450  	// And check it runs.
   451  	run(t, "executable linked to GOPATH library", "./bin/exe")
   452  }
   453  
   454  // The shared library contains a note listing the packages it contains in a section
   455  // that is not mapped into memory.
   456  func testPkgListNote(t *testing.T, f *elf.File, note *note) {
   457  	if note.section.Flags != 0 {
   458  		t.Errorf("package list section has flags %v", note.section.Flags)
   459  	}
   460  	if isOffsetLoaded(f, note.section.Offset) {
   461  		t.Errorf("package list section contained in PT_LOAD segment")
   462  	}
   463  	if note.desc != "depBase\n" {
   464  		t.Errorf("incorrect package list %q", note.desc)
   465  	}
   466  }
   467  
   468  // The shared library contains a note containing the ABI hash that is mapped into
   469  // memory and there is a local symbol called go.link.abihashbytes that points 16
   470  // bytes into it.
   471  func testABIHashNote(t *testing.T, f *elf.File, note *note) {
   472  	if note.section.Flags != elf.SHF_ALLOC {
   473  		t.Errorf("abi hash section has flags %v", note.section.Flags)
   474  	}
   475  	if !isOffsetLoaded(f, note.section.Offset) {
   476  		t.Errorf("abihash section not contained in PT_LOAD segment")
   477  	}
   478  	var hashbytes elf.Symbol
   479  	symbols, err := f.Symbols()
   480  	if err != nil {
   481  		t.Errorf("error reading symbols %v", err)
   482  		return
   483  	}
   484  	for _, sym := range symbols {
   485  		if sym.Name == "go.link.abihashbytes" {
   486  			hashbytes = sym
   487  		}
   488  	}
   489  	if hashbytes.Name == "" {
   490  		t.Errorf("no symbol called go.link.abihashbytes")
   491  		return
   492  	}
   493  	if elf.ST_BIND(hashbytes.Info) != elf.STB_LOCAL {
   494  		t.Errorf("%s has incorrect binding %v", hashbytes.Name, elf.ST_BIND(hashbytes.Info))
   495  	}
   496  	if f.Sections[hashbytes.Section] != note.section {
   497  		t.Errorf("%s has incorrect section %v", hashbytes.Name, f.Sections[hashbytes.Section].Name)
   498  	}
   499  	if hashbytes.Value-note.section.Addr != 16 {
   500  		t.Errorf("%s has incorrect offset into section %d", hashbytes.Name, hashbytes.Value-note.section.Addr)
   501  	}
   502  }
   503  
   504  // A Go shared library contains a note indicating which other Go shared libraries it
   505  // was linked against in an unmapped section.
   506  func testDepsNote(t *testing.T, f *elf.File, note *note) {
   507  	if note.section.Flags != 0 {
   508  		t.Errorf("package list section has flags %v", note.section.Flags)
   509  	}
   510  	if isOffsetLoaded(f, note.section.Offset) {
   511  		t.Errorf("package list section contained in PT_LOAD segment")
   512  	}
   513  	// libdepBase.so just links against the lib containing the runtime.
   514  	if note.desc != soname {
   515  		t.Errorf("incorrect dependency list %q", note.desc)
   516  	}
   517  }
   518  
   519  // The shared library contains notes with defined contents; see above.
   520  func TestNotes(t *testing.T) {
   521  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "depBase")
   522  	f, err := elf.Open(filepath.Join(gopathInstallDir, "libdepBase.so"))
   523  	if err != nil {
   524  		t.Fatal(err)
   525  	}
   526  	defer f.Close()
   527  	notes, err := readNotes(f)
   528  	if err != nil {
   529  		t.Fatal(err)
   530  	}
   531  	pkgListNoteFound := false
   532  	abiHashNoteFound := false
   533  	depsNoteFound := false
   534  	for _, note := range notes {
   535  		if note.name != "Go\x00\x00" {
   536  			continue
   537  		}
   538  		switch note.tag {
   539  		case 1: // ELF_NOTE_GOPKGLIST_TAG
   540  			if pkgListNoteFound {
   541  				t.Error("multiple package list notes")
   542  			}
   543  			testPkgListNote(t, f, note)
   544  			pkgListNoteFound = true
   545  		case 2: // ELF_NOTE_GOABIHASH_TAG
   546  			if abiHashNoteFound {
   547  				t.Error("multiple abi hash notes")
   548  			}
   549  			testABIHashNote(t, f, note)
   550  			abiHashNoteFound = true
   551  		case 3: // ELF_NOTE_GODEPS_TAG
   552  			if depsNoteFound {
   553  				t.Error("multiple abi hash notes")
   554  			}
   555  			testDepsNote(t, f, note)
   556  			depsNoteFound = true
   557  		}
   558  	}
   559  	if !pkgListNoteFound {
   560  		t.Error("package list note not found")
   561  	}
   562  	if !abiHashNoteFound {
   563  		t.Error("abi hash note not found")
   564  	}
   565  	if !depsNoteFound {
   566  		t.Error("deps note not found")
   567  	}
   568  }
   569  
   570  // Build a GOPATH package (depBase) into a shared library that links against the goroot
   571  // runtime, another package (dep2) that links against the first, and and an
   572  // executable that links against dep2.
   573  func TestTwoGopathShlibs(t *testing.T) {
   574  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "depBase")
   575  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "dep2")
   576  	goCmd(t, "install", "-linkshared", "exe2")
   577  	run(t, "executable linked to GOPATH library", "./bin/exe2")
   578  }
   579  
   580  func TestThreeGopathShlibs(t *testing.T) {
   581  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "depBase")
   582  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "dep2")
   583  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "dep3")
   584  	goCmd(t, "install", "-linkshared", "exe3")
   585  	run(t, "executable linked to GOPATH library", "./bin/exe3")
   586  }
   587  
   588  // If gccgo is not available or not new enough call t.Skip. Otherwise,
   589  // return a build.Context that is set up for gccgo.
   590  func prepGccgo(t *testing.T) build.Context {
   591  	gccgoName := os.Getenv("GCCGO")
   592  	if gccgoName == "" {
   593  		gccgoName = "gccgo"
   594  	}
   595  	gccgoPath, err := exec.LookPath(gccgoName)
   596  	if err != nil {
   597  		t.Skip("gccgo not found")
   598  	}
   599  	cmd := exec.Command(gccgoPath, "-dumpversion")
   600  	output, err := cmd.CombinedOutput()
   601  	if err != nil {
   602  		t.Fatalf("%s -dumpversion failed: %v\n%s", gccgoPath, err, output)
   603  	}
   604  	if string(output) < "5" {
   605  		t.Skipf("gccgo too old (%s)", strings.TrimSpace(string(output)))
   606  	}
   607  	gccgoContext := build.Default
   608  	gccgoContext.InstallSuffix = suffix + "_fPIC"
   609  	gccgoContext.Compiler = "gccgo"
   610  	gccgoContext.GOPATH = os.Getenv("GOPATH")
   611  	return gccgoContext
   612  }
   613  
   614  // Build a GOPATH package into a shared library with gccgo and an executable that
   615  // links against it.
   616  func TestGoPathShlibGccgo(t *testing.T) {
   617  	gccgoContext := prepGccgo(t)
   618  
   619  	libgoRE := regexp.MustCompile("libgo.so.[0-9]+")
   620  
   621  	depP, err := gccgoContext.Import("depBase", ".", build.ImportComment)
   622  	if err != nil {
   623  		t.Fatalf("import failed: %v", err)
   624  	}
   625  	gccgoInstallDir := filepath.Join(depP.PkgTargetRoot, "shlibs")
   626  	goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "depBase")
   627  	AssertIsLinkedToRegexp(t, filepath.Join(gccgoInstallDir, "libdepBase.so"), libgoRE)
   628  	goCmd(t, "install", "-compiler=gccgo", "-linkshared", "exe")
   629  	AssertIsLinkedToRegexp(t, "./bin/exe", libgoRE)
   630  	AssertIsLinkedTo(t, "./bin/exe", "libdepBase.so")
   631  	AssertHasRPath(t, "./bin/exe", gccgoInstallDir)
   632  	// And check it runs.
   633  	run(t, "gccgo-built", "./bin/exe")
   634  }
   635  
   636  // The gccgo version of TestTwoGopathShlibs: build a GOPATH package into a shared
   637  // library with gccgo, another GOPATH package that depends on the first and an
   638  // executable that links the second library.
   639  func TestTwoGopathShlibsGccgo(t *testing.T) {
   640  	gccgoContext := prepGccgo(t)
   641  
   642  	libgoRE := regexp.MustCompile("libgo.so.[0-9]+")
   643  
   644  	depP, err := gccgoContext.Import("depBase", ".", build.ImportComment)
   645  	if err != nil {
   646  		t.Fatalf("import failed: %v", err)
   647  	}
   648  	gccgoInstallDir := filepath.Join(depP.PkgTargetRoot, "shlibs")
   649  	goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "depBase")
   650  	goCmd(t, "install", "-compiler=gccgo", "-buildmode=shared", "-linkshared", "dep2")
   651  	goCmd(t, "install", "-compiler=gccgo", "-linkshared", "exe2")
   652  
   653  	AssertIsLinkedToRegexp(t, filepath.Join(gccgoInstallDir, "libdepBase.so"), libgoRE)
   654  	AssertIsLinkedToRegexp(t, filepath.Join(gccgoInstallDir, "libdep2.so"), libgoRE)
   655  	AssertIsLinkedTo(t, filepath.Join(gccgoInstallDir, "libdep2.so"), "libdepBase.so")
   656  	AssertIsLinkedToRegexp(t, "./bin/exe2", libgoRE)
   657  	AssertIsLinkedTo(t, "./bin/exe2", "libdep2")
   658  	AssertIsLinkedTo(t, "./bin/exe2", "libdepBase.so")
   659  
   660  	// And check it runs.
   661  	run(t, "gccgo-built", "./bin/exe2")
   662  }
   663  
   664  // Testing rebuilding of shared libraries when they are stale is a bit more
   665  // complicated that it seems like it should be. First, we make everything "old": but
   666  // only a few seconds old, or it might be older than gc (or the runtime source) and
   667  // everything will get rebuilt. Then define a timestamp slightly newer than this
   668  // time, which is what we set the mtime to of a file to cause it to be seen as new,
   669  // and finally another slightly even newer one that we can compare files against to
   670  // see if they have been rebuilt.
   671  var oldTime = time.Now().Add(-9 * time.Second)
   672  var nearlyNew = time.Now().Add(-6 * time.Second)
   673  var stampTime = time.Now().Add(-3 * time.Second)
   674  
   675  // resetFileStamps makes "everything" (bin, src, pkg from GOPATH and the
   676  // test-specific parts of GOROOT) appear old.
   677  func resetFileStamps() {
   678  	chtime := func(path string, info os.FileInfo, err error) error {
   679  		return os.Chtimes(path, oldTime, oldTime)
   680  	}
   681  	reset := func(path string) {
   682  		if err := filepath.Walk(path, chtime); err != nil {
   683  			log.Fatalf("resetFileStamps failed: %v", err)
   684  		}
   685  
   686  	}
   687  	reset("bin")
   688  	reset("pkg")
   689  	reset("src")
   690  	reset(gorootInstallDir)
   691  }
   692  
   693  // touch makes path newer than the "old" time stamp used by resetFileStamps.
   694  func touch(path string) {
   695  	if err := os.Chtimes(path, nearlyNew, nearlyNew); err != nil {
   696  		log.Fatalf("os.Chtimes failed: %v", err)
   697  	}
   698  }
   699  
   700  // isNew returns if the path is newer than the time stamp used by touch.
   701  func isNew(path string) bool {
   702  	fi, err := os.Stat(path)
   703  	if err != nil {
   704  		log.Fatalf("os.Stat failed: %v", err)
   705  	}
   706  	return fi.ModTime().After(stampTime)
   707  }
   708  
   709  // Fail unless path has been rebuilt (i.e. is newer than the time stamp used by
   710  // isNew)
   711  func AssertRebuilt(t *testing.T, msg, path string) {
   712  	if !isNew(path) {
   713  		t.Errorf("%s was not rebuilt (%s)", msg, path)
   714  	}
   715  }
   716  
   717  // Fail if path has been rebuilt (i.e. is newer than the time stamp used by isNew)
   718  func AssertNotRebuilt(t *testing.T, msg, path string) {
   719  	if isNew(path) {
   720  		t.Errorf("%s was rebuilt (%s)", msg, path)
   721  	}
   722  }
   723  
   724  func TestRebuilding(t *testing.T) {
   725  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "depBase")
   726  	goCmd(t, "install", "-linkshared", "exe")
   727  
   728  	// If the source is newer than both the .a file and the .so, both are rebuilt.
   729  	resetFileStamps()
   730  	touch("src/depBase/dep.go")
   731  	goCmd(t, "install", "-linkshared", "exe")
   732  	AssertRebuilt(t, "new source", filepath.Join(gopathInstallDir, "depBase.a"))
   733  	AssertRebuilt(t, "new source", filepath.Join(gopathInstallDir, "libdepBase.so"))
   734  
   735  	// If the .a file is newer than the .so, the .so is rebuilt (but not the .a)
   736  	resetFileStamps()
   737  	touch(filepath.Join(gopathInstallDir, "depBase.a"))
   738  	goCmd(t, "install", "-linkshared", "exe")
   739  	AssertNotRebuilt(t, "new .a file", filepath.Join(gopathInstallDir, "depBase.a"))
   740  	AssertRebuilt(t, "new .a file", filepath.Join(gopathInstallDir, "libdepBase.so"))
   741  }
   742  
   743  func appendFile(path, content string) {
   744  	f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0660)
   745  	if err != nil {
   746  		log.Fatalf("os.OpenFile failed: %v", err)
   747  	}
   748  	defer func() {
   749  		err := f.Close()
   750  		if err != nil {
   751  			log.Fatalf("f.Close failed: %v", err)
   752  		}
   753  	}()
   754  	_, err = f.WriteString(content)
   755  	if err != nil {
   756  		log.Fatalf("f.WriteString failed: %v", err)
   757  	}
   758  }
   759  
   760  func TestABIChecking(t *testing.T) {
   761  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "depBase")
   762  	goCmd(t, "install", "-linkshared", "exe")
   763  
   764  	// If we make an ABI-breaking change to depBase and rebuild libp.so but not exe,
   765  	// exe will abort with a complaint on startup.
   766  	// This assumes adding an exported function breaks ABI, which is not true in
   767  	// some senses but suffices for the narrow definition of ABI compatibility the
   768  	// toolchain uses today.
   769  	resetFileStamps()
   770  	appendFile("src/depBase/dep.go", "func ABIBreak() {}\n")
   771  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "depBase")
   772  	c := exec.Command("./bin/exe")
   773  	output, err := c.CombinedOutput()
   774  	if err == nil {
   775  		t.Fatal("executing exe did not fail after ABI break")
   776  	}
   777  	scanner := bufio.NewScanner(bytes.NewReader(output))
   778  	foundMsg := false
   779  	const wantLine = "abi mismatch detected between the executable and libdepBase.so"
   780  	for scanner.Scan() {
   781  		if scanner.Text() == wantLine {
   782  			foundMsg = true
   783  			break
   784  		}
   785  	}
   786  	if err = scanner.Err(); err != nil {
   787  		t.Errorf("scanner encountered error: %v", err)
   788  	}
   789  	if !foundMsg {
   790  		t.Fatalf("exe failed, but without line %q; got output:\n%s", wantLine, output)
   791  	}
   792  
   793  	// Rebuilding exe makes it work again.
   794  	goCmd(t, "install", "-linkshared", "exe")
   795  	run(t, "rebuilt exe", "./bin/exe")
   796  
   797  	// If we make a change which does not break ABI (such as adding an unexported
   798  	// function) and rebuild libdepBase.so, exe still works.
   799  	resetFileStamps()
   800  	appendFile("src/depBase/dep.go", "func noABIBreak() {}\n")
   801  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "depBase")
   802  	run(t, "after non-ABI breaking change", "./bin/exe")
   803  }
   804  
   805  // If a package 'explicit' imports a package 'implicit', building
   806  // 'explicit' into a shared library implicitly includes implicit in
   807  // the shared library. Building an executable that imports both
   808  // explicit and implicit builds the code from implicit into the
   809  // executable rather than fetching it from the shared library. The
   810  // link still succeeds and the executable still runs though.
   811  func TestImplicitInclusion(t *testing.T) {
   812  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "explicit")
   813  	goCmd(t, "install", "-linkshared", "implicitcmd")
   814  	run(t, "running executable linked against library that contains same package as it", "./bin/implicitcmd")
   815  }
   816  
   817  // Tests to make sure that the type fields of empty interfaces and itab
   818  // fields of nonempty interfaces are unique even across modules,
   819  // so that interface equality works correctly.
   820  func TestInterface(t *testing.T) {
   821  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "iface_a")
   822  	// Note: iface_i gets installed implicitly as a dependency of iface_a.
   823  	goCmd(t, "install", "-buildmode=shared", "-linkshared", "iface_b")
   824  	goCmd(t, "install", "-linkshared", "iface")
   825  	run(t, "running type/itab uniqueness tester", "./bin/iface")
   826  }