From fa8e52baedd21265f69b5f425157e11c8c4ec24a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=B6ren=20Tempel?= <soeren+git@soeren-tempel.net>
Date: Sat, 25 Mar 2023 09:08:04 +0100
Subject: [PATCH] cmd/link: prefer musl's over glibc's ld.so during dynamic
 linking

Without this commit glibc's is preferred over musl by default. This
causes issues on Alpine when a dynamically linked Go binary is created
while gcompat is installed, causing the binary to be linked against
the ld.so provided by the gcompat package.

This commit changes the logic to check for musl's ld.so first, if it
does not exist we fallback to glibc. This default can be overwritten
using the `-I` option of cmd/link.

See https://gitlab.alpinelinux.org/alpine/aports/-/issues/14737
---
 src/cmd/link/internal/ld/elf.go | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/cmd/link/internal/ld/elf.go b/src/cmd/link/internal/ld/elf.go
index 713f7739a5..8cf9377858 100644
--- a/src/cmd/link/internal/ld/elf.go
+++ b/src/cmd/link/internal/ld/elf.go
@@ -1886,14 +1886,14 @@ func asmbElf(ctxt *Link) {
 						Exitf("ELF interpreter not set")
 					}
 				} else {
-					interpreter = thearch.ELF.Linuxdynld
-					// If interpreter does not exist, try musl instead.
+					interpreter = thearch.ELF.LinuxdynldMusl
+					// If interpreter does not exist, try glibc instead.
 					// This lets the same cmd/link binary work on
-					// both glibc-based and musl-based systems.
+					// both musl-based and glibc-based systems.
 					if _, err := os.Stat(interpreter); err != nil {
-						if musl := thearch.ELF.LinuxdynldMusl; musl != "" {
-							if _, err := os.Stat(musl); err == nil {
-								interpreter = musl
+						if glibc := thearch.ELF.Linuxdynld; glibc != "" {
+							if _, err := os.Stat(glibc); err == nil {
+								interpreter = glibc
 							}
 						}
 					}
