From 1097a07b097043e15fe29a85326dbd196401244a Mon Sep 17 00:00:00 2001
From: Changqing Li <changqing.li@windriver.com>
Date: Tue, 27 Feb 2024 18:06:51 +0800
Subject: [PATCH] exec.go: filter out build-specific paths from linker flags

The flags can contain build-specific paths, breaking reproducibility.
Filter out options that have build-specific paths.

Upstream-Status: Inappropriate [ Not perfect for upstream ]

Signed-off-by: Changqing Li <changqing.li@windriver.com>
Signed-off-by: Jose Quaresma <jose.quaresma@foundries.io>
---
 src/cmd/go/internal/work/exec.go | 25 ++++++++++++++++++++++++-
 1 file changed, 24 insertions(+), 1 deletion(-)

diff --git a/src/cmd/go/internal/work/exec.go b/src/cmd/go/internal/work/exec.go
index 544df46..c8f297c 100644
--- a/src/cmd/go/internal/work/exec.go
+++ b/src/cmd/go/internal/work/exec.go
@@ -1401,6 +1401,29 @@ func (b *Builder) linkActionID(a *Action) cache.ActionID {
 	return h.Sum()
 }
 
+func filterLinkerFlags(flags []string) []string {
+	var newflags []string
+	var skipflag bool
+	skipflag = false
+	for i, flag := range flags {
+		if skipflag == true {
+			skipflag = false
+			continue
+		}
+		if strings.HasPrefix(flag, "--sysroot") || strings.HasPrefix(flag, "-fmacro-prefix-map") || strings.HasPrefix(flag, "-fdebug-prefix-map") || strings.HasPrefix(flag, "-ffile-prefix-map") || strings.HasPrefix(flag, "-fcanon-prefix-map") || strings.HasPrefix(flag, "-fprofile-prefix-map") || strings.HasPrefix(flag, "-Wl,-rpath-link"){
+			continue
+		} else if strings.HasPrefix(flag, "-extldflags") {
+			skipflag = true
+			newflags = append(newflags, flag)
+			var filterd_Extldflags []string = filterLinkerFlags(strings.Split(flags[i+1], " "))
+			newflags = append(newflags, strings.Join(filterd_Extldflags, " "))
+		} else {
+			newflags = append(newflags, flag)
+		}
+	}
+	return newflags
+}
+
 // printLinkerConfig prints the linker config into the hash h,
 // as part of the computation of a linker-related action ID.
 func (b *Builder) printLinkerConfig(h io.Writer, p *load.Package) {
@@ -1411,7 +1434,7 @@ func (b *Builder) printLinkerConfig(h io.Writer, p *load.Package) {
 	case "gc":
 		fmt.Fprintf(h, "link %s %q %s\n", b.toolID("link"), forcedLdflags, ldBuildmode)
 		if p != nil {
-			fmt.Fprintf(h, "linkflags %q\n", p.Internal.Ldflags)
+			fmt.Fprintf(h, "linkflags %q\n", filterLinkerFlags(p.Internal.Ldflags))
 		}
 
 		// GOARM, GOMIPS, etc.
