1
0
mirror of https://github.com/golang/go synced 2024-09-30 14:08:32 -06:00

[dev.link] cmd/oldlink: remove tests

They are essentially duplicates of cmd/link tests. No need to
test twice.

Change-Id: I91fdc996f5e160631648ee63341c4e46bb6cc54d
Reviewed-on: https://go-review.googlesource.com/c/go/+/226801
Reviewed-by: Jeremy Faller <jeremy@golang.org>
Reviewed-by: Than McIntosh <thanm@google.com>
This commit is contained in:
Cherry Zhang 2020-04-01 11:09:49 -04:00
parent 9f42c899e2
commit 2602b34659
11 changed files with 0 additions and 2862 deletions

View File

@ -1,201 +0,0 @@
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
cmddwarf "cmd/internal/dwarf"
"cmd/internal/objfile"
"debug/dwarf"
"internal/testenv"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"testing"
)
func testDWARF(t *testing.T, buildmode string, expectDWARF bool, env ...string) {
testenv.MustHaveCGO(t)
testenv.MustHaveGoBuild(t)
if runtime.GOOS == "plan9" {
t.Skip("skipping on plan9; no DWARF symbol table in executables")
}
out, err := exec.Command(testenv.GoToolPath(t), "list", "-f", "{{.Stale}}", "cmd/link").CombinedOutput()
if err != nil {
t.Fatalf("go list: %v\n%s", err, out)
}
if string(out) != "false\n" {
if os.Getenv("GOROOT_FINAL_OLD") != "" {
t.Skip("cmd/link is stale, but $GOROOT_FINAL_OLD is set")
}
t.Fatalf("cmd/link is stale - run go install cmd/link")
}
for _, prog := range []string{"testprog", "testprogcgo"} {
prog := prog
expectDWARF := expectDWARF
if runtime.GOOS == "aix" && prog == "testprogcgo" {
extld := os.Getenv("CC")
if extld == "" {
extld = "gcc"
}
expectDWARF, err = cmddwarf.IsDWARFEnabledOnAIXLd(extld)
if err != nil {
t.Fatal(err)
}
}
t.Run(prog, func(t *testing.T) {
t.Parallel()
tmpDir, err := ioutil.TempDir("", "go-link-TestDWARF")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
exe := filepath.Join(tmpDir, prog+".exe")
dir := "../../runtime/testdata/" + prog
cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", exe)
if buildmode != "" {
cmd.Args = append(cmd.Args, "-buildmode", buildmode)
}
cmd.Args = append(cmd.Args, dir)
if env != nil {
env = append(env, "CGO_CFLAGS=") // ensure CGO_CFLAGS does not contain any flags. Issue #35459
cmd.Env = append(os.Environ(), env...)
}
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("go build -o %v %v: %v\n%s", exe, dir, err, out)
}
if buildmode == "c-archive" {
// Extract the archive and use the go.o object within.
cmd := exec.Command("ar", "-x", exe)
cmd.Dir = tmpDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("ar -x %s: %v\n%s", exe, err, out)
}
exe = filepath.Join(tmpDir, "go.o")
}
if runtime.GOOS == "darwin" {
if _, err = exec.LookPath("symbols"); err == nil {
// Ensure Apple's tooling can parse our object for symbols.
out, err = exec.Command("symbols", exe).CombinedOutput()
if err != nil {
t.Fatalf("symbols %v: %v: %s", filepath.Base(exe), err, out)
} else {
if bytes.HasPrefix(out, []byte("Unable to find file")) {
// This failure will cause the App Store to reject our binaries.
t.Fatalf("symbols %v: failed to parse file", filepath.Base(exe))
} else if bytes.Contains(out, []byte(", Empty]")) {
t.Fatalf("symbols %v: parsed as empty", filepath.Base(exe))
}
}
}
}
f, err := objfile.Open(exe)
if err != nil {
t.Fatal(err)
}
defer f.Close()
syms, err := f.Symbols()
if err != nil {
t.Fatal(err)
}
var addr uint64
for _, sym := range syms {
if sym.Name == "main.main" {
addr = sym.Addr
break
}
}
if addr == 0 {
t.Fatal("cannot find main.main in symbols")
}
d, err := f.DWARF()
if err != nil {
if expectDWARF {
t.Fatal(err)
}
return
} else {
if !expectDWARF {
t.Fatal("unexpected DWARF section")
}
}
// TODO: We'd like to use filepath.Join here.
// Also related: golang.org/issue/19784.
wantFile := path.Join(prog, "main.go")
wantLine := 24
r := d.Reader()
entry, err := r.SeekPC(addr)
if err != nil {
t.Fatal(err)
}
lr, err := d.LineReader(entry)
if err != nil {
t.Fatal(err)
}
var line dwarf.LineEntry
if err := lr.SeekPC(addr, &line); err == dwarf.ErrUnknownPC {
t.Fatalf("did not find file:line for %#x (main.main)", addr)
} else if err != nil {
t.Fatal(err)
}
if !strings.HasSuffix(line.File.Name, wantFile) || line.Line != wantLine {
t.Errorf("%#x is %s:%d, want %s:%d", addr, line.File.Name, line.Line, filepath.Join("...", wantFile), wantLine)
}
})
}
}
func TestDWARF(t *testing.T) {
testDWARF(t, "", true)
if !testing.Short() {
if runtime.GOOS == "windows" {
t.Skip("skipping Windows/c-archive; see Issue 35512 for more.")
}
t.Run("c-archive", func(t *testing.T) {
testDWARF(t, "c-archive", true)
})
}
}
func TestDWARFiOS(t *testing.T) {
// Normally we run TestDWARF on native platform. But on iOS we don't have
// go build, so we do this test with a cross build.
// Only run this on darwin/amd64, where we can cross build for iOS.
if testing.Short() {
t.Skip("skipping in short mode")
}
if runtime.GOARCH != "amd64" || runtime.GOOS != "darwin" {
t.Skip("skipping on non-darwin/amd64 platform")
}
if err := exec.Command("xcrun", "--help").Run(); err != nil {
t.Skipf("error running xcrun, required for iOS cross build: %v", err)
}
cc := "CC=" + runtime.GOROOT() + "/misc/ios/clangwrap.sh"
// iOS doesn't allow unmapped segments, so iOS executables don't have DWARF.
testDWARF(t, "", false, cc, "CGO_ENABLED=1", "GOOS=darwin", "GOARCH=arm", "GOARM=7")
testDWARF(t, "", false, cc, "CGO_ENABLED=1", "GOOS=darwin", "GOARCH=arm64")
// However, c-archive iOS objects have embedded DWARF.
testDWARF(t, "c-archive", true, cc, "CGO_ENABLED=1", "GOOS=darwin", "GOARCH=arm", "GOARM=7")
testDWARF(t, "c-archive", true, cc, "CGO_ENABLED=1", "GOOS=darwin", "GOARCH=arm64")
}

View File

@ -1,416 +0,0 @@
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build dragonfly freebsd linux netbsd openbsd
package main
import (
"cmd/internal/sys"
"debug/elf"
"fmt"
"internal/testenv"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"text/template"
)
func getCCAndCCFLAGS(t *testing.T, env []string) (string, []string) {
goTool := testenv.GoToolPath(t)
cmd := exec.Command(goTool, "env", "CC")
cmd.Env = env
ccb, err := cmd.Output()
if err != nil {
t.Fatal(err)
}
cc := strings.TrimSpace(string(ccb))
cmd = exec.Command(goTool, "env", "GOGCCFLAGS")
cmd.Env = env
cflagsb, err := cmd.Output()
if err != nil {
t.Fatal(err)
}
cflags := strings.Fields(string(cflagsb))
return cc, cflags
}
var asmSource = `
.section .text1,"ax"
s1:
.byte 0
.section .text2,"ax"
s2:
.byte 0
`
var goSource = `
package main
func main() {}
`
// The linker used to crash if an ELF input file had multiple text sections
// with the same name.
func TestSectionsWithSameName(t *testing.T) {
testenv.MustHaveGoBuild(t)
testenv.MustHaveCGO(t)
t.Parallel()
objcopy, err := exec.LookPath("objcopy")
if err != nil {
t.Skipf("can't find objcopy: %v", err)
}
dir, err := ioutil.TempDir("", "go-link-TestSectionsWithSameName")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
gopath := filepath.Join(dir, "GOPATH")
env := append(os.Environ(), "GOPATH="+gopath)
if err := ioutil.WriteFile(filepath.Join(dir, "go.mod"), []byte("module elf_test\n"), 0666); err != nil {
t.Fatal(err)
}
asmFile := filepath.Join(dir, "x.s")
if err := ioutil.WriteFile(asmFile, []byte(asmSource), 0444); err != nil {
t.Fatal(err)
}
goTool := testenv.GoToolPath(t)
cc, cflags := getCCAndCCFLAGS(t, env)
asmObj := filepath.Join(dir, "x.o")
t.Logf("%s %v -c -o %s %s", cc, cflags, asmObj, asmFile)
if out, err := exec.Command(cc, append(cflags, "-c", "-o", asmObj, asmFile)...).CombinedOutput(); err != nil {
t.Logf("%s", out)
t.Fatal(err)
}
asm2Obj := filepath.Join(dir, "x2.syso")
t.Logf("%s --rename-section .text2=.text1 %s %s", objcopy, asmObj, asm2Obj)
if out, err := exec.Command(objcopy, "--rename-section", ".text2=.text1", asmObj, asm2Obj).CombinedOutput(); err != nil {
t.Logf("%s", out)
t.Fatal(err)
}
for _, s := range []string{asmFile, asmObj} {
if err := os.Remove(s); err != nil {
t.Fatal(err)
}
}
goFile := filepath.Join(dir, "main.go")
if err := ioutil.WriteFile(goFile, []byte(goSource), 0444); err != nil {
t.Fatal(err)
}
cmd := exec.Command(goTool, "build")
cmd.Dir = dir
cmd.Env = env
t.Logf("%s build", goTool)
if out, err := cmd.CombinedOutput(); err != nil {
t.Logf("%s", out)
t.Fatal(err)
}
}
var cSources35779 = []string{`
static int blah() { return 42; }
int Cfunc1() { return blah(); }
`, `
static int blah() { return 42; }
int Cfunc2() { return blah(); }
`,
}
// TestMinusRSymsWithSameName tests a corner case in the new
// loader. Prior to the fix this failed with the error 'loadelf:
// $WORK/b001/_pkg_.a(ldr.syso): duplicate symbol reference: blah in
// both main(.text) and main(.text)'. See issue #35779.
func TestMinusRSymsWithSameName(t *testing.T) {
testenv.MustHaveGoBuild(t)
testenv.MustHaveCGO(t)
t.Parallel()
dir, err := ioutil.TempDir("", "go-link-TestMinusRSymsWithSameName")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
gopath := filepath.Join(dir, "GOPATH")
env := append(os.Environ(), "GOPATH="+gopath)
if err := ioutil.WriteFile(filepath.Join(dir, "go.mod"), []byte("module elf_test\n"), 0666); err != nil {
t.Fatal(err)
}
goTool := testenv.GoToolPath(t)
cc, cflags := getCCAndCCFLAGS(t, env)
objs := []string{}
csrcs := []string{}
for i, content := range cSources35779 {
csrcFile := filepath.Join(dir, fmt.Sprintf("x%d.c", i))
csrcs = append(csrcs, csrcFile)
if err := ioutil.WriteFile(csrcFile, []byte(content), 0444); err != nil {
t.Fatal(err)
}
obj := filepath.Join(dir, fmt.Sprintf("x%d.o", i))
objs = append(objs, obj)
t.Logf("%s %v -c -o %s %s", cc, cflags, obj, csrcFile)
if out, err := exec.Command(cc, append(cflags, "-c", "-o", obj, csrcFile)...).CombinedOutput(); err != nil {
t.Logf("%s", out)
t.Fatal(err)
}
}
sysoObj := filepath.Join(dir, "ldr.syso")
t.Logf("%s %v -nostdlib -r -o %s %v", cc, cflags, sysoObj, objs)
if out, err := exec.Command(cc, append(cflags, "-nostdlib", "-r", "-o", sysoObj, objs[0], objs[1])...).CombinedOutput(); err != nil {
t.Logf("%s", out)
t.Fatal(err)
}
cruft := [][]string{objs, csrcs}
for _, sl := range cruft {
for _, s := range sl {
if err := os.Remove(s); err != nil {
t.Fatal(err)
}
}
}
goFile := filepath.Join(dir, "main.go")
if err := ioutil.WriteFile(goFile, []byte(goSource), 0444); err != nil {
t.Fatal(err)
}
t.Logf("%s build", goTool)
cmd := exec.Command(goTool, "build")
cmd.Dir = dir
cmd.Env = env
if out, err := cmd.CombinedOutput(); err != nil {
t.Logf("%s", out)
t.Fatal(err)
}
}
const pieSourceTemplate = `
package main
import "fmt"
// Force the creation of a lot of type descriptors that will go into
// the .data.rel.ro section.
{{range $index, $element := .}}var V{{$index}} interface{} = [{{$index}}]int{}
{{end}}
func main() {
{{range $index, $element := .}} fmt.Println(V{{$index}})
{{end}}
}
`
func TestPIESize(t *testing.T) {
testenv.MustHaveGoBuild(t)
if !sys.BuildModeSupported(runtime.Compiler, "pie", runtime.GOOS, runtime.GOARCH) {
t.Skip("-buildmode=pie not supported")
}
tmpl := template.Must(template.New("pie").Parse(pieSourceTemplate))
writeGo := func(t *testing.T, dir string) {
f, err := os.Create(filepath.Join(dir, "pie.go"))
if err != nil {
t.Fatal(err)
}
// Passing a 100-element slice here will cause
// pieSourceTemplate to create 100 variables with
// different types.
if err := tmpl.Execute(f, make([]byte, 100)); err != nil {
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
}
for _, external := range []bool{false, true} {
external := external
name := "TestPieSize-"
if external {
name += "external"
} else {
name += "internal"
}
t.Run(name, func(t *testing.T) {
t.Parallel()
dir, err := ioutil.TempDir("", "go-link-"+name)
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
writeGo(t, dir)
binexe := filepath.Join(dir, "exe")
binpie := filepath.Join(dir, "pie")
if external {
binexe += "external"
binpie += "external"
}
build := func(bin, mode string) error {
cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", bin, "-buildmode="+mode)
if external {
cmd.Args = append(cmd.Args, "-ldflags=-linkmode=external")
}
cmd.Args = append(cmd.Args, "pie.go")
cmd.Dir = dir
t.Logf("%v", cmd.Args)
out, err := cmd.CombinedOutput()
if len(out) > 0 {
t.Logf("%s", out)
}
if err != nil {
t.Error(err)
}
return err
}
var errexe, errpie error
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
errexe = build(binexe, "exe")
}()
go func() {
defer wg.Done()
errpie = build(binpie, "pie")
}()
wg.Wait()
if errexe != nil || errpie != nil {
t.Fatal("link failed")
}
var sizeexe, sizepie uint64
if fi, err := os.Stat(binexe); err != nil {
t.Fatal(err)
} else {
sizeexe = uint64(fi.Size())
}
if fi, err := os.Stat(binpie); err != nil {
t.Fatal(err)
} else {
sizepie = uint64(fi.Size())
}
elfexe, err := elf.Open(binexe)
if err != nil {
t.Fatal(err)
}
defer elfexe.Close()
elfpie, err := elf.Open(binpie)
if err != nil {
t.Fatal(err)
}
defer elfpie.Close()
// The difference in size between exe and PIE
// should be approximately the difference in
// size of the .text section plus the size of
// the PIE dynamic data sections plus the
// difference in size of the .got and .plt
// sections if they exist.
// We ignore unallocated sections.
// There may be gaps between non-writeable and
// writable PT_LOAD segments. We also skip those
// gaps (see issue #36023).
textsize := func(ef *elf.File, name string) uint64 {
for _, s := range ef.Sections {
if s.Name == ".text" {
return s.Size
}
}
t.Fatalf("%s: no .text section", name)
return 0
}
textexe := textsize(elfexe, binexe)
textpie := textsize(elfpie, binpie)
dynsize := func(ef *elf.File) uint64 {
var ret uint64
for _, s := range ef.Sections {
if s.Flags&elf.SHF_ALLOC == 0 {
continue
}
switch s.Type {
case elf.SHT_DYNSYM, elf.SHT_STRTAB, elf.SHT_REL, elf.SHT_RELA, elf.SHT_HASH, elf.SHT_GNU_HASH, elf.SHT_GNU_VERDEF, elf.SHT_GNU_VERNEED, elf.SHT_GNU_VERSYM:
ret += s.Size
}
if s.Flags&elf.SHF_WRITE != 0 && (strings.Contains(s.Name, ".got") || strings.Contains(s.Name, ".plt")) {
ret += s.Size
}
}
return ret
}
dynexe := dynsize(elfexe)
dynpie := dynsize(elfpie)
extrasize := func(ef *elf.File) uint64 {
var ret uint64
// skip unallocated sections
for _, s := range ef.Sections {
if s.Flags&elf.SHF_ALLOC == 0 {
ret += s.Size
}
}
// also skip gaps between PT_LOAD segments
var prev *elf.Prog
for _, seg := range ef.Progs {
if seg.Type != elf.PT_LOAD {
continue
}
if prev != nil {
ret += seg.Off - prev.Off - prev.Filesz
}
prev = seg
}
return ret
}
extraexe := extrasize(elfexe)
extrapie := extrasize(elfpie)
diffReal := (sizepie - extrapie) - (sizeexe - extraexe)
diffExpected := (textpie + dynpie) - (textexe + dynexe)
t.Logf("real size difference %#x, expected %#x", diffReal, diffExpected)
if diffReal > (diffExpected + diffExpected/10) {
t.Errorf("PIE unexpectedly large: got difference of %d (%d - %d), expected difference %d", diffReal, sizepie, sizeexe, diffExpected)
}
})
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,79 +0,0 @@
// +build cgo
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ld
import (
"debug/elf"
"internal/testenv"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestDynSymShInfo(t *testing.T) {
t.Parallel()
testenv.MustHaveGoBuild(t)
dir, err := ioutil.TempDir("", "go-build-issue33358")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
const prog = `
package main
import "net"
func main() {
net.Dial("", "")
}
`
src := filepath.Join(dir, "issue33358.go")
if err := ioutil.WriteFile(src, []byte(prog), 0666); err != nil {
t.Fatal(err)
}
binFile := filepath.Join(dir, "issue33358")
cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", binFile, src)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
}
fi, err := os.Open(binFile)
if err != nil {
t.Fatalf("failed to open built file: %v", err)
}
elfFile, err := elf.NewFile(fi)
if err != nil {
t.Skip("The system may not support ELF, skipped.")
}
section := elfFile.Section(".dynsym")
if section == nil {
t.Fatal("no dynsym")
}
symbols, err := elfFile.DynamicSymbols()
if err != nil {
t.Fatalf("failed to get dynamic symbols: %v", err)
}
var numLocalSymbols uint32
for i, s := range symbols {
if elf.ST_BIND(s.Info) != elf.STB_LOCAL {
numLocalSymbols = uint32(i + 1)
break
}
}
if section.Info != numLocalSymbols {
t.Fatalf("Unexpected sh info, want greater than 0, got: %d", section.Info)
}
}

View File

@ -1,54 +0,0 @@
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ld
import (
"internal/testenv"
"io/ioutil"
"os"
"runtime"
"strings"
"testing"
)
const prog = `
package main
import "log"
func main() {
log.Fatalf("HERE")
}
`
func TestIssue33808(t *testing.T) {
if runtime.GOOS != "darwin" {
return
}
testenv.MustHaveGoBuild(t)
testenv.MustHaveCGO(t)
dir, err := ioutil.TempDir("", "TestIssue33808")
if err != nil {
t.Fatalf("could not create directory: %v", err)
}
defer os.RemoveAll(dir)
f := gobuild(t, dir, prog, "-ldflags=-linkmode=external")
f.Close()
syms, err := f.Symbols()
if err != nil {
t.Fatalf("Error reading symbols: %v", err)
}
name := "log.Fatalf"
for _, sym := range syms {
if strings.Contains(sym.Name, name) {
return
}
}
t.Fatalf("Didn't find %v", name)
}

View File

@ -1,136 +0,0 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ld
import (
"fmt"
"internal/testenv"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestUndefinedRelocErrors(t *testing.T) {
t.Parallel()
testenv.MustHaveGoBuild(t)
dir, err := ioutil.TempDir("", "go-build")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
out, err := exec.Command(testenv.GoToolPath(t), "build", "./testdata/issue10978").CombinedOutput()
if err == nil {
t.Fatal("expected build to fail")
}
wantErrors := map[string]int{
// Main function has dedicated error message.
"function main is undeclared in the main package": 1,
// Single error reporting per each symbol.
// This way, duplicated messages are not reported for
// multiple relocations with a same name.
"main.defined1: relocation target main.undefined not defined": 1,
"main.defined2: relocation target main.undefined not defined": 1,
}
unexpectedErrors := map[string]int{}
for _, l := range strings.Split(string(out), "\n") {
if strings.HasPrefix(l, "#") || l == "" {
continue
}
matched := ""
for want := range wantErrors {
if strings.Contains(l, want) {
matched = want
break
}
}
if matched != "" {
wantErrors[matched]--
} else {
unexpectedErrors[l]++
}
}
for want, n := range wantErrors {
switch {
case n > 0:
t.Errorf("unmatched error: %s (x%d)", want, n)
case n < 0:
t.Errorf("extra errors: %s (x%d)", want, -n)
}
}
for unexpected, n := range unexpectedErrors {
t.Errorf("unexpected error: %s (x%d)", unexpected, n)
}
}
const carchiveSrcText = `
package main
//export GoFunc
func GoFunc() {
println(42)
}
func main() {
}
`
func TestArchiveBuildInvokeWithExec(t *testing.T) {
t.Parallel()
testenv.MustHaveGoBuild(t)
testenv.MustHaveCGO(t)
// run this test on just a small set of platforms (no need to test it
// across the board given the nature of the test).
pair := runtime.GOOS + "-" + runtime.GOARCH
switch pair {
case "darwin-amd64", "darwin-arm64", "linux-amd64", "freebsd-amd64":
default:
t.Skip("no need for test on " + pair)
}
switch runtime.GOOS {
case "openbsd", "windows":
t.Skip("c-archive unsupported")
}
dir, err := ioutil.TempDir("", "go-build")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
srcfile := filepath.Join(dir, "test.go")
arfile := filepath.Join(dir, "test.a")
if err := ioutil.WriteFile(srcfile, []byte(carchiveSrcText), 0666); err != nil {
t.Fatal(err)
}
ldf := fmt.Sprintf("-ldflags=-v -tmpdir=%s", dir)
argv := []string{"build", "-buildmode=c-archive", "-o", arfile, ldf, srcfile}
out, err := exec.Command(testenv.GoToolPath(t), argv...).CombinedOutput()
if err != nil {
t.Fatalf("build failure: %s\n%s\n", err, string(out))
}
found := false
const want = "invoking archiver with syscall.Exec"
for _, l := range strings.Split(string(out), "\n") {
if strings.HasPrefix(l, want) {
found = true
break
}
}
if !found {
t.Errorf("expected '%s' in -v output, got:\n%s\n", want, string(out))
}
}

View File

@ -1,37 +0,0 @@
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ld
import (
"internal/testenv"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
)
func TestNooptCgoBuild(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
t.Parallel()
testenv.MustHaveGoBuild(t)
testenv.MustHaveCGO(t)
dir, err := ioutil.TempDir("", "go-build")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
cmd := exec.Command(testenv.GoToolPath(t), "build", "-gcflags=-N -l", "-o", filepath.Join(dir, "a.out"))
cmd.Dir = filepath.Join(runtime.GOROOT(), "src", "runtime", "testdata", "testprogcgo")
out, err := cmd.CombinedOutput()
if err != nil {
t.Logf("go build output: %s", out)
t.Fatal(err)
}
}

View File

@ -1,449 +0,0 @@
package main
import (
"bufio"
"bytes"
"debug/macho"
"internal/testenv"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"testing"
)
var AuthorPaidByTheColumnInch struct {
fog int `text:"London. Michaelmas term lately over, and the Lord Chancellor sitting in Lincolns Inn Hall. Implacable November weather. As much mud in the streets as if the waters had but newly retired from the face of the earth, and it would not be wonderful to meet a Megalosaurus, forty feet long or so, waddling like an elephantine lizard up Holborn Hill. Smoke lowering down from chimney-pots, making a soft black drizzle, with flakes of soot in it as big as full-grown snowflakes—gone into mourning, one might imagine, for the death of the sun. Dogs, undistinguishable in mire. Horses, scarcely better; splashed to their very blinkers. Foot passengers, jostling one anothers umbrellas in a general infection of ill temper, and losing their foot-hold at street-corners, where tens of thousands of other foot passengers have been slipping and sliding since the day broke (if this day ever broke), adding new deposits to the crust upon crust of mud, sticking at those points tenaciously to the pavement, and accumulating at compound interest. Fog everywhere. Fog up the river, where it flows among green aits and meadows; fog down the river, where it rolls defiled among the tiers of shipping and the waterside pollutions of a great (and dirty) city. Fog on the Essex marshes, fog on the Kentish heights. Fog creeping into the cabooses of collier-brigs; fog lying out on the yards and hovering in the rigging of great ships; fog drooping on the gunwales of barges and small boats. Fog in the eyes and throats of ancient Greenwich pensioners, wheezing by the firesides of their wards; fog in the stem and bowl of the afternoon pipe of the wrathful skipper, down in his close cabin; fog cruelly pinching the toes and fingers of his shivering little prentice boy on deck. Chance people on the bridges peeping over the parapets into a nether sky of fog, with fog all round them, as if they were up in a balloon and hanging in the misty clouds. Gas looming through the fog in divers places in the streets, much as the sun may, from the spongey fields, be seen to loom by husbandman and ploughboy. Most of the shops lighted two hours before their time—as the gas seems to know, for it has a haggard and unwilling look. The raw afternoon is rawest, and the dense fog is densest, and the muddy streets are muddiest near that leaden-headed old obstruction, appropriate ornament for the threshold of a leaden-headed old corporation, Temple Bar. And hard by Temple Bar, in Lincolns Inn Hall, at the very heart of the fog, sits the Lord High Chancellor in his High Court of Chancery."`
wind int `text:"It was grand to see how the wind awoke, and bent the trees, and drove the rain before it like a cloud of smoke; and to hear the solemn thunder, and to see the lightning; and while thinking with awe of the tremendous powers by which our little lives are encompassed, to consider how beneficent they are, and how upon the smallest flower and leaf there was already a freshness poured from all this seeming rage, which seemed to make creation new again."`
jarndyce int `text:"Jarndyce and Jarndyce drones on. This scarecrow of a suit has, over the course of time, become so complicated, that no man alive knows what it means. The parties to it understand it least; but it has been observed that no two Chancery lawyers can talk about it for five minutes, without coming to a total disagreement as to all the premises. Innumerable children have been born into the cause; innumerable young people have married into it; innumerable old people have died out of it. Scores of persons have deliriously found themselves made parties in Jarndyce and Jarndyce, without knowing how or why; whole families have inherited legendary hatreds with the suit. The little plaintiff or defendant, who was promised a new rocking-horse when Jarndyce and Jarndyce should be settled, has grown up, possessed himself of a real horse, and trotted away into the other world. Fair wards of court have faded into mothers and grandmothers; a long procession of Chancellors has come in and gone out; the legion of bills in the suit have been transformed into mere bills of mortality; there are not three Jarndyces left upon the earth perhaps, since old Tom Jarndyce in despair blew his brains out at a coffee-house in Chancery Lane; but Jarndyce and Jarndyce still drags its dreary length before the Court, perennially hopeless."`
principle int `text:"The one great principle of the English law is, to make business for itself. There is no other principle distinctly, certainly, and consistently maintained through all its narrow turnings. Viewed by this light it becomes a coherent scheme, and not the monstrous maze the laity are apt to think it. Let them but once clearly perceive that its grand principle is to make business for itself at their expense, and surely they will cease to grumble."`
}
func TestLargeSymName(t *testing.T) {
// The compiler generates a symbol name using the string form of the
// type. This tests that the linker can read symbol names larger than
// the bufio buffer. Issue #15104.
_ = AuthorPaidByTheColumnInch
}
func TestIssue21703(t *testing.T) {
t.Parallel()
testenv.MustHaveGoBuild(t)
const source = `
package main
const X = "\n!\n"
func main() {}
`
tmpdir, err := ioutil.TempDir("", "issue21703")
if err != nil {
t.Fatalf("failed to create temp dir: %v\n", err)
}
defer os.RemoveAll(tmpdir)
err = ioutil.WriteFile(filepath.Join(tmpdir, "main.go"), []byte(source), 0666)
if err != nil {
t.Fatalf("failed to write main.go: %v\n", err)
}
cmd := exec.Command(testenv.GoToolPath(t), "tool", "compile", "main.go")
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("failed to compile main.go: %v, output: %s\n", err, out)
}
cmd = exec.Command(testenv.GoToolPath(t), "tool", "link", "main.o")
cmd.Dir = tmpdir
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("failed to link main.o: %v, output: %s\n", err, out)
}
}
// TestIssue28429 ensures that the linker does not attempt to link
// sections not named *.o. Such sections may be used by a build system
// to, for example, save facts produced by a modular static analysis
// such as golang.org/x/tools/go/analysis.
func TestIssue28429(t *testing.T) {
t.Parallel()
testenv.MustHaveGoBuild(t)
tmpdir, err := ioutil.TempDir("", "issue28429-")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpdir)
write := func(name, content string) {
err := ioutil.WriteFile(filepath.Join(tmpdir, name), []byte(content), 0666)
if err != nil {
t.Fatal(err)
}
}
runGo := func(args ...string) {
cmd := exec.Command(testenv.GoToolPath(t), args...)
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("'go %s' failed: %v, output: %s",
strings.Join(args, " "), err, out)
}
}
// Compile a main package.
write("main.go", "package main; func main() {}")
runGo("tool", "compile", "-p", "main", "main.go")
runGo("tool", "pack", "c", "main.a", "main.o")
// Add an extra section with a short, non-.o name.
// This simulates an alternative build system.
write(".facts", "this is not an object file")
runGo("tool", "pack", "r", "main.a", ".facts")
// Verify that the linker does not attempt
// to compile the extra section.
runGo("tool", "link", "main.a")
}
func TestUnresolved(t *testing.T) {
testenv.MustHaveGoBuild(t)
tmpdir, err := ioutil.TempDir("", "unresolved-")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpdir)
write := func(name, content string) {
err := ioutil.WriteFile(filepath.Join(tmpdir, name), []byte(content), 0666)
if err != nil {
t.Fatal(err)
}
}
// Test various undefined references. Because of issue #29852,
// this used to give confusing error messages because the
// linker would find an undefined reference to "zero" created
// by the runtime package.
write("go.mod", "module testunresolved\n")
write("main.go", `package main
func main() {
x()
}
func x()
`)
write("main.s", `
TEXT ·x(SB),0,$0
MOVD zero<>(SB), AX
MOVD zero(SB), AX
MOVD ·zero(SB), AX
RET
`)
cmd := exec.Command(testenv.GoToolPath(t), "build")
cmd.Dir = tmpdir
cmd.Env = append(os.Environ(),
"GOARCH=amd64", "GOOS=linux", "GOPATH="+filepath.Join(tmpdir, "_gopath"))
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected build to fail, but it succeeded")
}
out = regexp.MustCompile("(?m)^#.*\n").ReplaceAll(out, nil)
got := string(out)
want := `main.x: relocation target zero not defined
main.x: relocation target zero not defined
main.x: relocation target main.zero not defined
`
if want != got {
t.Fatalf("want:\n%sgot:\n%s", want, got)
}
}
func TestBuildForTvOS(t *testing.T) {
testenv.MustHaveCGO(t)
testenv.MustHaveGoBuild(t)
// Only run this on darwin/amd64, where we can cross build for tvOS.
if runtime.GOARCH != "amd64" || runtime.GOOS != "darwin" {
t.Skip("skipping on non-darwin/amd64 platform")
}
if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
t.Skip("skipping in -short mode with $GO_BUILDER_NAME empty")
}
if err := exec.Command("xcrun", "--help").Run(); err != nil {
t.Skipf("error running xcrun, required for iOS cross build: %v", err)
}
sdkPath, err := exec.Command("xcrun", "--sdk", "appletvos", "--show-sdk-path").Output()
if err != nil {
t.Skip("failed to locate appletvos SDK, skipping")
}
CC := []string{
"clang",
"-arch",
"arm64",
"-isysroot", strings.TrimSpace(string(sdkPath)),
"-mtvos-version-min=12.0",
"-fembed-bitcode",
"-framework", "CoreFoundation",
}
lib := filepath.Join("testdata", "lib.go")
tmpDir, err := ioutil.TempDir("", "go-link-TestBuildFortvOS")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
ar := filepath.Join(tmpDir, "lib.a")
cmd := exec.Command(testenv.GoToolPath(t), "build", "-buildmode=c-archive", "-o", ar, lib)
cmd.Env = append(os.Environ(),
"CGO_ENABLED=1",
"GOOS=darwin",
"GOARCH=arm64",
"CC="+strings.Join(CC, " "),
"CGO_CFLAGS=", // ensure CGO_CFLAGS does not contain any flags. Issue #35459
)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
}
link := exec.Command(CC[0], CC[1:]...)
link.Args = append(link.Args, ar, filepath.Join("testdata", "main.m"))
if out, err := link.CombinedOutput(); err != nil {
t.Fatalf("%v: %v:\n%s", link.Args, err, out)
}
}
var testXFlagSrc = `
package main
var X = "hello"
var Z = [99999]int{99998:12345} // make it large enough to be mmaped
func main() { println(X) }
`
func TestXFlag(t *testing.T) {
testenv.MustHaveGoBuild(t)
tmpdir, err := ioutil.TempDir("", "TestXFlag")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
src := filepath.Join(tmpdir, "main.go")
err = ioutil.WriteFile(src, []byte(testXFlagSrc), 0666)
if err != nil {
t.Fatal(err)
}
cmd := exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-X=main.X=meow", "-o", filepath.Join(tmpdir, "main"), src)
if out, err := cmd.CombinedOutput(); err != nil {
t.Errorf("%v: %v:\n%s", cmd.Args, err, out)
}
}
var testMacOSVersionSrc = `
package main
func main() { }
`
func TestMacOSVersion(t *testing.T) {
testenv.MustHaveGoBuild(t)
tmpdir, err := ioutil.TempDir("", "TestMacOSVersion")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
src := filepath.Join(tmpdir, "main.go")
err = ioutil.WriteFile(src, []byte(testMacOSVersionSrc), 0666)
if err != nil {
t.Fatal(err)
}
exe := filepath.Join(tmpdir, "main")
cmd := exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-linkmode=internal", "-o", exe, src)
cmd.Env = append(os.Environ(),
"CGO_ENABLED=0",
"GOOS=darwin",
"GOARCH=amd64",
)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
}
exef, err := os.Open(exe)
if err != nil {
t.Fatal(err)
}
exem, err := macho.NewFile(exef)
if err != nil {
t.Fatal(err)
}
found := false
const LC_VERSION_MIN_MACOSX = 0x24
checkMin := func(ver uint32) {
major, minor := (ver>>16)&0xff, (ver>>8)&0xff
if major != 10 || minor < 9 {
t.Errorf("LC_VERSION_MIN_MACOSX version %d.%d < 10.9", major, minor)
}
}
for _, cmd := range exem.Loads {
raw := cmd.Raw()
type_ := exem.ByteOrder.Uint32(raw)
if type_ != LC_VERSION_MIN_MACOSX {
continue
}
osVer := exem.ByteOrder.Uint32(raw[8:])
checkMin(osVer)
sdkVer := exem.ByteOrder.Uint32(raw[12:])
checkMin(sdkVer)
found = true
break
}
if !found {
t.Errorf("no LC_VERSION_MIN_MACOSX load command found")
}
}
const Issue34788src = `
package blah
func Blah(i int) int {
a := [...]int{1, 2, 3, 4, 5, 6, 7, 8}
return a[i&7]
}
`
func TestIssue34788Android386TLSSequence(t *testing.T) {
testenv.MustHaveGoBuild(t)
// This is a cross-compilation test, so it doesn't make
// sense to run it on every GOOS/GOARCH combination. Limit
// the test to amd64 + darwin/linux.
if runtime.GOARCH != "amd64" ||
(runtime.GOOS != "darwin" && runtime.GOOS != "linux") {
t.Skip("skipping on non-{linux,darwin}/amd64 platform")
}
tmpdir, err := ioutil.TempDir("", "TestIssue34788Android386TLSSequence")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
src := filepath.Join(tmpdir, "blah.go")
err = ioutil.WriteFile(src, []byte(Issue34788src), 0666)
if err != nil {
t.Fatal(err)
}
obj := filepath.Join(tmpdir, "blah.o")
cmd := exec.Command(testenv.GoToolPath(t), "tool", "compile", "-o", obj, src)
cmd.Env = append(os.Environ(), "GOARCH=386", "GOOS=android")
if out, err := cmd.CombinedOutput(); err != nil {
if err != nil {
t.Fatalf("failed to compile blah.go: %v, output: %s\n", err, out)
}
}
// Run objdump on the resulting object.
cmd = exec.Command(testenv.GoToolPath(t), "tool", "objdump", obj)
out, oerr := cmd.CombinedOutput()
if oerr != nil {
t.Fatalf("failed to objdump blah.o: %v, output: %s\n", oerr, out)
}
// Sift through the output; we should not be seeing any R_TLS_LE relocs.
scanner := bufio.NewScanner(bytes.NewReader(out))
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, "R_TLS_LE") {
t.Errorf("objdump output contains unexpected R_TLS_LE reloc: %s", line)
}
}
}
const testStrictDupGoSrc = `
package main
func f()
func main() { f() }
`
const testStrictDupAsmSrc1 = `
#include "textflag.h"
TEXT ·f(SB), NOSPLIT|DUPOK, $0-0
RET
`
const testStrictDupAsmSrc2 = `
#include "textflag.h"
TEXT ·f(SB), NOSPLIT|DUPOK, $0-0
JMP 0(PC)
`
func TestStrictDup(t *testing.T) {
// Check that -strictdups flag works.
testenv.MustHaveGoBuild(t)
tmpdir, err := ioutil.TempDir("", "TestStrictDup")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
src := filepath.Join(tmpdir, "x.go")
err = ioutil.WriteFile(src, []byte(testStrictDupGoSrc), 0666)
if err != nil {
t.Fatal(err)
}
src = filepath.Join(tmpdir, "a.s")
err = ioutil.WriteFile(src, []byte(testStrictDupAsmSrc1), 0666)
if err != nil {
t.Fatal(err)
}
src = filepath.Join(tmpdir, "b.s")
err = ioutil.WriteFile(src, []byte(testStrictDupAsmSrc2), 0666)
if err != nil {
t.Fatal(err)
}
src = filepath.Join(tmpdir, "go.mod")
err = ioutil.WriteFile(src, []byte("module teststrictdup\n"), 0666)
if err != nil {
t.Fatal(err)
}
cmd := exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-strictdups=1")
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Errorf("linking with -strictdups=1 failed: %v", err)
}
if !bytes.Contains(out, []byte("mismatched payload")) {
t.Errorf("unexpected output:\n%s", out)
}
cmd = exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-strictdups=2")
cmd.Dir = tmpdir
out, err = cmd.CombinedOutput()
if err == nil {
t.Errorf("linking with -strictdups=2 did not fail")
}
if !bytes.Contains(out, []byte("mismatched payload")) {
t.Errorf("unexpected output:\n%s", out)
}
}

View File

@ -1,112 +0,0 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This program generates a test to verify that a program can be
// successfully linked even when there are very large text
// sections present.
package main
import (
"bytes"
"cmd/internal/objabi"
"fmt"
"internal/testenv"
"io/ioutil"
"os"
"os/exec"
"testing"
)
func TestLargeText(t *testing.T) {
if testing.Short() || (objabi.GOARCH != "ppc64le" && objabi.GOARCH != "ppc64" && objabi.GOARCH != "arm") {
t.Skipf("Skipping large text section test in short mode or on %s", objabi.GOARCH)
}
testenv.MustHaveGoBuild(t)
var w bytes.Buffer
const FN = 4
tmpdir, err := ioutil.TempDir("", "bigtext")
if err != nil {
t.Fatalf("can't create temp directory: %v\n", err)
}
defer os.RemoveAll(tmpdir)
// Generate the scenario where the total amount of text exceeds the
// limit for the jmp/call instruction, on RISC architectures like ppc64le,
// which is 2^26. When that happens the call requires special trampolines or
// long branches inserted by the linker where supported.
// Multiple .s files are generated instead of one.
instOnArch := map[string]string{
"ppc64": "\tMOVD\tR0,R3\n",
"ppc64le": "\tMOVD\tR0,R3\n",
"arm": "\tMOVW\tR0,R1\n",
}
inst := instOnArch[objabi.GOARCH]
for j := 0; j < FN; j++ {
testname := fmt.Sprintf("bigfn%d", j)
fmt.Fprintf(&w, "TEXT ·%s(SB),$0\n", testname)
for i := 0; i < 2200000; i++ {
fmt.Fprintf(&w, inst)
}
fmt.Fprintf(&w, "\tRET\n")
err := ioutil.WriteFile(tmpdir+"/"+testname+".s", w.Bytes(), 0666)
if err != nil {
t.Fatalf("can't write output: %v\n", err)
}
w.Reset()
}
fmt.Fprintf(&w, "package main\n")
fmt.Fprintf(&w, "\nimport (\n")
fmt.Fprintf(&w, "\t\"os\"\n")
fmt.Fprintf(&w, "\t\"fmt\"\n")
fmt.Fprintf(&w, ")\n\n")
for i := 0; i < FN; i++ {
fmt.Fprintf(&w, "func bigfn%d()\n", i)
}
fmt.Fprintf(&w, "\nfunc main() {\n")
// There are lots of dummy code generated in the .s files just to generate a lot
// of text. Link them in but guard their call so their code is not executed but
// the main part of the program can be run.
fmt.Fprintf(&w, "\tif os.Getenv(\"LINKTESTARG\") != \"\" {\n")
for i := 0; i < FN; i++ {
fmt.Fprintf(&w, "\t\tbigfn%d()\n", i)
}
fmt.Fprintf(&w, "\t}\n")
fmt.Fprintf(&w, "\tfmt.Printf(\"PASS\\n\")\n")
fmt.Fprintf(&w, "}")
err = ioutil.WriteFile(tmpdir+"/bigfn.go", w.Bytes(), 0666)
if err != nil {
t.Fatalf("can't write output: %v\n", err)
}
// Build and run with internal linking.
os.Chdir(tmpdir)
cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "bigtext")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Build failed for big text program with internal linking: %v, output: %s", err, out)
}
cmd = exec.Command(tmpdir + "/bigtext")
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("Program built with internal linking failed to run with err %v, output: %s", err, out)
}
// Build and run with external linking
os.Chdir(tmpdir)
cmd = exec.Command(testenv.GoToolPath(t), "build", "-o", "bigtext", "-ldflags", "'-linkmode=external'")
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("Build failed for big text program with external linking: %v, output: %s", err, out)
}
cmd = exec.Command(tmpdir + "/bigtext")
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("Program built with external linking failed to run with err %v, output: %s", err, out)
}
}

View File

@ -1,8 +0,0 @@
package main
import "C"
//export GoFunc
func GoFunc() {}
func main() {}

View File

@ -1,5 +0,0 @@
extern void GoFunc();
int main(int argc, char **argv) {
GoFunc();
}