|
| 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 | + "errors" |
| 12 | + "flag" |
| 13 | + "fmt" |
| 14 | + "go/build" |
| 15 | + "io/ioutil" |
| 16 | + "log" |
| 17 | + "math/rand" |
| 18 | + "os" |
| 19 | + "os/exec" |
| 20 | + "path/filepath" |
| 21 | + "strings" |
| 22 | + "testing" |
| 23 | + "time" |
| 24 | +) |
| 25 | + |
| 26 | +var gopathInstallDir, gorootInstallDir, suffix string |
| 27 | + |
| 28 | +// This is the smallest set of packages we can link into a shared |
| 29 | +// library (runtime/cgo is built implicitly). |
| 30 | +var minpkgs = []string{"runtime", "sync/atomic"} |
| 31 | +var soname = "libruntime,sync-atomic.so" |
| 32 | + |
| 33 | +// run runs a command and calls t.Errorf if it fails. |
| 34 | +func run(t *testing.T, msg string, args ...string) { |
| 35 | + c := exec.Command(args[0], args[1:]...) |
| 36 | + if output, err := c.CombinedOutput(); err != nil { |
| 37 | + t.Errorf("executing %s (%s) failed %s:\n%s", strings.Join(args, " "), msg, err, output) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +// goCmd invokes the go tool with the installsuffix set up by TestMain. It calls |
| 42 | +// t.Errorf if the command fails. |
| 43 | +func goCmd(t *testing.T, args ...string) { |
| 44 | + newargs := []string{args[0], "-installsuffix=" + suffix} |
| 45 | + if testing.Verbose() { |
| 46 | + newargs = append(newargs, "-v") |
| 47 | + } |
| 48 | + newargs = append(newargs, args[1:]...) |
| 49 | + c := exec.Command("go", newargs...) |
| 50 | + if testing.Verbose() { |
| 51 | + fmt.Printf("+ go %s\n", strings.Join(newargs, " ")) |
| 52 | + c.Stdout = os.Stdout |
| 53 | + c.Stderr = os.Stderr |
| 54 | + } |
| 55 | + if output, err := c.CombinedOutput(); err != nil { |
| 56 | + t.Errorf("executing %s failed %v:\n%s", strings.Join(c.Args, " "), err, output) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +// TestMain calls testMain so that the latter can use defer (TestMain exits with os.Exit). |
| 61 | +func testMain(m *testing.M) (int, error) { |
| 62 | + // Because go install -buildmode=shared $standard_library_package always |
| 63 | + // installs into $GOROOT, here are some gymnastics to come up with a unique |
| 64 | + // installsuffix to use in this test that we can clean up afterwards. |
| 65 | + myContext := build.Default |
| 66 | + runtimeP, err := myContext.Import("runtime", ".", build.ImportComment) |
| 67 | + if err != nil { |
| 68 | + return 0, fmt.Errorf("import failed: %v", err) |
| 69 | + } |
| 70 | + for i := 0; i < 10000; i++ { |
| 71 | + try := fmt.Sprintf("%s_%d_dynlink", runtimeP.PkgTargetRoot, rand.Int63()) |
| 72 | + err = os.Mkdir(try, 0700) |
| 73 | + if os.IsExist(err) { |
| 74 | + continue |
| 75 | + } |
| 76 | + if err == nil { |
| 77 | + gorootInstallDir = try |
| 78 | + } |
| 79 | + break |
| 80 | + } |
| 81 | + if err != nil { |
| 82 | + return 0, fmt.Errorf("can't create temporary directory: %v", err) |
| 83 | + } |
| 84 | + if gorootInstallDir == "" { |
| 85 | + return 0, errors.New("could not create temporary directory after 10000 tries") |
| 86 | + } |
| 87 | + defer os.RemoveAll(gorootInstallDir) |
| 88 | + |
| 89 | + // Some tests need to edit the source in GOPATH, so copy this directory to a |
| 90 | + // temporary directory and chdir to that. |
| 91 | + scratchDir, err := ioutil.TempDir("", "testshared") |
| 92 | + if err != nil { |
| 93 | + return 0, fmt.Errorf("TempDir failed: %v", err) |
| 94 | + } |
| 95 | + defer os.RemoveAll(scratchDir) |
| 96 | + err = filepath.Walk(".", func(path string, info os.FileInfo, err error) error { |
| 97 | + scratchPath := filepath.Join(scratchDir, path) |
| 98 | + if info.IsDir() { |
| 99 | + if path == "." { |
| 100 | + return nil |
| 101 | + } |
| 102 | + return os.Mkdir(scratchPath, info.Mode()) |
| 103 | + } else { |
| 104 | + fromBytes, err := ioutil.ReadFile(path) |
| 105 | + if err != nil { |
| 106 | + return err |
| 107 | + } |
| 108 | + return ioutil.WriteFile(scratchPath, fromBytes, info.Mode()) |
| 109 | + } |
| 110 | + }) |
| 111 | + if err != nil { |
| 112 | + return 0, fmt.Errorf("walk failed: %v", err) |
| 113 | + } |
| 114 | + os.Setenv("GOPATH", scratchDir) |
| 115 | + myContext.GOPATH = scratchDir |
| 116 | + os.Chdir(scratchDir) |
| 117 | + |
| 118 | + // All tests depend on runtime being built into a shared library. Because |
| 119 | + // that takes a few seconds, do it here and have all tests use the version |
| 120 | + // built here. |
| 121 | + suffix = strings.Split(filepath.Base(gorootInstallDir), "_")[2] |
| 122 | + goCmd(nil, append([]string{"install", "-buildmode=shared"}, minpkgs...)...) |
| 123 | + |
| 124 | + myContext.InstallSuffix = suffix + "_dynlink" |
| 125 | + depP, err := myContext.Import("dep", ".", build.ImportComment) |
| 126 | + if err != nil { |
| 127 | + return 0, fmt.Errorf("import failed: %v", err) |
| 128 | + } |
| 129 | + gopathInstallDir = depP.PkgTargetRoot |
| 130 | + return m.Run(), nil |
| 131 | +} |
| 132 | + |
| 133 | +func TestMain(m *testing.M) { |
| 134 | + flag.Parse() |
| 135 | + exitCode, err := testMain(m) |
| 136 | + if err != nil { |
| 137 | + log.Fatal(err) |
| 138 | + } |
| 139 | + os.Exit(exitCode) |
| 140 | +} |
| 141 | + |
| 142 | +// The shared library was built at the expected location. |
| 143 | +func TestSOBuilt(t *testing.T) { |
| 144 | + _, err := os.Stat(filepath.Join(gorootInstallDir, soname)) |
| 145 | + if err != nil { |
| 146 | + t.Error(err) |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +// The install command should have created a "shlibname" file for the |
| 151 | +// listed packages (and runtime/cgo) indicating the name of the shared |
| 152 | +// library containing it. |
| 153 | +func TestShlibnameFiles(t *testing.T) { |
| 154 | + pkgs := append([]string{}, minpkgs...) |
| 155 | + pkgs = append(pkgs, "runtime/cgo") |
| 156 | + for _, pkg := range pkgs { |
| 157 | + shlibnamefile := filepath.Join(gorootInstallDir, pkg+".shlibname") |
| 158 | + contentsb, err := ioutil.ReadFile(shlibnamefile) |
| 159 | + if err != nil { |
| 160 | + t.Errorf("error reading shlibnamefile for %s: %v", pkg, err) |
| 161 | + continue |
| 162 | + } |
| 163 | + contents := strings.TrimSpace(string(contentsb)) |
| 164 | + if contents != soname { |
| 165 | + t.Errorf("shlibnamefile for %s has wrong contents: %q", pkg, contents) |
| 166 | + } |
| 167 | + } |
| 168 | +} |
| 169 | + |
| 170 | +func dynStrings(path string, flag elf.DynTag) []string { |
| 171 | + f, err := elf.Open(path) |
| 172 | + defer f.Close() |
| 173 | + if err != nil { |
| 174 | + log.Fatal("elf.Open failed: ", err) |
| 175 | + } |
| 176 | + dynstrings, err := f.DynString(flag) |
| 177 | + if err != nil { |
| 178 | + log.Fatal("dynstring failed: ", err) |
| 179 | + } |
| 180 | + return dynstrings |
| 181 | +} |
| 182 | + |
| 183 | +func AssertIsLinkedTo(t *testing.T, path, lib string) { |
| 184 | + for _, dynstring := range dynStrings(path, elf.DT_NEEDED) { |
| 185 | + if dynstring == lib { |
| 186 | + return |
| 187 | + } |
| 188 | + } |
| 189 | + t.Errorf("%s is not linked to %s", path, lib) |
| 190 | +} |
| 191 | + |
| 192 | +func AssertHasRPath(t *testing.T, path, dir string) { |
| 193 | + for _, dynstring := range dynStrings(path, elf.DT_RPATH) { |
| 194 | + for _, rpath := range strings.Split(dynstring, ":") { |
| 195 | + if filepath.Clean(rpath) == filepath.Clean(dir) { |
| 196 | + return |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + t.Errorf("%s does not have rpath %s", path, dir) |
| 201 | +} |
| 202 | + |
| 203 | +// Build a trivial program that links against the shared runtime and check it runs. |
| 204 | +func TestTrivialExecutable(t *testing.T) { |
| 205 | + goCmd(t, "install", "-linkshared", "trivial") |
| 206 | + run(t, "trivial executable", "./bin/trivial") |
| 207 | + AssertIsLinkedTo(t, "./bin/trivial", soname) |
| 208 | + AssertHasRPath(t, "./bin/trivial", gorootInstallDir) |
| 209 | +} |
| 210 | + |
| 211 | +// Build a GOPATH package into a shared library that links against the goroot runtime |
| 212 | +// and an executable that links against both. |
| 213 | +func TestGOPathShlib(t *testing.T) { |
| 214 | + goCmd(t, "install", "-buildmode=shared", "-linkshared", "dep") |
| 215 | + AssertIsLinkedTo(t, filepath.Join(gopathInstallDir, "libdep.so"), soname) |
| 216 | + goCmd(t, "install", "-linkshared", "exe") |
| 217 | + AssertIsLinkedTo(t, "./bin/exe", soname) |
| 218 | + AssertIsLinkedTo(t, "./bin/exe", "libdep.so") |
| 219 | + AssertHasRPath(t, "./bin/exe", gorootInstallDir) |
| 220 | + AssertHasRPath(t, "./bin/exe", gopathInstallDir) |
| 221 | + // And check it runs. |
| 222 | + run(t, "executable linked to GOPATH library", "./bin/exe") |
| 223 | +} |
| 224 | + |
| 225 | +// Testing rebuilding of shared libraries when they are stale is a bit more |
| 226 | +// complicated that it seems like it should be. First, we make everything "old": but |
| 227 | +// only a few seconds old, or it might be older than 6g (or the runtime source) and |
| 228 | +// everything will get rebuilt. Then define a timestamp slightly newer than this |
| 229 | +// time, which is what we set the mtime to of a file to cause it to be seen as new, |
| 230 | +// and finally another slightly even newer one that we can compare files against to |
| 231 | +// see if they have been rebuilt. |
| 232 | +var oldTime = time.Now().Add(-9 * time.Second) |
| 233 | +var nearlyNew = time.Now().Add(-6 * time.Second) |
| 234 | +var stampTime = time.Now().Add(-3 * time.Second) |
| 235 | + |
| 236 | +// resetFileStamps makes "everything" (bin, src, pkg from GOPATH and the |
| 237 | +// test-specific parts of GOROOT) appear old. |
| 238 | +func resetFileStamps() { |
| 239 | + chtime := func(path string, info os.FileInfo, err error) error { |
| 240 | + return os.Chtimes(path, oldTime, oldTime) |
| 241 | + } |
| 242 | + reset := func(path string) { |
| 243 | + if err := filepath.Walk(path, chtime); err != nil { |
| 244 | + log.Fatalf("resetFileStamps failed: %v", err) |
| 245 | + } |
| 246 | + |
| 247 | + } |
| 248 | + reset("bin") |
| 249 | + reset("pkg") |
| 250 | + reset("src") |
| 251 | + reset(gorootInstallDir) |
| 252 | +} |
| 253 | + |
| 254 | +// touch makes path newer than the "old" time stamp used by resetFileStamps. |
| 255 | +func touch(path string) { |
| 256 | + if err := os.Chtimes(path, nearlyNew, nearlyNew); err != nil { |
| 257 | + log.Fatalf("os.Chtimes failed: %v", err) |
| 258 | + } |
| 259 | +} |
| 260 | + |
| 261 | +// isNew returns if the path is newer than the time stamp used by touch. |
| 262 | +func isNew(path string) bool { |
| 263 | + fi, err := os.Stat(path) |
| 264 | + if err != nil { |
| 265 | + log.Fatalf("os.Stat failed: %v", err) |
| 266 | + } |
| 267 | + return fi.ModTime().After(stampTime) |
| 268 | +} |
| 269 | + |
| 270 | +// Fail unless path has been rebuilt (i.e. is newer than the time stamp used by |
| 271 | +// isNew) |
| 272 | +func AssertRebuilt(t *testing.T, msg, path string) { |
| 273 | + if !isNew(path) { |
| 274 | + t.Errorf("%s was not rebuilt (%s)", msg, path) |
| 275 | + } |
| 276 | +} |
| 277 | + |
| 278 | +// Fail if path has been rebuilt (i.e. is newer than the time stamp used by isNew) |
| 279 | +func AssertNotRebuilt(t *testing.T, msg, path string) { |
| 280 | + if isNew(path) { |
| 281 | + t.Errorf("%s was rebuilt (%s)", msg, path) |
| 282 | + } |
| 283 | +} |
| 284 | + |
| 285 | +func TestRebuilding(t *testing.T) { |
| 286 | + goCmd(t, "install", "-buildmode=shared", "-linkshared", "dep") |
| 287 | + goCmd(t, "install", "-linkshared", "exe") |
| 288 | + |
| 289 | + // If the source is newer than both the .a file and the .so, both are rebuilt. |
| 290 | + resetFileStamps() |
| 291 | + touch("src/dep/dep.go") |
| 292 | + goCmd(t, "install", "-linkshared", "exe") |
| 293 | + AssertRebuilt(t, "new source", filepath.Join(gopathInstallDir, "dep.a")) |
| 294 | + AssertRebuilt(t, "new source", filepath.Join(gopathInstallDir, "libdep.so")) |
| 295 | + |
| 296 | + // If the .a file is newer than the .so, the .so is rebuilt (but not the .a) |
| 297 | + resetFileStamps() |
| 298 | + touch(filepath.Join(gopathInstallDir, "dep.a")) |
| 299 | + goCmd(t, "install", "-linkshared", "exe") |
| 300 | + AssertNotRebuilt(t, "new .a file", filepath.Join(gopathInstallDir, "dep.a")) |
| 301 | + AssertRebuilt(t, "new .a file", filepath.Join(gopathInstallDir, "libdep.so")) |
| 302 | +} |
| 303 | + |
| 304 | +func appendFile(path, content string) { |
| 305 | + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0660) |
| 306 | + if err != nil { |
| 307 | + log.Fatalf("os.OpenFile failed: %v", err) |
| 308 | + } |
| 309 | + defer func() { |
| 310 | + err := f.Close() |
| 311 | + if err != nil { |
| 312 | + log.Fatalf("f.Close failed: %v", err) |
| 313 | + } |
| 314 | + }() |
| 315 | + _, err = f.WriteString(content) |
| 316 | + if err != nil { |
| 317 | + log.Fatalf("f.WriteString failed: %v", err) |
| 318 | + } |
| 319 | +} |
| 320 | + |
| 321 | +func TestABIChecking(t *testing.T) { |
| 322 | + goCmd(t, "install", "-buildmode=shared", "-linkshared", "dep") |
| 323 | + goCmd(t, "install", "-linkshared", "exe") |
| 324 | + |
| 325 | + // If we make an ABI-breaking change to dep and rebuild libp.so but not exe, |
| 326 | + // exe will abort with a complaint on startup. |
| 327 | + // This assumes adding an exported function breaks ABI, which is not true in |
| 328 | + // some senses but suffices for the narrow definition of ABI compatiblity the |
| 329 | + // toolchain uses today. |
| 330 | + appendFile("src/dep/dep.go", "func ABIBreak() {}\n") |
| 331 | + goCmd(t, "install", "-buildmode=shared", "-linkshared", "dep") |
| 332 | + c := exec.Command("./bin/exe") |
| 333 | + output, err := c.CombinedOutput() |
| 334 | + if err == nil { |
| 335 | + t.Fatal("executing exe did not fail after ABI break") |
| 336 | + } |
| 337 | + scanner := bufio.NewScanner(bytes.NewReader(output)) |
| 338 | + foundMsg := false |
| 339 | + const wantLine = "abi mismatch detected between the executable and libdep.so" |
| 340 | + for scanner.Scan() { |
| 341 | + if scanner.Text() == wantLine { |
| 342 | + foundMsg = true |
| 343 | + break |
| 344 | + } |
| 345 | + } |
| 346 | + if err = scanner.Err(); err != nil { |
| 347 | + t.Errorf("scanner encountered error: %v", err) |
| 348 | + } |
| 349 | + if !foundMsg { |
| 350 | + t.Fatalf("exe failed, but without line %q; got output:\n%s", wantLine, output) |
| 351 | + } |
| 352 | + |
| 353 | + // Rebuilding exe makes it work again. |
| 354 | + goCmd(t, "install", "-linkshared", "exe") |
| 355 | + run(t, "rebuilt exe", "./bin/exe") |
| 356 | + |
| 357 | + // If we make a change which does not break ABI (such as adding an unexported |
| 358 | + // function) and rebuild libdep.so, exe still works. |
| 359 | + appendFile("src/dep/dep.go", "func noABIBreak() {}\n") |
| 360 | + goCmd(t, "install", "-buildmode=shared", "-linkshared", "dep") |
| 361 | + run(t, "after non-ABI breaking change", "./bin/exe") |
| 362 | +} |
0 commit comments