compiler_wrapper: Filter "-z,defs" from linker thoroughly

Remove "-z,defs" from linker options even when it is part of a
longer "-Wl,bar,-z,defs,foo".

BUG=b:261897667
TEST=libsepol and libselinux build

Change-Id: I993e3efada14dbff653894fc36af168a9cc372b1
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/toolchain-utils/+/4129877
Reviewed-by: Ryan Beltran <ryanbeltran@chromium.org>
Auto-Submit: Manoj Gupta <manojgupta@chromium.org>
Commit-Queue: Ryan Beltran <ryanbeltran@chromium.org>
Tested-by: Manoj Gupta <manojgupta@chromium.org>
diff --git a/compiler_wrapper/sanitizer_flags.go b/compiler_wrapper/sanitizer_flags.go
index 58312cc..3bf4434 100644
--- a/compiler_wrapper/sanitizer_flags.go
+++ b/compiler_wrapper/sanitizer_flags.go
@@ -73,9 +73,13 @@
 	builder.transformArgs(func(arg builderArg) string {
 		// TODO: This is a bug in the old wrapper to not filter
 		// non user args for gcc. Fix this once we don't compare to the old wrapper anymore.
-		if (builder.target.compilerType != gccType || arg.fromUser) &&
-			unsupportedSanitizerFlags[arg.value] {
-			return ""
+		linkerDefinedFlag := ",-z,defs"
+		if builder.target.compilerType != gccType || arg.fromUser {
+			if unsupportedSanitizerFlags[arg.value] {
+				return ""
+			} else if strings.Contains(arg.value, linkerDefinedFlag) {
+				return strings.ReplaceAll(arg.value, linkerDefinedFlag, "")
+			}
 		}
 		return arg.value
 	})
diff --git a/compiler_wrapper/sanitizer_flags_test.go b/compiler_wrapper/sanitizer_flags_test.go
index b4b1fd8..8fb3e9f 100644
--- a/compiler_wrapper/sanitizer_flags_test.go
+++ b/compiler_wrapper/sanitizer_flags_test.go
@@ -45,6 +45,12 @@
 		}
 
 		cmd = ctx.must(callCompiler(ctx, ctx.cfg,
+			ctx.newCommand(gccX86_64, "-fsanitize=kernel-address", "-Wl,-z,defs,relro", mainCc)))
+		if err := verifyArgCount(cmd, 1, "-Wl,relro"); err != nil {
+			t.Error(err)
+		}
+
+		cmd = ctx.must(callCompiler(ctx, ctx.cfg,
 			ctx.newCommand(gccX86_64, "-fsanitize=kernel-address", "-Wl,-z -Wl,defs", mainCc)))
 		if err := verifyArgCount(cmd, 0, "-Wl,-z"); err != nil {
 			t.Error(err)