blob: b57041f1db376fe3da6db840a61e22b17028b651 [file] [log] [blame]
Andrew Geissler706d5aa2021-02-12 15:55:30 -06001From 4759221d46b1666de96b8047cec3160bfe4d3d5d Mon Sep 17 00:00:00 2001
2From: Ian Lance Taylor <iant@golang.org>
3Date: Fri, 13 Nov 2020 11:05:37 -0800
4Subject: [PATCH] cmd/go: permit CGO_LDFLAGS to appear in //go:ldflag
5
6Fixes #42565
7
8Upstream-Status: Backport [https://github.com/golang/go/commit/782cf560db4c919790fdb476d1bbe18e5ddf5ffd]
9Change-Id: If7cf39905d124dbd54dfac6a53ee38270498efed
10Reviewed-on: https://go-review.googlesource.com/c/go/+/269818
11Trust: Ian Lance Taylor <iant@golang.org>
12Run-TryBot: Ian Lance Taylor <iant@golang.org>
13TryBot-Result: Go Bot <gobot@golang.org>
14Reviewed-by: Jay Conrod <jayconrod@google.com>
15Signed-off-by: Khem Raj <raj.khem@gmail.com>
16---
17 src/cmd/go/internal/work/exec.go | 15 +++++++++
18 src/cmd/go/testdata/script/ldflag.txt | 44 +++++++++++++++++++++++++++
19 2 files changed, 59 insertions(+)
20 create mode 100644 src/cmd/go/testdata/script/ldflag.txt
21
22diff --git a/src/cmd/go/internal/work/exec.go b/src/cmd/go/internal/work/exec.go
23index 575a2df..9209e3d 100644
24--- a/src/cmd/go/internal/work/exec.go
25+++ b/src/cmd/go/internal/work/exec.go
26@@ -2821,6 +2821,21 @@ func (b *Builder) cgo(a *Action, cgoExe, objdir string, pcCFLAGS, pcLDFLAGS, cgo
27 idx = bytes.Index(src, []byte(cgoLdflag))
28 }
29 }
30+
31+ // We expect to find the contents of cgoLDFLAGS in flags.
32+ if len(cgoLDFLAGS) > 0 {
33+ outer:
34+ for i := range flags {
35+ for j, f := range cgoLDFLAGS {
36+ if f != flags[i+j] {
37+ continue outer
38+ }
39+ }
40+ flags = append(flags[:i], flags[i+len(cgoLDFLAGS):]...)
41+ break
42+ }
43+ }
44+
45 if err := checkLinkerFlags("LDFLAGS", "go:cgo_ldflag", flags); err != nil {
46 return nil, nil, err
47 }
48diff --git a/src/cmd/go/testdata/script/ldflag.txt b/src/cmd/go/testdata/script/ldflag.txt
49new file mode 100644
50index 0000000..6ceb33b
51--- /dev/null
52+++ b/src/cmd/go/testdata/script/ldflag.txt
53@@ -0,0 +1,44 @@
54+# Issue #42565
55+
56+[!cgo] skip
57+
58+# We can't build package bad, which uses #cgo LDFLAGS.
59+cd bad
60+! go build
61+stderr no-such-warning
62+
63+# We can build package ok with the same flags in CGO_LDFLAGS.
64+env CGO_LDFLAGS=-Wno-such-warning -Wno-unknown-warning-option
65+cd ../ok
66+go build
67+
68+# Build a main program that actually uses LDFLAGS.
69+cd ..
70+go build -ldflags=-v
71+
72+# Because we passed -v the Go linker should print the external linker
73+# command which should include the flag we passed in CGO_LDFLAGS.
74+stderr no-such-warning
75+
76+-- go.mod --
77+module ldflag
78+
79+-- bad/bad.go --
80+package bad
81+
82+// #cgo LDFLAGS: -Wno-such-warning -Wno-unknown-warning
83+import "C"
84+
85+func F() {}
86+-- ok/ok.go --
87+package ok
88+
89+import "C"
90+
91+func F() {}
92+-- main.go --
93+package main
94+
95+import _ "ldflag/ok"
96+
97+func main() {}
98--
992.29.2
100