From 737d78a9785ea3e928de2b36a4e3e7decd8c9491 Mon Sep 17 00:00:00 2001 From: Carlo Cabrera Date: Thu, 12 Dec 2024 16:15:20 +0800 Subject: [PATCH] [Darwin][Driver][clang] Prioritise command line args over `DEFAULT_SYSROOT` (#115993) If a toolchain is configured with `DEFAULT_SYSROOT`, then this could result in an unintended value for `-syslibroot` being passed to the linker if the user manually sets `-isysroot` or `SDKROOT`. Let's fix this by prioritising command line flags when determining `-syslibroot` before checking `getSysRoot`. Downstream bug report: https://github.com/Homebrew/homebrew-core/issues/197277 Co-authored-by: Bo Anderson Co-authored-by: Bo Anderson --- clang/lib/Driver/ToolChains/Darwin.cpp | 10 +++++++--- clang/test/Driver/sysroot.c | 3 +-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp b/clang/lib/Driver/ToolChains/Darwin.cpp index 87380869f6fdab..cdb6d21a0148b6 100644 --- a/clang/lib/Driver/ToolChains/Darwin.cpp +++ b/clang/lib/Driver/ToolChains/Darwin.cpp @@ -430,13 +430,17 @@ void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args, // Give --sysroot= preference, over the Apple specific behavior to also use // --isysroot as the syslibroot. - StringRef sysroot = C.getSysRoot(); - if (sysroot != "") { + // We check `OPT__sysroot_EQ` directly instead of `getSysRoot` to make sure we + // prioritise command line arguments over configuration of `DEFAULT_SYSROOT`. + if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) { CmdArgs.push_back("-syslibroot"); - CmdArgs.push_back(C.getArgs().MakeArgString(sysroot)); + CmdArgs.push_back(A->getValue()); } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { CmdArgs.push_back("-syslibroot"); CmdArgs.push_back(A->getValue()); + } else if (StringRef sysroot = C.getSysRoot(); sysroot != "") { + CmdArgs.push_back("-syslibroot"); + CmdArgs.push_back(C.getArgs().MakeArgString(sysroot)); } Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace); diff --git a/clang/test/Driver/sysroot.c b/clang/test/Driver/sysroot.c index 85da2499090af1..3080f76e031686 100644 --- a/clang/test/Driver/sysroot.c +++ b/clang/test/Driver/sysroot.c @@ -4,10 +4,9 @@ // CHECK-SYSROOTEQ: "-cc1"{{.*}} "-isysroot" "{{[^"]*}}/FOO" // Apple Darwin uses -isysroot as the syslib root, too. -// We pass --sysroot="" to defeat any -DDEFAULT_SYSROOT parameter. // RUN: touch %t2.o // RUN: %clang -target i386-apple-darwin10 \ -// RUN: -isysroot /FOO --sysroot="" -### %t2.o 2> %t2 +// RUN: -isysroot /FOO -### %t2.o 2> %t2 // RUN: FileCheck --check-prefix=CHECK-APPLE-ISYSROOT < %t2 %s // CHECK-APPLE-ISYSROOT: "-arch" "i386"{{.*}} "-syslibroot" "{{[^"]*}}/FOO"