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.
31 // C compiler with args (from $(go env CC) $(go env GOGCCFLAGS)).
37 var GOOS, GOARCH, GOPATH string
40 var testWork bool // If true, preserve temporary directories.
42 func TestMain(m *testing.M) {
43 flag.BoolVar(&testWork, "testwork", false, "if true, log and preserve the test's temporary working directory")
45 if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
46 fmt.Printf("SKIP - short mode and $GO_BUILDER_NAME not set\n")
49 log.SetFlags(log.Lshortfile)
53 func testMain(m *testing.M) int {
54 // We need a writable GOPATH in which to run the tests.
55 // Construct one in a temporary directory.
57 GOPATH, err = os.MkdirTemp("", "carchive_test")
64 defer os.RemoveAll(GOPATH)
66 os.Setenv("GOPATH", GOPATH)
68 // Copy testdata into GOPATH/src/testarchive, along with a go.mod file
69 // declaring the same path.
70 modRoot := filepath.Join(GOPATH, "src", "testcarchive")
71 if err := overlayDir(modRoot, "testdata"); err != nil {
74 if err := os.Chdir(modRoot); err != nil {
77 os.Setenv("PWD", modRoot)
78 if err := os.WriteFile("go.mod", []byte("module testcarchive\n"), 0666); err != nil {
83 GOARCH = goEnv("GOARCH")
84 bin = cmdToRun("./testp")
87 cc = []string{string(ccOut)}
89 out := goEnv("GOGCCFLAGS")
96 if quote == '\000' && unicode.IsSpace(c) {
98 cc = append(cc, s[start:i])
106 if quote == '\000' && !backslash && (c == '"' || c == '\'') {
109 } else if !backslash && quote == c {
111 } else if (quote == '\000' || quote == '"') && !backslash && c == '\\' {
119 cc = append(cc, s[start:])
123 // -Wl,-bnoobjreorder is mandatory to keep the same layout
125 cc = append(cc, "-Wl,-bnoobjreorder")
127 libbase := GOOS + "_" + GOARCH
128 if runtime.Compiler == "gccgo" {
129 libbase = "gccgo_" + libgodir + "_fPIC"
132 case "darwin", "ios":
133 if GOARCH == "arm64" {
136 case "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "solaris", "illumos":
140 libgodir = filepath.Join(GOPATH, "pkg", libbase, "testcarchive")
141 cc = append(cc, "-I", libgodir)
143 // Force reallocation (and avoid aliasing bugs) for parallel tests that append to cc.
144 cc = cc[:len(cc):len(cc)]
146 if GOOS == "windows" {
153 func goEnv(key string) string {
154 out, err := exec.Command("go", "env", key).Output()
156 if ee, ok := err.(*exec.ExitError); ok {
157 fmt.Fprintf(os.Stderr, "%s", ee.Stderr)
159 log.Panicf("go env %s failed:\n%s\n", key, err)
161 return strings.TrimSpace(string(out))
164 func cmdToRun(name string) []string {
165 execScript := "go_" + goEnv("GOOS") + "_" + goEnv("GOARCH") + "_exec"
166 executor, err := exec.LookPath(execScript)
168 return []string{name}
170 return []string{executor, name}
173 // genHeader writes a C header file for the C-exported declarations found in .go
174 // source files in dir.
176 // TODO(golang.org/issue/35715): This should be simpler.
177 func genHeader(t *testing.T, header, dir string) {
180 // The 'cgo' command generates a number of additional artifacts,
181 // but we're only interested in the header.
182 // Shunt the rest of the outputs to a temporary directory.
183 objDir, err := os.MkdirTemp(GOPATH, "_obj")
187 defer os.RemoveAll(objDir)
189 files, err := filepath.Glob(filepath.Join(dir, "*.go"))
194 cmd := exec.Command("go", "tool", "cgo",
196 "-exportheader", header)
197 cmd.Args = append(cmd.Args, files...)
199 if out, err := cmd.CombinedOutput(); err != nil {
205 func testInstall(t *testing.T, exe, libgoa, libgoh string, buildcmd ...string) {
207 cmd := exec.Command(buildcmd[0], buildcmd[1:]...)
208 cmd.Env = append(cmd.Environ(), "GO111MODULE=off") // 'go install' only works in GOPATH mode
210 if out, err := cmd.CombinedOutput(); err != nil {
221 ccArgs := append(cc, "-o", exe, "main.c")
222 if GOOS == "windows" {
223 ccArgs = append(ccArgs, "main_windows.c", libgoa, "-lntdll", "-lws2_32", "-lwinmm")
225 ccArgs = append(ccArgs, "main_unix.c", libgoa)
227 if runtime.Compiler == "gccgo" {
228 ccArgs = append(ccArgs, "-lgo")
231 if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil {
239 binArgs := append(cmdToRun(exe), "arg1", "arg2")
240 cmd = exec.Command(binArgs[0], binArgs[1:]...)
241 if runtime.Compiler == "gccgo" {
242 cmd.Env = append(cmd.Environ(), "GCCGO=1")
244 if out, err := cmd.CombinedOutput(); err != nil {
249 checkLineComments(t, libgoh)
252 var badLineRegexp = regexp.MustCompile(`(?m)^#line [0-9]+ "/.*$`)
254 // checkLineComments checks that the export header generated by
255 // -buildmode=c-archive doesn't have any absolute paths in the #line
256 // comments. We don't want those paths because they are unhelpful for
257 // the user and make the files change based on details of the location
259 func checkLineComments(t *testing.T, hdrname string) {
260 hdr, err := os.ReadFile(hdrname)
262 if !os.IsNotExist(err) {
267 if line := badLineRegexp.Find(hdr); line != nil {
268 t.Errorf("bad #line directive with absolute path in %s: %q", hdrname, line)
272 // checkArchive verifies that the created library looks OK.
273 // We just check a couple of things now, we can add more checks as needed.
274 func checkArchive(t *testing.T, arname string) {
278 case "aix", "darwin", "ios", "windows":
279 // We don't have any checks for non-ELF libraries yet.
280 if _, err := os.Stat(arname); err != nil {
281 t.Errorf("archive %s does not exist: %v", arname, err)
284 checkELFArchive(t, arname)
288 // checkELFArchive checks an ELF archive.
289 func checkELFArchive(t *testing.T, arname string) {
292 f, err := os.Open(arname)
294 t.Errorf("archive %s does not exist: %v", arname, err)
299 // TODO(iant): put these in a shared package? But where?
311 hdrlen = namelen + datelen + uidlen + gidlen + modelen + sizelen + fmaglen
324 var magbuf [len(magic)]byte
325 if _, err := io.ReadFull(f, magbuf[:]); err != nil {
326 t.Errorf("%s: archive too short", arname)
329 if string(magbuf[:]) != magic {
330 t.Errorf("%s: incorrect archive magic string %q", arname, magbuf)
333 off := int64(len(magic))
337 if _, err := f.Read(b[:]); err != nil {
341 t.Errorf("%s: error skipping alignment byte at %d: %v", arname, off, err)
346 var hdrbuf [hdrlen]byte
347 if _, err := io.ReadFull(f, hdrbuf[:]); err != nil {
351 t.Errorf("%s: error reading archive header at %d: %v", arname, off, err)
356 hdrslice := hdrbuf[:]
357 set := func(len int, ps *string) {
358 *ps = string(bytes.TrimSpace(hdrslice[:len]))
359 hdrslice = hdrslice[len:]
361 set(namelen, &hdr.name)
362 set(datelen, &hdr.date)
363 set(uidlen, &hdr.uid)
364 set(gidlen, &hdr.gid)
365 set(modelen, &hdr.mode)
366 set(sizelen, &hdr.size)
367 hdr.fmag = string(hdrslice[:fmaglen])
368 hdrslice = hdrslice[fmaglen:]
369 if len(hdrslice) != 0 {
370 t.Fatalf("internal error: len(hdrslice) == %d", len(hdrslice))
373 if hdr.fmag != fmag {
374 t.Errorf("%s: invalid fmagic value %q at %d", arname, hdr.fmag, off)
378 size, err := strconv.ParseInt(hdr.size, 10, 64)
380 t.Errorf("%s: error parsing size %q at %d: %v", arname, hdr.size, off, err)
387 case "__.SYMDEF", "/", "/SYM64/":
388 // The archive symbol map.
389 case "//", "ARFILENAMES/":
390 // The extended name table.
392 // This should be an ELF object.
393 checkELFArchiveObject(t, arname, off, io.NewSectionReader(f, off, size))
397 if _, err := f.Seek(off, os.SEEK_SET); err != nil {
398 t.Errorf("%s: failed to seek to %d: %v", arname, off, err)
403 // checkELFArchiveObject checks an object in an ELF archive.
404 func checkELFArchiveObject(t *testing.T, arname string, off int64, obj io.ReaderAt) {
407 ef, err := elf.NewFile(obj)
409 t.Errorf("%s: failed to open ELF file at %d: %v", arname, off, err)
414 // Verify section types.
415 for _, sec := range ef.Sections {
418 case ".text", ".data":
419 want = elf.SHT_PROGBITS
421 want = elf.SHT_NOBITS
423 want = elf.SHT_SYMTAB
425 want = elf.SHT_STRTAB
427 want = elf.SHT_INIT_ARRAY
429 want = elf.SHT_FINI_ARRAY
430 case ".preinit_array":
431 want = elf.SHT_PREINIT_ARRAY
433 if want != elf.SHT_NULL && sec.Type != want {
434 t.Errorf("%s: incorrect section type in elf file at %d for section %q: got %v want %v", arname, off, sec.Name, sec.Type, want)
439 func TestInstall(t *testing.T) {
441 defer os.RemoveAll(filepath.Join(GOPATH, "pkg"))
445 if runtime.Compiler == "gccgo" {
446 libgoa = "liblibgo.a"
449 // Generate the p.h header file.
451 // 'go install -i -buildmode=c-archive ./libgo' would do that too, but that
452 // would also attempt to install transitive standard-library dependencies to
453 // GOROOT, and we cannot assume that GOROOT is writable. (A non-root user may
454 // be running this test in a GOROOT owned by root.)
455 genHeader(t, "p.h", "./p")
457 testInstall(t, "./testp1"+exeSuffix,
458 filepath.Join(libgodir, libgoa),
459 filepath.Join(libgodir, "libgo.h"),
460 "go", "install", "-buildmode=c-archive", "./libgo")
462 // Test building libgo other than installing it.
463 // Header files are now present.
464 testInstall(t, "./testp2"+exeSuffix, "libgo.a", "libgo.h",
465 "go", "build", "-buildmode=c-archive", filepath.Join(".", "libgo", "libgo.go"))
467 testInstall(t, "./testp3"+exeSuffix, "libgo.a", "libgo.h",
468 "go", "build", "-buildmode=c-archive", "-o", "libgo.a", "./libgo")
471 func TestEarlySignalHandler(t *testing.T) {
473 case "darwin", "ios":
476 t.Skipf("skipping on %s/%s; see https://golang.org/issue/13701", GOOS, GOARCH)
479 t.Skip("skipping signal test on Windows")
484 os.Remove("libgo2.a")
485 os.Remove("libgo2.h")
486 os.Remove("testp" + exeSuffix)
487 os.RemoveAll(filepath.Join(GOPATH, "pkg"))
491 cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo2.a", "./libgo2")
492 if out, err := cmd.CombinedOutput(); err != nil {
496 checkLineComments(t, "libgo2.h")
497 checkArchive(t, "libgo2.a")
499 ccArgs := append(cc, "-o", "testp"+exeSuffix, "main2.c", "libgo2.a")
500 if runtime.Compiler == "gccgo" {
501 ccArgs = append(ccArgs, "-lgo")
503 if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil {
509 if runtime.GOOS == "darwin" {
512 cmd = exec.Command(bin[0], append(bin[1:], darwin)...)
514 if out, err := cmd.CombinedOutput(); err != nil {
520 func TestSignalForwarding(t *testing.T) {
521 checkSignalForwardingTest(t)
525 os.Remove("libgo2.a")
526 os.Remove("libgo2.h")
527 os.Remove("testp" + exeSuffix)
528 os.RemoveAll(filepath.Join(GOPATH, "pkg"))
532 cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo2.a", "./libgo2")
533 if out, err := cmd.CombinedOutput(); err != nil {
537 checkLineComments(t, "libgo2.h")
538 checkArchive(t, "libgo2.a")
540 ccArgs := append(cc, "-o", "testp"+exeSuffix, "main5.c", "libgo2.a")
541 if runtime.Compiler == "gccgo" {
542 ccArgs = append(ccArgs, "-lgo")
544 if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil {
549 cmd = exec.Command(bin[0], append(bin[1:], "1")...)
551 out, err := cmd.CombinedOutput()
552 t.Logf("%v\n%s", cmd.Args, out)
553 expectSignal(t, err, syscall.SIGSEGV)
555 // SIGPIPE is never forwarded on darwin. See golang.org/issue/33384.
556 if runtime.GOOS != "darwin" && runtime.GOOS != "ios" {
557 // Test SIGPIPE forwarding
558 cmd = exec.Command(bin[0], append(bin[1:], "3")...)
560 out, err = cmd.CombinedOutput()
564 expectSignal(t, err, syscall.SIGPIPE)
568 func TestSignalForwardingExternal(t *testing.T) {
569 if GOOS == "freebsd" || GOOS == "aix" {
570 t.Skipf("skipping on %s/%s; signal always goes to the Go runtime", GOOS, GOARCH)
571 } else if GOOS == "darwin" && GOARCH == "amd64" {
572 t.Skipf("skipping on %s/%s: runtime does not permit SI_USER SIGSEGV", GOOS, GOARCH)
574 checkSignalForwardingTest(t)
578 os.Remove("libgo2.a")
579 os.Remove("libgo2.h")
580 os.Remove("testp" + exeSuffix)
581 os.RemoveAll(filepath.Join(GOPATH, "pkg"))
585 cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo2.a", "./libgo2")
586 if out, err := cmd.CombinedOutput(); err != nil {
590 checkLineComments(t, "libgo2.h")
591 checkArchive(t, "libgo2.a")
593 ccArgs := append(cc, "-o", "testp"+exeSuffix, "main5.c", "libgo2.a")
594 if runtime.Compiler == "gccgo" {
595 ccArgs = append(ccArgs, "-lgo")
597 if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil {
602 // We want to send the process a signal and see if it dies.
603 // Normally the signal goes to the C thread, the Go signal
604 // handler picks it up, sees that it is running in a C thread,
605 // and the program dies. Unfortunately, occasionally the
606 // signal is delivered to a Go thread, which winds up
607 // discarding it because it was sent by another program and
608 // there is no Go handler for it. To avoid this, run the
609 // program several times in the hopes that it will eventually
612 for i := 0; i < tries; i++ {
613 cmd = exec.Command(bin[0], append(bin[1:], "2")...)
615 stderr, err := cmd.StderrPipe()
621 r := bufio.NewReader(stderr)
629 // Wait for trigger to ensure that the process is started.
630 ok, err := r.ReadString('\n')
633 if err != nil || ok != "OK\n" {
634 t.Fatalf("Did not receive OK signal")
637 // Give the program a chance to enter the sleep function.
638 time.Sleep(time.Millisecond)
640 cmd.Process.Signal(syscall.SIGSEGV)
648 if expectSignal(t, err, syscall.SIGSEGV) {
653 t.Errorf("program succeeded unexpectedly %d times", tries)
656 // checkSignalForwardingTest calls t.Skip if the SignalForwarding test
657 // doesn't work on this platform.
658 func checkSignalForwardingTest(t *testing.T) {
660 case "darwin", "ios":
663 t.Skipf("skipping on %s/%s; see https://golang.org/issue/13701", GOOS, GOARCH)
666 t.Skip("skipping signal test on Windows")
670 // expectSignal checks that err, the exit status of a test program,
671 // shows a failure due to a specific signal. Returns whether we found
672 // the expected signal.
673 func expectSignal(t *testing.T, err error, sig syscall.Signal) bool {
675 t.Error("test program succeeded unexpectedly")
676 } else if ee, ok := err.(*exec.ExitError); !ok {
677 t.Errorf("error (%v) has type %T; expected exec.ExitError", err, err)
678 } else if ws, ok := ee.Sys().(syscall.WaitStatus); !ok {
679 t.Errorf("error.Sys (%v) has type %T; expected syscall.WaitStatus", ee.Sys(), ee.Sys())
680 } else if !ws.Signaled() || ws.Signal() != sig {
681 t.Errorf("got %v; expected signal %v", ee, sig)
688 func TestOsSignal(t *testing.T) {
691 t.Skip("skipping signal test on Windows")
696 os.Remove("libgo3.a")
697 os.Remove("libgo3.h")
698 os.Remove("testp" + exeSuffix)
699 os.RemoveAll(filepath.Join(GOPATH, "pkg"))
703 cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo3.a", "./libgo3")
704 if out, err := cmd.CombinedOutput(); err != nil {
708 checkLineComments(t, "libgo3.h")
709 checkArchive(t, "libgo3.a")
711 ccArgs := append(cc, "-o", "testp"+exeSuffix, "main3.c", "libgo3.a")
712 if runtime.Compiler == "gccgo" {
713 ccArgs = append(ccArgs, "-lgo")
715 if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil {
720 if out, err := exec.Command(bin[0], bin[1:]...).CombinedOutput(); err != nil {
726 func TestSigaltstack(t *testing.T) {
729 t.Skip("skipping signal test on Windows")
734 os.Remove("libgo4.a")
735 os.Remove("libgo4.h")
736 os.Remove("testp" + exeSuffix)
737 os.RemoveAll(filepath.Join(GOPATH, "pkg"))
741 cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo4.a", "./libgo4")
742 if out, err := cmd.CombinedOutput(); err != nil {
746 checkLineComments(t, "libgo4.h")
747 checkArchive(t, "libgo4.a")
749 ccArgs := append(cc, "-o", "testp"+exeSuffix, "main4.c", "libgo4.a")
750 if runtime.Compiler == "gccgo" {
751 ccArgs = append(ccArgs, "-lgo")
753 if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil {
758 if out, err := exec.Command(bin[0], bin[1:]...).CombinedOutput(); err != nil {
764 const testar = `#!/usr/bin/env bash
765 while [[ $1 == -* ]] >/dev/null; do
769 echo "testar" > PWD/testar.ran
772 func TestExtar(t *testing.T) {
775 t.Skip("skipping signal test on Windows")
777 if runtime.Compiler == "gccgo" {
778 t.Skip("skipping -extar test when using gccgo")
780 if runtime.GOOS == "ios" {
781 t.Skip("shell scripts are not executable on iOS hosts")
786 os.Remove("libgo4.a")
787 os.Remove("libgo4.h")
789 os.Remove("testar.ran")
790 os.RemoveAll(filepath.Join(GOPATH, "pkg"))
795 dir, err := os.Getwd()
799 s := strings.Replace(testar, "PWD", dir, 1)
800 if err := os.WriteFile("testar", []byte(s), 0777); err != nil {
804 cmd := exec.Command("go", "build", "-buildmode=c-archive", "-ldflags=-extar="+filepath.Join(dir, "testar"), "-o", "libgo4.a", "./libgo4")
805 if out, err := cmd.CombinedOutput(); err != nil {
809 checkLineComments(t, "libgo4.h")
811 if _, err := os.Stat("testar.ran"); err != nil {
812 if os.IsNotExist(err) {
813 t.Error("testar does not exist after go build")
815 t.Errorf("error checking testar: %v", err)
820 func TestPIE(t *testing.T) {
822 case "windows", "darwin", "ios", "plan9":
823 t.Skipf("skipping PIE test on %s", GOOS)
827 if runtime.Compiler == "gccgo" {
828 libgoa = "liblibgo.a"
833 os.Remove("testp" + exeSuffix)
835 os.RemoveAll(filepath.Join(GOPATH, "pkg"))
839 // Generate the p.h header file.
841 // 'go install -i -buildmode=c-archive ./libgo' would do that too, but that
842 // would also attempt to install transitive standard-library dependencies to
843 // GOROOT, and we cannot assume that GOROOT is writable. (A non-root user may
844 // be running this test in a GOROOT owned by root.)
845 genHeader(t, "p.h", "./p")
847 cmd := exec.Command("go", "build", "-buildmode=c-archive", "./libgo")
848 if out, err := cmd.CombinedOutput(); err != nil {
853 ccArgs := append(cc, "-fPIE", "-pie", "-o", "testp"+exeSuffix, "main.c", "main_unix.c", libgoa)
854 if runtime.Compiler == "gccgo" {
855 ccArgs = append(ccArgs, "-lgo")
857 if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil {
862 binArgs := append(bin, "arg1", "arg2")
863 cmd = exec.Command(binArgs[0], binArgs[1:]...)
864 if runtime.Compiler == "gccgo" {
865 cmd.Env = append(os.Environ(), "GCCGO=1")
867 if out, err := cmd.CombinedOutput(); err != nil {
873 f, err := elf.Open("testp" + exeSuffix)
875 t.Fatal("elf.Open failed: ", err)
878 if hasDynTag(t, f, elf.DT_TEXTREL) {
879 t.Errorf("%s has DT_TEXTREL flag", "testp"+exeSuffix)
884 func hasDynTag(t *testing.T, f *elf.File, tag elf.DynTag) bool {
885 ds := f.SectionByType(elf.SHT_DYNAMIC)
887 t.Error("no SHT_DYNAMIC section")
892 t.Errorf("can't read SHT_DYNAMIC contents: %v", err)
899 t = elf.DynTag(f.ByteOrder.Uint32(d[:4]))
902 t = elf.DynTag(f.ByteOrder.Uint64(d[:8]))
912 func TestSIGPROF(t *testing.T) {
914 case "windows", "plan9":
915 t.Skipf("skipping SIGPROF test on %s", GOOS)
916 case "darwin", "ios":
917 t.Skipf("skipping SIGPROF test on %s; see https://golang.org/issue/19320", GOOS)
924 os.Remove("testp6" + exeSuffix)
925 os.Remove("libgo6.a")
926 os.Remove("libgo6.h")
930 cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo6.a", "./libgo6")
931 out, err := cmd.CombinedOutput()
932 t.Logf("%v\n%s", cmd.Args, out)
936 checkLineComments(t, "libgo6.h")
937 checkArchive(t, "libgo6.a")
939 ccArgs := append(cc, "-o", "testp6"+exeSuffix, "main6.c", "libgo6.a")
940 if runtime.Compiler == "gccgo" {
941 ccArgs = append(ccArgs, "-lgo")
943 out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput()
944 t.Logf("%v\n%s", ccArgs, out)
949 argv := cmdToRun("./testp6")
950 cmd = exec.Command(argv[0], argv[1:]...)
951 out, err = cmd.CombinedOutput()
952 t.Logf("%v\n%s", argv, out)
958 // TestCompileWithoutShared tests that if we compile code without the
959 // -shared option, we can put it into an archive. When we use the go
960 // tool with -buildmode=c-archive, it passes -shared to the compiler,
961 // so we override that. The go tool doesn't work this way, but Bazel
962 // will likely do it in the future. And it ought to work. This test
963 // was added because at one time it did not work on PPC Linux.
964 func TestCompileWithoutShared(t *testing.T) {
965 // For simplicity, reuse the signal forwarding test.
966 checkSignalForwardingTest(t)
970 os.Remove("libgo2.a")
971 os.Remove("libgo2.h")
975 cmd := exec.Command("go", "build", "-buildmode=c-archive", "-gcflags=-shared=false", "-o", "libgo2.a", "./libgo2")
976 out, err := cmd.CombinedOutput()
977 t.Logf("%v\n%s", cmd.Args, out)
981 checkLineComments(t, "libgo2.h")
982 checkArchive(t, "libgo2.a")
984 exe := "./testnoshared" + exeSuffix
986 // In some cases, -no-pie is needed here, but not accepted everywhere. First try
987 // if -no-pie is accepted. See #22126.
988 ccArgs := append(cc, "-o", exe, "-no-pie", "main5.c", "libgo2.a")
989 if runtime.Compiler == "gccgo" {
990 ccArgs = append(ccArgs, "-lgo")
992 out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput()
993 t.Logf("%v\n%s", ccArgs, out)
995 // If -no-pie unrecognized, try -nopie if this is possibly clang
996 if err != nil && bytes.Contains(out, []byte("unknown")) && !strings.Contains(cc[0], "gcc") {
997 ccArgs = append(cc, "-o", exe, "-nopie", "main5.c", "libgo2.a")
998 out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput()
999 t.Logf("%v\n%s", ccArgs, out)
1002 // Don't use either -no-pie or -nopie
1003 if err != nil && bytes.Contains(out, []byte("unrecognized")) {
1004 ccArgs = append(cc, "-o", exe, "main5.c", "libgo2.a")
1005 out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput()
1006 t.Logf("%v\n%s", ccArgs, out)
1012 defer os.Remove(exe)
1015 binArgs := append(cmdToRun(exe), "1")
1016 out, err = exec.Command(binArgs[0], binArgs[1:]...).CombinedOutput()
1017 t.Logf("%v\n%s", binArgs, out)
1018 expectSignal(t, err, syscall.SIGSEGV)
1020 // SIGPIPE is never forwarded on darwin. See golang.org/issue/33384.
1021 if runtime.GOOS != "darwin" && runtime.GOOS != "ios" {
1022 binArgs := append(cmdToRun(exe), "3")
1023 out, err = exec.Command(binArgs[0], binArgs[1:]...).CombinedOutput()
1024 t.Logf("%v\n%s", binArgs, out)
1025 expectSignal(t, err, syscall.SIGPIPE)
1029 // Test that installing a second time recreates the header file.
1030 func TestCachedInstall(t *testing.T) {
1032 defer os.RemoveAll(filepath.Join(GOPATH, "pkg"))
1035 h := filepath.Join(libgodir, "libgo.h")
1037 buildcmd := []string{"go", "install", "-buildmode=c-archive", "./libgo"}
1039 cmd := exec.Command(buildcmd[0], buildcmd[1:]...)
1040 cmd.Env = append(cmd.Environ(), "GO111MODULE=off") // 'go install' only works in GOPATH mode
1042 if out, err := cmd.CombinedOutput(); err != nil {
1047 if _, err := os.Stat(h); err != nil {
1048 t.Errorf("libgo.h not installed: %v", err)
1051 if err := os.Remove(h); err != nil {
1055 cmd = exec.Command(buildcmd[0], buildcmd[1:]...)
1056 cmd.Env = append(cmd.Environ(), "GO111MODULE=off")
1058 if out, err := cmd.CombinedOutput(); err != nil {
1063 if _, err := os.Stat(h); err != nil {
1064 t.Errorf("libgo.h not installed in second run: %v", err)
1069 func TestManyCalls(t *testing.T) {
1074 os.Remove("testp7" + exeSuffix)
1075 os.Remove("libgo7.a")
1076 os.Remove("libgo7.h")
1080 cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo7.a", "./libgo7")
1081 out, err := cmd.CombinedOutput()
1082 t.Logf("%v\n%s", cmd.Args, out)
1086 checkLineComments(t, "libgo7.h")
1087 checkArchive(t, "libgo7.a")
1089 ccArgs := append(cc, "-o", "testp7"+exeSuffix, "main7.c", "libgo7.a")
1090 if runtime.Compiler == "gccgo" {
1091 ccArgs = append(ccArgs, "-lgo")
1093 out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput()
1094 t.Logf("%v\n%s", ccArgs, out)
1099 argv := cmdToRun("./testp7")
1100 cmd = exec.Command(argv[0], argv[1:]...)
1101 sb := new(strings.Builder)
1104 if err := cmd.Start(); err != nil {
1108 timer := time.AfterFunc(time.Minute,
1110 t.Error("test program timed out")
1117 t.Logf("%v\n%s", cmd.Args, sb)
1124 func TestPreemption(t *testing.T) {
1125 if runtime.Compiler == "gccgo" {
1126 t.Skip("skipping asynchronous preemption test with gccgo")
1133 os.Remove("testp8" + exeSuffix)
1134 os.Remove("libgo8.a")
1135 os.Remove("libgo8.h")
1139 cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo8.a", "./libgo8")
1140 out, err := cmd.CombinedOutput()
1141 t.Logf("%v\n%s", cmd.Args, out)
1145 checkLineComments(t, "libgo8.h")
1146 checkArchive(t, "libgo8.a")
1148 ccArgs := append(cc, "-o", "testp8"+exeSuffix, "main8.c", "libgo8.a")
1149 out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput()
1150 t.Logf("%v\n%s", ccArgs, out)
1155 argv := cmdToRun("./testp8")
1156 cmd = exec.Command(argv[0], argv[1:]...)
1157 sb := new(strings.Builder)
1160 if err := cmd.Start(); err != nil {
1164 timer := time.AfterFunc(time.Minute,
1166 t.Error("test program timed out")
1173 t.Logf("%v\n%s", cmd.Args, sb)