3 //go:build !nacl && !js && gc && !wasip1
5 // Copyright 2016 The Go Authors. All rights reserved.
6 // Use of this source code is governed by a BSD-style
7 // license that can be found in the LICENSE file.
9 // Test the compiler -linkobj flag.
22 var pwd, tmpdir string
25 dir, err := ioutil.TempDir("", "go-test-linkobj-")
33 if err := os.Chdir(dir); err != nil {
43 println("hello from p1")
53 println("hello from p2")
65 println("hello from main")
69 stdlibimportcfg, err := os.ReadFile(os.Getenv("STDLIB_IMPORTCFG"))
71 fatalf("listing stdlib export files: %v", err)
74 // two rounds: once using normal objects, again using .a files (compile -pack).
75 for round := 0; round < 2; round++ {
76 pkg := "-pack=" + fmt.Sprint(round)
78 // The compiler expects the files being read to have the right suffix.
84 importcfg := string(stdlibimportcfg) + "\npackagefile p1=p1." + o + "\npackagefile p2=p2." + o
85 os.WriteFile("importcfg", []byte(importcfg), 0644)
87 // inlining is disabled to make sure that the link objects contain needed code.
88 run("go", "tool", "compile", "-p=p1", pkg, "-D", ".", "-importcfg=importcfg", "-l", "-o", "p1."+o, "-linkobj", "p1.lo", "p1.go")
89 run("go", "tool", "compile", "-p=p2", pkg, "-D", ".", "-importcfg=importcfg", "-l", "-o", "p2."+o, "-linkobj", "p2.lo", "p2.go")
90 run("go", "tool", "compile", "-p=main", pkg, "-D", ".", "-importcfg=importcfg", "-l", "-o", "p3."+o, "-linkobj", "p3.lo", "p3.go")
98 out := runFail("go", "tool", "link", "p2."+o)
99 if !strings.Contains(out, "not package main") {
100 fatalf("link p2.o failed but not for package main:\n%s", out)
103 run("go", "tool", "link", "-importcfg=importcfg", "-o", "a.out.exe", "p3."+o)
104 out = run("./a.out.exe")
105 if !strings.Contains(out, "hello from p1\nhello from p2\nhello from main\n") {
106 fatalf("running main, incorrect output:\n%s", out)
109 // ensure that mistaken future round can't use these
111 os.Remove("a.out.exe")
117 func run(args ...string) string {
118 out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
120 fatalf("run %v: %s\n%s", args, err, out)
125 func runFail(args ...string) string {
126 out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
128 fatalf("runFail %v: unexpected success!\n%s", args, err, out)
133 func cp(src, dst string) {
134 data, err := ioutil.ReadFile(src)
138 err = ioutil.WriteFile(dst, data, 0666)
144 func writeFile(name, data string) {
145 err := ioutil.WriteFile(name, []byte(data), 0666)
154 println("TMPDIR:", tmpdir)
157 os.Chdir(pwd) // get out of tmpdir before removing it
161 func fatalf(format string, args ...interface{}) {
163 log.Fatalf(format, args...)