1 // Copyright 2016 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.
23 var AuthorPaidByTheColumnInch struct {
24 fog int `text:"London. Michaelmas term lately over, and the Lord Chancellor sitting in Lincoln’s 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 another’s 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 Lincoln’s Inn Hall, at the very heart of the fog, sits the Lord High Chancellor in his High Court of Chancery."`
26 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."`
28 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."`
30 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."`
33 func TestLargeSymName(t *testing.T) {
34 // The compiler generates a symbol name using the string form of the
35 // type. This tests that the linker can read symbol names larger than
36 // the bufio buffer. Issue #15104.
37 _ = AuthorPaidByTheColumnInch
40 func TestIssue21703(t *testing.T) {
43 testenv.MustHaveGoBuild(t)
53 err := ioutil.WriteFile(filepath.Join(tmpdir, "main.go"), []byte(source), 0666)
55 t.Fatalf("failed to write main.go: %v\n", err)
58 cmd := exec.Command(testenv.GoToolPath(t), "tool", "compile", "main.go")
60 out, err := cmd.CombinedOutput()
62 t.Fatalf("failed to compile main.go: %v, output: %s\n", err, out)
65 cmd = exec.Command(testenv.GoToolPath(t), "tool", "link", "main.o")
67 out, err = cmd.CombinedOutput()
69 t.Fatalf("failed to link main.o: %v, output: %s\n", err, out)
73 // TestIssue28429 ensures that the linker does not attempt to link
74 // sections not named *.o. Such sections may be used by a build system
75 // to, for example, save facts produced by a modular static analysis
76 // such as golang.org/x/tools/go/analysis.
77 func TestIssue28429(t *testing.T) {
80 testenv.MustHaveGoBuild(t)
84 write := func(name, content string) {
85 err := ioutil.WriteFile(filepath.Join(tmpdir, name), []byte(content), 0666)
91 runGo := func(args ...string) {
92 cmd := exec.Command(testenv.GoToolPath(t), args...)
94 out, err := cmd.CombinedOutput()
96 t.Fatalf("'go %s' failed: %v, output: %s",
97 strings.Join(args, " "), err, out)
101 // Compile a main package.
102 write("main.go", "package main; func main() {}")
103 runGo("tool", "compile", "-p", "main", "main.go")
104 runGo("tool", "pack", "c", "main.a", "main.o")
106 // Add an extra section with a short, non-.o name.
107 // This simulates an alternative build system.
108 write(".facts", "this is not an object file")
109 runGo("tool", "pack", "r", "main.a", ".facts")
111 // Verify that the linker does not attempt
112 // to compile the extra section.
113 runGo("tool", "link", "main.a")
116 func TestUnresolved(t *testing.T) {
117 testenv.MustHaveGoBuild(t)
121 tmpdir := t.TempDir()
123 write := func(name, content string) {
124 err := ioutil.WriteFile(filepath.Join(tmpdir, name), []byte(content), 0666)
130 // Test various undefined references. Because of issue #29852,
131 // this used to give confusing error messages because the
132 // linker would find an undefined reference to "zero" created
133 // by the runtime package.
135 write("go.mod", "module testunresolved\n")
136 write("main.go", `package main
151 cmd := exec.Command(testenv.GoToolPath(t), "build")
153 cmd.Env = append(os.Environ(),
154 "GOARCH=amd64", "GOOS=linux", "GOPATH="+filepath.Join(tmpdir, "_gopath"))
155 out, err := cmd.CombinedOutput()
157 t.Fatalf("expected build to fail, but it succeeded")
159 out = regexp.MustCompile("(?m)^#.*\n").ReplaceAll(out, nil)
161 want := `main.x: relocation target zero not defined
162 main.x: relocation target zero not defined
163 main.x: relocation target main.zero not defined
166 t.Fatalf("want:\n%sgot:\n%s", want, got)
170 func TestIssue33979(t *testing.T) {
171 testenv.MustHaveGoBuild(t)
172 testenv.MustHaveCGO(t)
173 testenv.MustInternalLink(t)
175 // Skip test on platforms that do not support cgo internal linking.
176 switch runtime.GOARCH {
177 case "mips", "mipsle", "mips64", "mips64le":
178 t.Skipf("Skipping on %s/%s", runtime.GOOS, runtime.GOARCH)
180 if runtime.GOOS == "aix" ||
181 runtime.GOOS == "windows" && runtime.GOARCH == "arm64" {
182 t.Skipf("Skipping on %s/%s", runtime.GOOS, runtime.GOARCH)
187 tmpdir := t.TempDir()
189 write := func(name, content string) {
190 err := ioutil.WriteFile(filepath.Join(tmpdir, name), []byte(content), 0666)
196 run := func(name string, args ...string) string {
197 cmd := exec.Command(name, args...)
199 out, err := cmd.CombinedOutput()
201 t.Fatalf("'go %s' failed: %v, output: %s", strings.Join(args, " "), err, out)
205 runGo := func(args ...string) string {
206 return run(testenv.GoToolPath(t), args...)
209 // Test object with undefined reference that was not generated
210 // by Go, resulting in an SXREF symbol being loaded during linking.
211 // Because of issue #33979, the SXREF symbol would be found during
212 // error reporting, resulting in confusing error messages.
214 write("main.go", `package main
220 // The following assembly must work on all architectures.
234 cc := strings.TrimSpace(runGo("env", "CC"))
235 cflags := strings.Fields(runGo("env", "GOGCCFLAGS"))
237 // Compile, assemble and pack the Go and C code.
238 runGo("tool", "asm", "-gensymabis", "-o", "symabis", "x.s")
239 runGo("tool", "compile", "-symabis", "symabis", "-p", "main", "-o", "x1.o", "main.go")
240 runGo("tool", "asm", "-o", "x2.o", "x.s")
241 run(cc, append(cflags, "-c", "-o", "x3.o", "x.c")...)
242 runGo("tool", "pack", "c", "x.a", "x1.o", "x2.o", "x3.o")
244 // Now attempt to link using the internal linker.
245 cmd := exec.Command(testenv.GoToolPath(t), "tool", "link", "-linkmode=internal", "x.a")
247 out, err := cmd.CombinedOutput()
249 t.Fatalf("expected link to fail, but it succeeded")
251 re := regexp.MustCompile(`(?m)^main\(.*text\): relocation target undefined not defined$`)
253 t.Fatalf("got:\n%q\nwant:\n%s", out, re)
257 func TestBuildForTvOS(t *testing.T) {
258 testenv.MustHaveCGO(t)
259 testenv.MustHaveGoBuild(t)
261 // Only run this on darwin/amd64, where we can cross build for tvOS.
262 if runtime.GOARCH != "amd64" || runtime.GOOS != "darwin" {
263 t.Skip("skipping on non-darwin/amd64 platform")
265 if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
266 t.Skip("skipping in -short mode with $GO_BUILDER_NAME empty")
268 if err := exec.Command("xcrun", "--help").Run(); err != nil {
269 t.Skipf("error running xcrun, required for iOS cross build: %v", err)
274 sdkPath, err := exec.Command("xcrun", "--sdk", "appletvos", "--show-sdk-path").Output()
276 t.Skip("failed to locate appletvos SDK, skipping")
282 "-isysroot", strings.TrimSpace(string(sdkPath)),
283 "-mtvos-version-min=12.0",
285 "-framework", "CoreFoundation",
287 lib := filepath.Join("testdata", "testBuildFortvOS", "lib.go")
288 tmpDir := t.TempDir()
290 ar := filepath.Join(tmpDir, "lib.a")
291 cmd := exec.Command(testenv.GoToolPath(t), "build", "-buildmode=c-archive", "-o", ar, lib)
292 cmd.Env = append(os.Environ(),
296 "CC="+strings.Join(CC, " "),
297 "CGO_CFLAGS=", // ensure CGO_CFLAGS does not contain any flags. Issue #35459
299 if out, err := cmd.CombinedOutput(); err != nil {
300 t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
303 link := exec.Command(CC[0], CC[1:]...)
304 link.Args = append(link.Args, "-o", filepath.Join(tmpDir, "a.out")) // Avoid writing to package directory.
305 link.Args = append(link.Args, ar, filepath.Join("testdata", "testBuildFortvOS", "main.m"))
306 if out, err := link.CombinedOutput(); err != nil {
307 t.Fatalf("%v: %v:\n%s", link.Args, err, out)
314 var Z = [99999]int{99998:12345} // make it large enough to be mmaped
315 func main() { println(X) }
318 func TestXFlag(t *testing.T) {
319 testenv.MustHaveGoBuild(t)
323 tmpdir := t.TempDir()
325 src := filepath.Join(tmpdir, "main.go")
326 err := ioutil.WriteFile(src, []byte(testXFlagSrc), 0666)
331 cmd := exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-X=main.X=meow", "-o", filepath.Join(tmpdir, "main"), src)
332 if out, err := cmd.CombinedOutput(); err != nil {
333 t.Errorf("%v: %v:\n%s", cmd.Args, err, out)
337 var testMachOBuildVersionSrc = `
342 func TestMachOBuildVersion(t *testing.T) {
343 testenv.MustHaveGoBuild(t)
347 tmpdir := t.TempDir()
349 src := filepath.Join(tmpdir, "main.go")
350 err := ioutil.WriteFile(src, []byte(testMachOBuildVersionSrc), 0666)
355 exe := filepath.Join(tmpdir, "main")
356 cmd := exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-linkmode=internal", "-o", exe, src)
357 cmd.Env = append(os.Environ(),
362 if out, err := cmd.CombinedOutput(); err != nil {
363 t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
365 exef, err := os.Open(exe)
370 exem, err := macho.NewFile(exef)
375 const LC_BUILD_VERSION = 0x32
376 checkMin := func(ver uint32) {
377 major, minor := (ver>>16)&0xff, (ver>>8)&0xff
378 if major != 10 || minor < 9 {
379 t.Errorf("LC_BUILD_VERSION version %d.%d < 10.9", major, minor)
382 for _, cmd := range exem.Loads {
384 type_ := exem.ByteOrder.Uint32(raw)
385 if type_ != LC_BUILD_VERSION {
388 osVer := exem.ByteOrder.Uint32(raw[12:])
390 sdkVer := exem.ByteOrder.Uint32(raw[16:])
396 t.Errorf("no LC_BUILD_VERSION load command found")
400 const Issue34788src = `
404 func Blah(i int) int {
405 a := [...]int{1, 2, 3, 4, 5, 6, 7, 8}
410 func TestIssue34788Android386TLSSequence(t *testing.T) {
411 testenv.MustHaveGoBuild(t)
413 // This is a cross-compilation test, so it doesn't make
414 // sense to run it on every GOOS/GOARCH combination. Limit
415 // the test to amd64 + darwin/linux.
416 if runtime.GOARCH != "amd64" ||
417 (runtime.GOOS != "darwin" && runtime.GOOS != "linux") {
418 t.Skip("skipping on non-{linux,darwin}/amd64 platform")
423 tmpdir := t.TempDir()
425 src := filepath.Join(tmpdir, "blah.go")
426 err := ioutil.WriteFile(src, []byte(Issue34788src), 0666)
431 obj := filepath.Join(tmpdir, "blah.o")
432 cmd := exec.Command(testenv.GoToolPath(t), "tool", "compile", "-o", obj, src)
433 cmd.Env = append(os.Environ(), "GOARCH=386", "GOOS=android")
434 if out, err := cmd.CombinedOutput(); err != nil {
435 t.Fatalf("failed to compile blah.go: %v, output: %s\n", err, out)
438 // Run objdump on the resulting object.
439 cmd = exec.Command(testenv.GoToolPath(t), "tool", "objdump", obj)
440 out, oerr := cmd.CombinedOutput()
442 t.Fatalf("failed to objdump blah.o: %v, output: %s\n", oerr, out)
445 // Sift through the output; we should not be seeing any R_TLS_LE relocs.
446 scanner := bufio.NewScanner(bytes.NewReader(out))
448 line := scanner.Text()
449 if strings.Contains(line, "R_TLS_LE") {
450 t.Errorf("objdump output contains unexpected R_TLS_LE reloc: %s", line)
455 const testStrictDupGoSrc = `
461 const testStrictDupAsmSrc1 = `
462 #include "textflag.h"
463 TEXT ·f(SB), NOSPLIT|DUPOK, $0-0
467 const testStrictDupAsmSrc2 = `
468 #include "textflag.h"
469 TEXT ·f(SB), NOSPLIT|DUPOK, $0-0
473 const testStrictDupAsmSrc3 = `
474 #include "textflag.h"
475 GLOBL ·rcon(SB), RODATA|DUPOK, $64
478 const testStrictDupAsmSrc4 = `
479 #include "textflag.h"
480 GLOBL ·rcon(SB), RODATA|DUPOK, $32
483 func TestStrictDup(t *testing.T) {
484 // Check that -strictdups flag works.
485 testenv.MustHaveGoBuild(t)
487 asmfiles := []struct {
491 {"a", testStrictDupAsmSrc1},
492 {"b", testStrictDupAsmSrc2},
493 {"c", testStrictDupAsmSrc3},
494 {"d", testStrictDupAsmSrc4},
499 tmpdir := t.TempDir()
501 src := filepath.Join(tmpdir, "x.go")
502 err := ioutil.WriteFile(src, []byte(testStrictDupGoSrc), 0666)
506 for _, af := range asmfiles {
507 src = filepath.Join(tmpdir, af.fname+".s")
508 err = ioutil.WriteFile(src, []byte(af.payload), 0666)
513 src = filepath.Join(tmpdir, "go.mod")
514 err = ioutil.WriteFile(src, []byte("module teststrictdup\n"), 0666)
519 cmd := exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-strictdups=1")
521 out, err := cmd.CombinedOutput()
523 t.Errorf("linking with -strictdups=1 failed: %v\n%s", err, string(out))
525 if !bytes.Contains(out, []byte("mismatched payload")) {
526 t.Errorf("unexpected output:\n%s", out)
529 cmd = exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-strictdups=2")
531 out, err = cmd.CombinedOutput()
533 t.Errorf("linking with -strictdups=2 did not fail")
535 // NB: on amd64 we get the 'new length' error, on arm64 the 'different
537 if !(bytes.Contains(out, []byte("mismatched payload: new length")) ||
538 bytes.Contains(out, []byte("mismatched payload: same length but different contents"))) ||
539 !bytes.Contains(out, []byte("mismatched payload: different sizes")) {
540 t.Errorf("unexpected output:\n%s", out)
544 const testFuncAlignSrc = `
553 addr := reflect.ValueOf(alignPc).Pointer()
554 if (addr % 512) != 0 {
555 fmt.Printf("expected 512 bytes alignment, got %v\n", addr)
562 const testFuncAlignAsmSrc = `
563 #include "textflag.h"
565 TEXT ·alignPc(SB),NOSPLIT, $0-0
572 // TestFuncAlign verifies that the address of a function can be aligned
573 // with a specific value on arm64.
574 func TestFuncAlign(t *testing.T) {
575 if runtime.GOARCH != "arm64" || runtime.GOOS != "linux" {
576 t.Skip("skipping on non-linux/arm64 platform")
578 testenv.MustHaveGoBuild(t)
582 tmpdir := t.TempDir()
584 src := filepath.Join(tmpdir, "go.mod")
585 err := ioutil.WriteFile(src, []byte("module cmd/link/TestFuncAlign/falign"), 0666)
589 src = filepath.Join(tmpdir, "falign.go")
590 err = ioutil.WriteFile(src, []byte(testFuncAlignSrc), 0666)
594 src = filepath.Join(tmpdir, "falign.s")
595 err = ioutil.WriteFile(src, []byte(testFuncAlignAsmSrc), 0666)
600 // Build and run with old object file format.
601 cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "falign")
603 out, err := cmd.CombinedOutput()
605 t.Errorf("build failed: %v", err)
607 cmd = exec.Command(tmpdir + "/falign")
608 out, err = cmd.CombinedOutput()
610 t.Errorf("failed to run with err %v, output: %s", err, out)
612 if string(out) != "PASS" {
613 t.Errorf("unexpected output: %s\n", out)
617 const testTrampSrc = `
624 if e := recover(); e == nil {
625 panic("did not panic")
631 // Test deferreturn trampolines. See issue #39049.
632 func f1() { defer f2() }
633 func f2() { panic("XXX") }
636 func TestTrampoline(t *testing.T) {
637 // Test that trampoline insertion works as expected.
638 // For stress test, we set -debugtramp=2 flag, which sets a very low
639 // threshold for trampoline generation, and essentially all cross-package
640 // calls will use trampolines.
641 switch runtime.GOARCH {
642 case "arm", "arm64", "ppc64", "ppc64le":
644 t.Skipf("trampoline insertion is not implemented on %s", runtime.GOARCH)
647 testenv.MustHaveGoBuild(t)
651 tmpdir := t.TempDir()
653 src := filepath.Join(tmpdir, "hello.go")
654 err := ioutil.WriteFile(src, []byte(testTrampSrc), 0666)
658 exe := filepath.Join(tmpdir, "hello.exe")
660 cmd := exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-debugtramp=2", "-o", exe, src)
661 out, err := cmd.CombinedOutput()
663 t.Fatalf("build failed: %v\n%s", err, out)
665 cmd = exec.Command(exe)
666 out, err = cmd.CombinedOutput()
668 t.Errorf("executable failed to run: %v\n%s", err, out)
670 if string(out) != "hello\n" {
671 t.Errorf("unexpected output:\n%s", out)
675 const testTrampCgoSrc = `
678 // #include <stdio.h>
679 // void CHello() { printf("hello\n"); fflush(stdout); }
687 func TestTrampolineCgo(t *testing.T) {
688 // Test that trampoline insertion works for cgo code.
689 // For stress test, we set -debugtramp=2 flag, which sets a very low
690 // threshold for trampoline generation, and essentially all cross-package
691 // calls will use trampolines.
692 switch runtime.GOARCH {
693 case "arm", "arm64", "ppc64", "ppc64le":
695 t.Skipf("trampoline insertion is not implemented on %s", runtime.GOARCH)
698 testenv.MustHaveGoBuild(t)
699 testenv.MustHaveCGO(t)
703 tmpdir := t.TempDir()
705 src := filepath.Join(tmpdir, "hello.go")
706 err := ioutil.WriteFile(src, []byte(testTrampCgoSrc), 0666)
710 exe := filepath.Join(tmpdir, "hello.exe")
712 cmd := exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-debugtramp=2", "-o", exe, src)
713 out, err := cmd.CombinedOutput()
715 t.Fatalf("build failed: %v\n%s", err, out)
717 cmd = exec.Command(exe)
718 out, err = cmd.CombinedOutput()
720 t.Errorf("executable failed to run: %v\n%s", err, out)
722 if string(out) != "hello\n" && string(out) != "hello\r\n" {
723 t.Errorf("unexpected output:\n%s", out)
726 // Test internal linking mode.
728 if runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" || (runtime.GOARCH == "arm64" && runtime.GOOS == "windows") || !testenv.CanInternalLink() {
729 return // internal linking cgo is not supported
731 cmd = exec.Command(testenv.GoToolPath(t), "build", "-ldflags=-debugtramp=2 -linkmode=internal", "-o", exe, src)
732 out, err = cmd.CombinedOutput()
734 t.Fatalf("build failed: %v\n%s", err, out)
736 cmd = exec.Command(exe)
737 out, err = cmd.CombinedOutput()
739 t.Errorf("executable failed to run: %v\n%s", err, out)
741 if string(out) != "hello\n" && string(out) != "hello\r\n" {
742 t.Errorf("unexpected output:\n%s", out)
746 func TestIndexMismatch(t *testing.T) {
747 // Test that index mismatch will cause a link-time error (not run-time error).
748 // This shouldn't happen with "go build". We invoke the compiler and the linker
749 // manually, and try to "trick" the linker with an inconsistent object file.
750 testenv.MustHaveGoBuild(t)
754 tmpdir := t.TempDir()
756 aSrc := filepath.Join("testdata", "testIndexMismatch", "a.go")
757 bSrc := filepath.Join("testdata", "testIndexMismatch", "b.go")
758 mSrc := filepath.Join("testdata", "testIndexMismatch", "main.go")
759 aObj := filepath.Join(tmpdir, "a.o")
760 mObj := filepath.Join(tmpdir, "main.o")
761 exe := filepath.Join(tmpdir, "main.exe")
763 // Build a program with main package importing package a.
764 cmd := exec.Command(testenv.GoToolPath(t), "tool", "compile", "-o", aObj, aSrc)
766 out, err := cmd.CombinedOutput()
768 t.Fatalf("compiling a.go failed: %v\n%s", err, out)
770 cmd = exec.Command(testenv.GoToolPath(t), "tool", "compile", "-I", tmpdir, "-o", mObj, mSrc)
772 out, err = cmd.CombinedOutput()
774 t.Fatalf("compiling main.go failed: %v\n%s", err, out)
776 cmd = exec.Command(testenv.GoToolPath(t), "tool", "link", "-L", tmpdir, "-o", exe, mObj)
778 out, err = cmd.CombinedOutput()
780 t.Errorf("linking failed: %v\n%s", err, out)
783 // Now, overwrite a.o with the object of b.go. This should
784 // result in an index mismatch.
785 cmd = exec.Command(testenv.GoToolPath(t), "tool", "compile", "-o", aObj, bSrc)
787 out, err = cmd.CombinedOutput()
789 t.Fatalf("compiling a.go failed: %v\n%s", err, out)
791 cmd = exec.Command(testenv.GoToolPath(t), "tool", "link", "-L", tmpdir, "-o", exe, mObj)
793 out, err = cmd.CombinedOutput()
795 t.Fatalf("linking didn't fail")
797 if !bytes.Contains(out, []byte("fingerprint mismatch")) {
798 t.Errorf("did not see expected error message. out:\n%s", out)
802 func TestPErsrcBinutils(t *testing.T) {
803 // Test that PE rsrc section is handled correctly (issue 39658).
804 testenv.MustHaveGoBuild(t)
806 if (runtime.GOARCH != "386" && runtime.GOARCH != "amd64") || runtime.GOOS != "windows" {
807 // This test is limited to amd64 and 386, because binutils is limited as such
808 t.Skipf("this is only for windows/amd64 and windows/386")
813 tmpdir := t.TempDir()
815 pkgdir := filepath.Join("testdata", "pe-binutils")
816 exe := filepath.Join(tmpdir, "a.exe")
817 cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", exe)
819 // cmd.Env = append(os.Environ(), "GOOS=windows", "GOARCH=amd64") // uncomment if debugging in a cross-compiling environment
820 out, err := cmd.CombinedOutput()
822 t.Fatalf("building failed: %v, output:\n%s", err, out)
825 // Check that the binary contains the rsrc data
826 b, err := ioutil.ReadFile(exe)
828 t.Fatalf("reading output failed: %v", err)
830 if !bytes.Contains(b, []byte("Hello Gophers!")) {
831 t.Fatalf("binary does not contain expected content")
835 func TestPErsrcLLVM(t *testing.T) {
836 // Test that PE rsrc section is handled correctly (issue 39658).
837 testenv.MustHaveGoBuild(t)
839 if runtime.GOOS != "windows" {
840 t.Skipf("this is a windows-only test")
845 tmpdir := t.TempDir()
847 pkgdir := filepath.Join("testdata", "pe-llvm")
848 exe := filepath.Join(tmpdir, "a.exe")
849 cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", exe)
851 // cmd.Env = append(os.Environ(), "GOOS=windows", "GOARCH=amd64") // uncomment if debugging in a cross-compiling environment
852 out, err := cmd.CombinedOutput()
854 t.Fatalf("building failed: %v, output:\n%s", err, out)
857 // Check that the binary contains the rsrc data
858 b, err := ioutil.ReadFile(exe)
860 t.Fatalf("reading output failed: %v", err)
862 if !bytes.Contains(b, []byte("resname RCDATA a.rc")) {
863 t.Fatalf("binary does not contain expected content")
867 func TestContentAddressableSymbols(t *testing.T) {
868 // Test that the linker handles content-addressable symbols correctly.
869 testenv.MustHaveGoBuild(t)
873 src := filepath.Join("testdata", "testHashedSyms", "p.go")
874 cmd := exec.Command(testenv.GoToolPath(t), "run", src)
875 out, err := cmd.CombinedOutput()
877 t.Errorf("command %s failed: %v\n%s", cmd, err, out)
881 func TestReadOnly(t *testing.T) {
882 // Test that read-only data is indeed read-only.
883 testenv.MustHaveGoBuild(t)
887 src := filepath.Join("testdata", "testRO", "x.go")
888 cmd := exec.Command(testenv.GoToolPath(t), "run", src)
889 out, err := cmd.CombinedOutput()
891 t.Errorf("running test program did not fail. output:\n%s", out)
895 const testIssue38554Src = `
902 return T{} // compiler will make a large stmp symbol, but not used.
911 func TestIssue38554(t *testing.T) {
912 testenv.MustHaveGoBuild(t)
916 tmpdir := t.TempDir()
918 src := filepath.Join(tmpdir, "x.go")
919 err := ioutil.WriteFile(src, []byte(testIssue38554Src), 0666)
921 t.Fatalf("failed to write source file: %v", err)
923 exe := filepath.Join(tmpdir, "x.exe")
924 cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", exe, src)
925 out, err := cmd.CombinedOutput()
927 t.Fatalf("build failed: %v\n%s", err, out)
930 fi, err := os.Stat(exe)
932 t.Fatalf("failed to stat output file: %v", err)
935 // The test program is not much different from a helloworld, which is
936 // typically a little over 1 MB. We allow 5 MB. If the bad stmp is live,
937 // it will be over 10 MB.
939 if got := fi.Size(); got > want {
940 t.Errorf("binary too big: got %d, want < %d", got, want)
944 const testIssue42396src = `
957 func TestIssue42396(t *testing.T) {
958 testenv.MustHaveGoBuild(t)
960 if !sys.RaceDetectorSupported(runtime.GOOS, runtime.GOARCH) {
961 t.Skip("no race detector support")
966 tmpdir := t.TempDir()
968 src := filepath.Join(tmpdir, "main.go")
969 err := ioutil.WriteFile(src, []byte(testIssue42396src), 0666)
971 t.Fatalf("failed to write source file: %v", err)
973 exe := filepath.Join(tmpdir, "main.exe")
974 cmd := exec.Command(testenv.GoToolPath(t), "build", "-gcflags=-race", "-o", exe, src)
975 out, err := cmd.CombinedOutput()
977 t.Fatalf("build unexpectedly succeeded")
980 // Check to make sure that we see a reasonable error message
982 if strings.Contains(string(out), "panic:") {
983 t.Fatalf("build should not fail with panic:\n%s", out)
985 const want = "reference to undefined builtin"
986 if !strings.Contains(string(out), want) {
987 t.Fatalf("error message incorrect: expected it to contain %q but instead got:\n%s\n", want, out)
991 const testLargeRelocSrc = `
994 var x = [1<<25]byte{1<<23: 23, 1<<24: 24}
1000 check(x[1<<24-1], 0)
1002 check(x[1<<24+1], 0)
1005 func check(x, y byte) {
1012 func TestLargeReloc(t *testing.T) {
1013 // Test that large relocation addend is handled correctly.
1014 // In particular, on darwin/arm64 when external linking,
1015 // Mach-O relocation has only 24-bit addend. See issue #42738.
1016 testenv.MustHaveGoBuild(t)
1019 tmpdir := t.TempDir()
1021 src := filepath.Join(tmpdir, "x.go")
1022 err := ioutil.WriteFile(src, []byte(testLargeRelocSrc), 0666)
1024 t.Fatalf("failed to write source file: %v", err)
1026 cmd := exec.Command(testenv.GoToolPath(t), "run", src)
1027 out, err := cmd.CombinedOutput()
1029 t.Errorf("build failed: %v. output:\n%s", err, out)
1032 if testenv.HasCGO() { // currently all targets that support cgo can external link
1033 cmd = exec.Command(testenv.GoToolPath(t), "run", "-ldflags=-linkmode=external", src)
1034 out, err = cmd.CombinedOutput()
1036 t.Fatalf("build failed: %v. output:\n%s", err, out)