1 // +build !nacl,!js,gc,!wasip1
4 // Copyright 2016 The Go Authors. All rights reserved.
5 // Use of this source code is governed by a BSD-style
6 // license that can be found in the LICENSE file.
8 // Test the compiler -linkobj flag.
21 var pwd, tmpdir string
24 dir, err := ioutil.TempDir("", "go-test-linkobj-")
32 if err := os.Chdir(dir); err != nil {
42 println("hello from p1")
52 println("hello from p2")
64 println("hello from main")
68 stdlibimportcfg, err := os.ReadFile(os.Getenv("STDLIB_IMPORTCFG"))
70 fatalf("listing stdlib export files: %v", err)
73 // two rounds: once using normal objects, again using .a files (compile -pack).
74 for round := 0; round < 2; round++ {
75 pkg := "-pack=" + fmt.Sprint(round)
77 // The compiler expects the files being read to have the right suffix.
83 importcfg := string(stdlibimportcfg) + "\npackagefile p1=p1." + o + "\npackagefile p2=p2." + o
84 os.WriteFile("importcfg", []byte(importcfg), 0644)
86 // inlining is disabled to make sure that the link objects contain needed code.
87 run("go", "tool", "compile", "-p=p1", pkg, "-D", ".", "-importcfg=importcfg", "-l", "-o", "p1."+o, "-linkobj", "p1.lo", "p1.go")
88 run("go", "tool", "compile", "-p=p2", pkg, "-D", ".", "-importcfg=importcfg", "-l", "-o", "p2."+o, "-linkobj", "p2.lo", "p2.go")
89 run("go", "tool", "compile", "-p=main", pkg, "-D", ".", "-importcfg=importcfg", "-l", "-o", "p3."+o, "-linkobj", "p3.lo", "p3.go")
97 out := runFail("go", "tool", "link", "p2."+o)
98 if !strings.Contains(out, "not package main") {
99 fatalf("link p2.o failed but not for package main:\n%s", out)
102 run("go", "tool", "link", "-importcfg=importcfg", "-o", "a.out.exe", "p3."+o)
103 out = run("./a.out.exe")
104 if !strings.Contains(out, "hello from p1\nhello from p2\nhello from main\n") {
105 fatalf("running main, incorrect output:\n%s", out)
108 // ensure that mistaken future round can't use these
110 os.Remove("a.out.exe")
116 func run(args ...string) string {
117 out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
119 fatalf("run %v: %s\n%s", args, err, out)
124 func runFail(args ...string) string {
125 out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
127 fatalf("runFail %v: unexpected success!\n%s", args, err, out)
132 func cp(src, dst string) {
133 data, err := ioutil.ReadFile(src)
137 err = ioutil.WriteFile(dst, data, 0666)
143 func writeFile(name, data string) {
144 err := ioutil.WriteFile(name, []byte(data), 0666)
153 println("TMPDIR:", tmpdir)
156 os.Chdir(pwd) // get out of tmpdir before removing it
160 func fatalf(format string, args ...interface{}) {
162 log.Fatalf(format, args...)