cmd/link: pass darwin/amd64-specific flags only on AMD64

The linker assumed macOS is AMD64 (and 386 in the past). It
passes darwin/amd64-specific flags to the external linker when
building for macOS. They don't work for ARM64-based macOS. So
only pass them on AMD64.

Disable DWARF combining for macOS ARM64 for now. The generated
binary doesn't run. (TODO: fix.)

For macOS ARM64 port. External linking now works.

Change-Id: Iab53bc48f4fadd9b91de8898b4b450ea442667a2
Reviewed-on: https://go-review.googlesource.com/c/go/+/253019
Run-TryBot: Cherry Zhang <cherryyz@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Than McIntosh <thanm@google.com>
diff --git a/src/cmd/link/internal/ld/lib.go b/src/cmd/link/internal/ld/lib.go
index d6ee437..702c902 100644
--- a/src/cmd/link/internal/ld/lib.go
+++ b/src/cmd/link/internal/ld/lib.go
@@ -1240,7 +1240,8 @@
 
 	switch ctxt.HeadType {
 	case objabi.Hdarwin:
-		if machoPlatform == PLATFORM_MACOS {
+		if machoPlatform == PLATFORM_MACOS && ctxt.IsAMD64() {
+			// Leave room for DWARF combining.
 			// -headerpad is incompatible with -fembed-bitcode.
 			argv = append(argv, "-Wl,-headerpad,1144")
 		}
@@ -1280,7 +1281,7 @@
 	switch ctxt.BuildMode {
 	case BuildModeExe:
 		if ctxt.HeadType == objabi.Hdarwin {
-			if machoPlatform == PLATFORM_MACOS {
+			if machoPlatform == PLATFORM_MACOS && ctxt.IsAMD64() {
 				argv = append(argv, "-Wl,-no_pie")
 				argv = append(argv, "-Wl,-pagezero_size,4000000")
 			}
@@ -1517,7 +1518,7 @@
 	// does not work, the resulting programs will not run. See
 	// issue #17847. To avoid this problem pass -no-pie to the
 	// toolchain if it is supported.
-	if ctxt.BuildMode == BuildModeExe && !ctxt.linkShared {
+	if ctxt.BuildMode == BuildModeExe && !ctxt.linkShared && !(ctxt.IsDarwin() && ctxt.IsARM64()) {
 		// GCC uses -no-pie, clang uses -nopie.
 		for _, nopie := range []string{"-no-pie", "-nopie"} {
 			if linkerFlagSupported(argv[0], altLinker, nopie) {
@@ -1607,7 +1608,7 @@
 			Exitf("%s: parsing Mach-O header failed: %v", os.Args[0], err)
 		}
 		// Only macOS supports unmapped segments such as our __DWARF segment.
-		if machoPlatform == PLATFORM_MACOS {
+		if machoPlatform == PLATFORM_MACOS && ctxt.IsAMD64() {
 			if err := machoCombineDwarf(ctxt, exef, exem, dsym, combinedOutput); err != nil {
 				Exitf("%s: combining dwarf failed: %v", os.Args[0], err)
 			}