master
1//===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This is the entry point to the clang driver; it is a thin wrapper
10// for functionality in the Driver clang library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Driver/Driver.h"
15#include "clang/Basic/DiagnosticOptions.h"
16#include "clang/Basic/HeaderInclude.h"
17#include "clang/Basic/Stack.h"
18#include "clang/Config/config.h"
19#include "clang/Driver/Compilation.h"
20#include "clang/Driver/DriverDiagnostic.h"
21#include "clang/Driver/Options.h"
22#include "clang/Driver/ToolChain.h"
23#include "clang/Frontend/ChainedDiagnosticConsumer.h"
24#include "clang/Frontend/CompilerInvocation.h"
25#include "clang/Frontend/SerializedDiagnosticPrinter.h"
26#include "clang/Frontend/TextDiagnosticPrinter.h"
27#include "clang/Frontend/Utils.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringSet.h"
32#include "llvm/Config/llvm-config.h" // for LLVM_ON_UNIX
33#include "llvm/Option/ArgList.h"
34#include "llvm/Option/OptTable.h"
35#include "llvm/Option/Option.h"
36#include "llvm/Support/BuryPointer.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/CrashRecoveryContext.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/FileSystem.h"
41#include "llvm/Support/LLVMDriver.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/PrettyStackTrace.h"
44#include "llvm/Support/Process.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/StringSaver.h"
48#include "llvm/Support/TargetSelect.h"
49#include "llvm/Support/Timer.h"
50#include "llvm/Support/VirtualFileSystem.h"
51#include "llvm/Support/raw_ostream.h"
52#include "llvm/TargetParser/Host.h"
53#include <memory>
54#include <optional>
55#include <set>
56#include <system_error>
57
58using namespace clang;
59using namespace clang::driver;
60using namespace llvm::opt;
61
62std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
63 if (!CanonicalPrefixes) {
64 SmallString<128> ExecutablePath(Argv0);
65 // Do a PATH lookup if Argv0 isn't a valid path.
66 if (!llvm::sys::fs::exists(ExecutablePath))
67 if (llvm::ErrorOr<std::string> P =
68 llvm::sys::findProgramByName(ExecutablePath))
69 ExecutablePath = *P;
70 return std::string(ExecutablePath);
71 }
72
73 // This just needs to be some symbol in the binary; C++ doesn't
74 // allow taking the address of ::main however.
75 void *P = (void*) (intptr_t) GetExecutablePath;
76 return llvm::sys::fs::getMainExecutable(Argv0, P);
77}
78
79static const char *GetStableCStr(llvm::StringSet<> &SavedStrings, StringRef S) {
80 return SavedStrings.insert(S).first->getKeyData();
81}
82
83extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
84 void *MainAddr);
85extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
86 void *MainAddr);
87
88static void insertTargetAndModeArgs(const ParsedClangName &NameParts,
89 SmallVectorImpl<const char *> &ArgVector,
90 llvm::StringSet<> &SavedStrings) {
91 // Put target and mode arguments at the start of argument list so that
92 // arguments specified in command line could override them. Avoid putting
93 // them at index 0, as an option like '-cc1' must remain the first.
94 int InsertionPoint = 0;
95 if (ArgVector.size() > 0)
96 ++InsertionPoint;
97
98 if (NameParts.DriverMode) {
99 // Add the mode flag to the arguments.
100 ArgVector.insert(ArgVector.begin() + InsertionPoint,
101 GetStableCStr(SavedStrings, NameParts.DriverMode));
102 }
103
104 if (NameParts.TargetIsValid) {
105 const char *arr[] = {"-target", GetStableCStr(SavedStrings,
106 NameParts.TargetPrefix)};
107 ArgVector.insert(ArgVector.begin() + InsertionPoint,
108 std::begin(arr), std::end(arr));
109 }
110}
111
112static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver,
113 SmallVectorImpl<const char *> &Opts) {
114 llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
115 // The first instance of '#' should be replaced with '=' in each option.
116 for (const char *Opt : Opts)
117 if (char *NumberSignPtr = const_cast<char *>(::strchr(Opt, '#')))
118 *NumberSignPtr = '=';
119}
120
121template <class T>
122static T checkEnvVar(const char *EnvOptSet, const char *EnvOptFile,
123 std::string &OptFile) {
124 const char *Str = ::getenv(EnvOptSet);
125 if (!Str)
126 return T{};
127
128 T OptVal = Str;
129 if (const char *Var = ::getenv(EnvOptFile))
130 OptFile = Var;
131 return OptVal;
132}
133
134static bool SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
135 TheDriver.CCPrintOptions =
136 checkEnvVar<bool>("CC_PRINT_OPTIONS", "CC_PRINT_OPTIONS_FILE",
137 TheDriver.CCPrintOptionsFilename);
138 if (checkEnvVar<bool>("CC_PRINT_HEADERS", "CC_PRINT_HEADERS_FILE",
139 TheDriver.CCPrintHeadersFilename)) {
140 TheDriver.CCPrintHeadersFormat = HIFMT_Textual;
141 TheDriver.CCPrintHeadersFiltering = HIFIL_None;
142 } else {
143 std::string EnvVar = checkEnvVar<std::string>(
144 "CC_PRINT_HEADERS_FORMAT", "CC_PRINT_HEADERS_FILE",
145 TheDriver.CCPrintHeadersFilename);
146 if (!EnvVar.empty()) {
147 TheDriver.CCPrintHeadersFormat =
148 stringToHeaderIncludeFormatKind(EnvVar.c_str());
149 if (!TheDriver.CCPrintHeadersFormat) {
150 TheDriver.Diag(clang::diag::err_drv_print_header_env_var)
151 << 0 << EnvVar;
152 return false;
153 }
154
155 const char *FilteringStr = ::getenv("CC_PRINT_HEADERS_FILTERING");
156 if (!FilteringStr) {
157 TheDriver.Diag(clang::diag::err_drv_print_header_env_var_invalid_format)
158 << EnvVar;
159 return false;
160 }
161 HeaderIncludeFilteringKind Filtering;
162 if (!stringToHeaderIncludeFiltering(FilteringStr, Filtering)) {
163 TheDriver.Diag(clang::diag::err_drv_print_header_env_var)
164 << 1 << FilteringStr;
165 return false;
166 }
167
168 if ((TheDriver.CCPrintHeadersFormat == HIFMT_Textual &&
169 Filtering != HIFIL_None) ||
170 (TheDriver.CCPrintHeadersFormat == HIFMT_JSON &&
171 Filtering == HIFIL_None)) {
172 TheDriver.Diag(clang::diag::err_drv_print_header_env_var_combination)
173 << EnvVar << FilteringStr;
174 return false;
175 }
176 TheDriver.CCPrintHeadersFiltering = Filtering;
177 }
178 }
179
180 TheDriver.CCLogDiagnostics =
181 checkEnvVar<bool>("CC_LOG_DIAGNOSTICS", "CC_LOG_DIAGNOSTICS_FILE",
182 TheDriver.CCLogDiagnosticsFilename);
183 TheDriver.CCPrintProcessStats =
184 checkEnvVar<bool>("CC_PRINT_PROC_STAT", "CC_PRINT_PROC_STAT_FILE",
185 TheDriver.CCPrintStatReportFilename);
186 TheDriver.CCPrintInternalStats =
187 checkEnvVar<bool>("CC_PRINT_INTERNAL_STAT", "CC_PRINT_INTERNAL_STAT_FILE",
188 TheDriver.CCPrintInternalStatReportFilename);
189
190 return true;
191}
192
193static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
194 const std::string &Path) {
195 // If the clang binary happens to be named cl.exe for compatibility reasons,
196 // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
197 StringRef ExeBasename(llvm::sys::path::stem(Path));
198 if (ExeBasename.equals_insensitive("cl"))
199 ExeBasename = "clang-cl";
200 DiagClient->setPrefix(std::string(ExeBasename));
201}
202
203static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV,
204 const llvm::ToolContext &ToolContext) {
205 // If we call the cc1 tool from the clangDriver library (through
206 // Driver::CC1Main), we need to clean up the options usage count. The options
207 // are currently global, and they might have been used previously by the
208 // driver.
209 llvm::cl::ResetAllOptionOccurrences();
210
211 llvm::BumpPtrAllocator A;
212 llvm::cl::ExpansionContext ECtx(A, llvm::cl::TokenizeGNUCommandLine);
213 if (llvm::Error Err = ECtx.expandResponseFiles(ArgV)) {
214 llvm::errs() << toString(std::move(Err)) << '\n';
215 return 1;
216 }
217 StringRef Tool = ArgV[1];
218 void *GetExecutablePathVP = (void *)(intptr_t)GetExecutablePath;
219 if (Tool == "-cc1")
220 return cc1_main(ArrayRef(ArgV).slice(1), ArgV[0], GetExecutablePathVP);
221 if (Tool == "-cc1as")
222 return cc1as_main(ArrayRef(ArgV).slice(2), ArgV[0], GetExecutablePathVP);
223 // Reject unknown tools.
224 llvm::errs()
225 << "error: unknown integrated tool '" << Tool << "'. "
226 << "Valid tools include '-cc1' and '-cc1as'.\n";
227 return 1;
228}
229
230static int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
231 noteBottomOfStack();
232 llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
233 " and include the crash backtrace, preprocessed "
234 "source, and associated run script.\n");
235 size_t argv_offset = (strcmp(Argv[1], "-cc1") == 0 || strcmp(Argv[1], "-cc1as") == 0) ? 0 : 1;
236 SmallVector<const char *, 256> Args(Argv + argv_offset, Argv + Argc);
237
238 if (llvm::sys::Process::FixupStandardFileDescriptors())
239 return 1;
240
241 llvm::InitializeAllTargets();
242
243 llvm::BumpPtrAllocator A;
244 llvm::StringSaver Saver(A);
245
246 const char *ProgName =
247 ToolContext.NeedsPrependArg ? ToolContext.PrependArg : ToolContext.Path;
248
249 bool ClangCLMode =
250 IsClangCL(getDriverMode(ProgName, llvm::ArrayRef(Args).slice(1)));
251
252 if (llvm::Error Err = expandResponseFiles(Args, ClangCLMode, A)) {
253 llvm::errs() << toString(std::move(Err)) << '\n';
254 return 1;
255 }
256
257 // Handle -cc1 integrated tools.
258 if (Args.size() >= 2 && StringRef(Args[1]).starts_with("-cc1"))
259 return ExecuteCC1Tool(Args, ToolContext);
260
261 // Handle options that need handling before the real command line parsing in
262 // Driver::BuildCompilation()
263 bool CanonicalPrefixes = true;
264 for (int i = 1, size = Args.size(); i < size; ++i) {
265 // Skip end-of-line response file markers
266 if (Args[i] == nullptr)
267 continue;
268 if (StringRef(Args[i]) == "-canonical-prefixes")
269 CanonicalPrefixes = true;
270 else if (StringRef(Args[i]) == "-no-canonical-prefixes")
271 CanonicalPrefixes = false;
272 }
273
274 // Handle CL and _CL_ which permits additional command line options to be
275 // prepended or appended.
276 if (ClangCLMode) {
277 // Arguments in "CL" are prepended.
278 std::optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
279 if (OptCL) {
280 SmallVector<const char *, 8> PrependedOpts;
281 getCLEnvVarOptions(*OptCL, Saver, PrependedOpts);
282
283 // Insert right after the program name to prepend to the argument list.
284 Args.insert(Args.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
285 }
286 // Arguments in "_CL_" are appended.
287 std::optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
288 if (Opt_CL_) {
289 SmallVector<const char *, 8> AppendedOpts;
290 getCLEnvVarOptions(*Opt_CL_, Saver, AppendedOpts);
291
292 // Insert at the end of the argument list to append.
293 Args.append(AppendedOpts.begin(), AppendedOpts.end());
294 }
295 }
296
297 llvm::StringSet<> SavedStrings;
298 // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
299 // scenes.
300 if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
301 // FIXME: Driver shouldn't take extra initial argument.
302 driver::applyOverrideOptions(Args, OverrideStr, SavedStrings,
303 "CCC_OVERRIDE_OPTIONS", &llvm::errs());
304 }
305
306 std::string Path = GetExecutablePath(ToolContext.Path, CanonicalPrefixes);
307
308 // Whether the cc1 tool should be called inside the current process, or if we
309 // should spawn a new clang subprocess (old behavior).
310 // Not having an additional process saves some execution time of Windows,
311 // and makes debugging and profiling easier.
312 bool UseNewCC1Process = CLANG_SPAWN_CC1;
313 for (const char *Arg : Args)
314 UseNewCC1Process = llvm::StringSwitch<bool>(Arg)
315 .Case("-fno-integrated-cc1", true)
316 .Case("-fintegrated-cc1", false)
317 .Default(UseNewCC1Process);
318
319 std::unique_ptr<DiagnosticOptions> DiagOpts = CreateAndPopulateDiagOpts(Args);
320 // Driver's diagnostics don't use suppression mappings, so don't bother
321 // parsing them. CC1 still receives full args, so this doesn't impact other
322 // actions.
323 DiagOpts->DiagnosticSuppressionMappingsFile.clear();
324
325 TextDiagnosticPrinter *DiagClient =
326 new TextDiagnosticPrinter(llvm::errs(), *DiagOpts);
327 FixupDiagPrefixExeName(DiagClient, ProgName);
328
329 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
330
331 DiagnosticsEngine Diags(DiagID, *DiagOpts, DiagClient);
332
333 if (!DiagOpts->DiagnosticSerializationFile.empty()) {
334 auto SerializedConsumer =
335 clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
336 *DiagOpts, /*MergeChildRecords=*/true);
337 Diags.setClient(new ChainedDiagnosticConsumer(
338 Diags.takeClient(), std::move(SerializedConsumer)));
339 }
340
341 auto VFS = llvm::vfs::getRealFileSystem();
342 ProcessWarningOptions(Diags, *DiagOpts, *VFS, /*ReportDiags=*/false);
343
344 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags,
345 /*Title=*/"clang LLVM compiler", VFS);
346 auto TargetAndMode = ToolChain::getTargetAndModeFromProgramName(ProgName);
347 TheDriver.setTargetAndMode(TargetAndMode);
348 // If -canonical-prefixes is set, GetExecutablePath will have resolved Path
349 // to the llvm driver binary, not clang. In this case, we need to use
350 // PrependArg which should be clang-*. Checking just CanonicalPrefixes is
351 // safe even in the normal case because PrependArg will be null so
352 // setPrependArg will be a no-op.
353 if (ToolContext.NeedsPrependArg || CanonicalPrefixes)
354 TheDriver.setPrependArg(ToolContext.PrependArg);
355
356 insertTargetAndModeArgs(TargetAndMode, Args, SavedStrings);
357
358 if (!SetBackdoorDriverOutputsFromEnvVars(TheDriver))
359 return 1;
360
361 auto ExecuteCC1WithContext =
362 [&ToolContext](SmallVectorImpl<const char *> &ArgV) {
363 return ExecuteCC1Tool(ArgV, ToolContext);
364 };
365 if (!UseNewCC1Process) {
366 TheDriver.CC1Main = ExecuteCC1WithContext;
367 // Ensure the CC1Command actually catches cc1 crashes
368 llvm::CrashRecoveryContext::Enable();
369 }
370
371 std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(Args));
372
373 Driver::ReproLevel ReproLevel = Driver::ReproLevel::OnCrash;
374 if (Arg *A = C->getArgs().getLastArg(options::OPT_gen_reproducer_eq)) {
375 auto Level =
376 llvm::StringSwitch<std::optional<Driver::ReproLevel>>(A->getValue())
377 .Case("off", Driver::ReproLevel::Off)
378 .Case("crash", Driver::ReproLevel::OnCrash)
379 .Case("error", Driver::ReproLevel::OnError)
380 .Case("always", Driver::ReproLevel::Always)
381 .Default(std::nullopt);
382 if (!Level) {
383 llvm::errs() << "Unknown value for " << A->getSpelling() << ": '"
384 << A->getValue() << "'\n";
385 return 1;
386 }
387 ReproLevel = *Level;
388 }
389 if (!!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
390 ReproLevel = Driver::ReproLevel::Always;
391
392 int Res = 1;
393 bool IsCrash = false;
394 Driver::CommandStatus CommandStatus = Driver::CommandStatus::Ok;
395 // Pretend the first command failed if ReproStatus is Always.
396 const Command *FailingCommand = nullptr;
397 if (!C->getJobs().empty())
398 FailingCommand = &*C->getJobs().begin();
399 if (C && !C->containsError()) {
400 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
401 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
402
403 for (const auto &P : FailingCommands) {
404 int CommandRes = P.first;
405 FailingCommand = P.second;
406 if (!Res)
407 Res = CommandRes;
408
409 // If result status is < 0, then the driver command signalled an error.
410 // If result status is 70, then the driver command reported a fatal error.
411 // On Windows, abort will return an exit code of 3. In these cases,
412 // generate additional diagnostic information if possible.
413 IsCrash = CommandRes < 0 || CommandRes == 70;
414#ifdef _WIN32
415 IsCrash |= CommandRes == 3;
416#endif
417#if LLVM_ON_UNIX
418 // When running in integrated-cc1 mode, the CrashRecoveryContext returns
419 // the same codes as if the program crashed. See section "Exit Status for
420 // Commands":
421 // https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xcu_chap02.html
422 IsCrash |= CommandRes > 128;
423#endif
424 CommandStatus =
425 IsCrash ? Driver::CommandStatus::Crash : Driver::CommandStatus::Error;
426 if (IsCrash)
427 break;
428 }
429 }
430
431 // Print the bug report message that would be printed if we did actually
432 // crash, but only if we're crashing due to FORCE_CLANG_DIAGNOSTICS_CRASH.
433 if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
434 llvm::dbgs() << llvm::getBugReportMsg();
435 if (FailingCommand != nullptr &&
436 TheDriver.maybeGenerateCompilationDiagnostics(CommandStatus, ReproLevel,
437 *C, *FailingCommand))
438 Res = 1;
439
440 Diags.getClient()->finish();
441
442 if (!UseNewCC1Process && IsCrash) {
443 // When crashing in -fintegrated-cc1 mode, bury the timer pointers, because
444 // the internal linked list might point to already released stack frames.
445 llvm::BuryPointer(llvm::TimerGroup::acquireTimerGlobals());
446 } else {
447 // If any timers were active but haven't been destroyed yet, print their
448 // results now. This happens in -disable-free mode.
449 llvm::TimerGroup::printAll(llvm::errs());
450 llvm::TimerGroup::clearAll();
451 }
452
453#ifdef _WIN32
454 // Exit status should not be negative on Win32, unless abnormal termination.
455 // Once abnormal termination was caught, negative status should not be
456 // propagated.
457 if (Res < 0)
458 Res = 1;
459#endif
460
461 // If we have multiple failing commands, we return the result of the first
462 // failing command.
463 return Res;
464}
465
466extern "C" int ZigClang_main(int, char **);
467int ZigClang_main(int argc, char **argv) {
468 return clang_main(argc, argv, {argv[0], nullptr, false});
469}