1// run
2
3//go:build !nacl && !js && !wasip1 && gc
4
5// Copyright 2014 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.
8
9// Run the linkx test.
10
11package main
12
13import (
14	"bytes"
15	"fmt"
16	"os"
17	"os/exec"
18	"strings"
19)
20
21func main() {
22	// test(" ") // old deprecated & removed syntax
23	test("=") // new syntax
24}
25
26func test(sep string) {
27	// Successful run
28	cmd := exec.Command("go", "run", "-ldflags=-X main.tbd"+sep+"hello -X main.overwrite"+sep+"trumped -X main.nosuchsymbol"+sep+"neverseen", "linkx.go")
29	var out, errbuf bytes.Buffer
30	cmd.Stdout = &out
31	cmd.Stderr = &errbuf
32	err := cmd.Run()
33	if err != nil {
34		fmt.Println(errbuf.String())
35		fmt.Println(out.String())
36		fmt.Println(err)
37		os.Exit(1)
38	}
39
40	want := "hello\nhello\nhello\ntrumped\ntrumped\ntrumped\n"
41	got := out.String()
42	if got != want {
43		fmt.Printf("got %q want %q\n", got, want)
44		os.Exit(1)
45	}
46
47	// Issue 8810
48	cmd = exec.Command("go", "run", "-ldflags=-X main.tbd", "linkx.go")
49	_, err = cmd.CombinedOutput()
50	if err == nil {
51		fmt.Println("-X linker flag should not accept keys without values")
52		os.Exit(1)
53	}
54
55	// Issue 9621
56	cmd = exec.Command("go", "run", "-ldflags=-X main.b=false -X main.x=42", "linkx.go")
57	outx, err := cmd.CombinedOutput()
58	if err == nil {
59		fmt.Println("-X linker flag should not overwrite non-strings")
60		os.Exit(1)
61	}
62	outstr := string(outx)
63	if !strings.Contains(outstr, "main.b") {
64		fmt.Printf("-X linker flag did not diagnose overwrite of main.b:\n%s\n", outstr)
65		os.Exit(1)
66	}
67	if !strings.Contains(outstr, "main.x") {
68		fmt.Printf("-X linker flag did not diagnose overwrite of main.x:\n%s\n", outstr)
69		os.Exit(1)
70	}
71}
72