]> Cypherpunks repositories - gostls13.git/commitdiff
cmd/go: use the last -linkmode flag to determine external linking
authorXiangdong Ji <xiangdong.ji@gmail.com>
Sun, 18 Oct 2020 18:43:23 +0000 (11:43 -0700)
committerBryan C. Mills <bcmills@google.com>
Thu, 22 Oct 2020 14:51:57 +0000 (14:51 +0000)
Current linkmode checking in determining package dependencies doesn't
take multiple -linkmode options into consideration, may lead to redundant
dependency on 'runtime/cgo'.

Fixes the problem and adds a testcase.

Change-Id: Iac5ea9fb3ca5ef931201afd0f3441f41f946c919
Reviewed-on: https://go-review.googlesource.com/c/go/+/263497
Trust: Jay Conrod <jayconrod@google.com>
Reviewed-by: Bryan C. Mills <bcmills@google.com>
src/cmd/go/internal/load/pkg.go
src/cmd/go/testdata/script/gcflags_patterns.txt

index c9665265e943421d9e2e5a6606e6aa753b2aa403..f07bd3e075ef959711de2c89c77a67654fba276b 100644 (file)
@@ -1978,16 +1978,20 @@ func externalLinkingForced(p *Package) bool {
        // external linking mode, as of course does
        // -ldflags=-linkmode=external. External linking mode forces
        // an import of runtime/cgo.
+       // If there are multiple -linkmode options, the last one wins.
        pieCgo := cfg.BuildBuildmode == "pie" && !sys.InternalLinkPIESupported(cfg.BuildContext.GOOS, cfg.BuildContext.GOARCH)
        linkmodeExternal := false
        if p != nil {
                ldflags := BuildLdflags.For(p)
-               for i, a := range ldflags {
-                       if a == "-linkmode=external" {
-                               linkmodeExternal = true
-                       }
-                       if a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
+               for i := len(ldflags) - 1; i >= 0; i-- {
+                       a := ldflags[i]
+                       if a == "-linkmode=external" ||
+                               a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
                                linkmodeExternal = true
+                               break
+                       } else if a == "-linkmode=internal" ||
+                               a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "internal" {
+                               break
                        }
                }
        }
index 5374493a439e0a0c491a6ea617090d3f47d16217..f23cecefd3aa30e87ef45d26b15949c2f88d3f28 100644 (file)
@@ -63,6 +63,10 @@ stderr 'link.* -X=math.pi=3'
 go build -n -ldflags=-X=math.pi=3
 stderr 'link.* -X=math.pi=3'
 
+# cgo.a should not be a dependency of internally-linked go package
+go build -ldflags='-linkmode=external -linkmode=internal' -n prog.go
+! stderr 'packagefile .*runtime/cgo.a'
+
 -- z1/z.go --
 package z1
 import _ "y"