xref: /freebsd-src/contrib/llvm-project/clang/tools/driver/driver.cpp (revision 6528635081e60bf58faec65b39c0f819e50720fe)
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/Stack.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Compilation.h"
19 #include "clang/Driver/DriverDiagnostic.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/ToolChain.h"
22 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
23 #include "clang/Frontend/CompilerInvocation.h"
24 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
25 #include "clang/Frontend/TextDiagnosticPrinter.h"
26 #include "clang/Frontend/Utils.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/OptTable.h"
32 #include "llvm/Option/Option.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/CrashRecoveryContext.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Host.h"
38 #include "llvm/Support/InitLLVM.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Process.h"
41 #include "llvm/Support/Program.h"
42 #include "llvm/Support/Regex.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/StringSaver.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <memory>
49 #include <set>
50 #include <system_error>
51 using namespace clang;
52 using namespace clang::driver;
53 using namespace llvm::opt;
54 
55 std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
56   if (!CanonicalPrefixes) {
57     SmallString<128> ExecutablePath(Argv0);
58     // Do a PATH lookup if Argv0 isn't a valid path.
59     if (!llvm::sys::fs::exists(ExecutablePath))
60       if (llvm::ErrorOr<std::string> P =
61               llvm::sys::findProgramByName(ExecutablePath))
62         ExecutablePath = *P;
63     return ExecutablePath.str();
64   }
65 
66   // This just needs to be some symbol in the binary; C++ doesn't
67   // allow taking the address of ::main however.
68   void *P = (void*) (intptr_t) GetExecutablePath;
69   return llvm::sys::fs::getMainExecutable(Argv0, P);
70 }
71 
72 static const char *GetStableCStr(std::set<std::string> &SavedStrings,
73                                  StringRef S) {
74   return SavedStrings.insert(S).first->c_str();
75 }
76 
77 /// ApplyQAOverride - Apply a list of edits to the input argument lists.
78 ///
79 /// The input string is a space separate list of edits to perform,
80 /// they are applied in order to the input argument lists. Edits
81 /// should be one of the following forms:
82 ///
83 ///  '#': Silence information about the changes to the command line arguments.
84 ///
85 ///  '^': Add FOO as a new argument at the beginning of the command line.
86 ///
87 ///  '+': Add FOO as a new argument at the end of the command line.
88 ///
89 ///  's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
90 ///  line.
91 ///
92 ///  'xOPTION': Removes all instances of the literal argument OPTION.
93 ///
94 ///  'XOPTION': Removes all instances of the literal argument OPTION,
95 ///  and the following argument.
96 ///
97 ///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
98 ///  at the end of the command line.
99 ///
100 /// \param OS - The stream to write edit information to.
101 /// \param Args - The vector of command line arguments.
102 /// \param Edit - The override command to perform.
103 /// \param SavedStrings - Set to use for storing string representations.
104 static void ApplyOneQAOverride(raw_ostream &OS,
105                                SmallVectorImpl<const char*> &Args,
106                                StringRef Edit,
107                                std::set<std::string> &SavedStrings) {
108   // This does not need to be efficient.
109 
110   if (Edit[0] == '^') {
111     const char *Str =
112       GetStableCStr(SavedStrings, Edit.substr(1));
113     OS << "### Adding argument " << Str << " at beginning\n";
114     Args.insert(Args.begin() + 1, Str);
115   } else if (Edit[0] == '+') {
116     const char *Str =
117       GetStableCStr(SavedStrings, Edit.substr(1));
118     OS << "### Adding argument " << Str << " at end\n";
119     Args.push_back(Str);
120   } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
121              Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
122     StringRef MatchPattern = Edit.substr(2).split('/').first;
123     StringRef ReplPattern = Edit.substr(2).split('/').second;
124     ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
125 
126     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
127       // Ignore end-of-line response file markers
128       if (Args[i] == nullptr)
129         continue;
130       std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
131 
132       if (Repl != Args[i]) {
133         OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
134         Args[i] = GetStableCStr(SavedStrings, Repl);
135       }
136     }
137   } else if (Edit[0] == 'x' || Edit[0] == 'X') {
138     auto Option = Edit.substr(1);
139     for (unsigned i = 1; i < Args.size();) {
140       if (Option == Args[i]) {
141         OS << "### Deleting argument " << Args[i] << '\n';
142         Args.erase(Args.begin() + i);
143         if (Edit[0] == 'X') {
144           if (i < Args.size()) {
145             OS << "### Deleting argument " << Args[i] << '\n';
146             Args.erase(Args.begin() + i);
147           } else
148             OS << "### Invalid X edit, end of command line!\n";
149         }
150       } else
151         ++i;
152     }
153   } else if (Edit[0] == 'O') {
154     for (unsigned i = 1; i < Args.size();) {
155       const char *A = Args[i];
156       // Ignore end-of-line response file markers
157       if (A == nullptr)
158         continue;
159       if (A[0] == '-' && A[1] == 'O' &&
160           (A[2] == '\0' ||
161            (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
162                              ('0' <= A[2] && A[2] <= '9'))))) {
163         OS << "### Deleting argument " << Args[i] << '\n';
164         Args.erase(Args.begin() + i);
165       } else
166         ++i;
167     }
168     OS << "### Adding argument " << Edit << " at end\n";
169     Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
170   } else {
171     OS << "### Unrecognized edit: " << Edit << "\n";
172   }
173 }
174 
175 /// ApplyQAOverride - Apply a comma separate list of edits to the
176 /// input argument lists. See ApplyOneQAOverride.
177 static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
178                             const char *OverrideStr,
179                             std::set<std::string> &SavedStrings) {
180   raw_ostream *OS = &llvm::errs();
181 
182   if (OverrideStr[0] == '#') {
183     ++OverrideStr;
184     OS = &llvm::nulls();
185   }
186 
187   *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
188 
189   // This does not need to be efficient.
190 
191   const char *S = OverrideStr;
192   while (*S) {
193     const char *End = ::strchr(S, ' ');
194     if (!End)
195       End = S + strlen(S);
196     if (End != S)
197       ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
198     S = End;
199     if (*S != '\0')
200       ++S;
201   }
202 }
203 
204 extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
205                     void *MainAddr);
206 extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
207                       void *MainAddr);
208 extern int cc1gen_reproducer_main(ArrayRef<const char *> Argv,
209                                   const char *Argv0, void *MainAddr);
210 
211 static void insertTargetAndModeArgs(const ParsedClangName &NameParts,
212                                     SmallVectorImpl<const char *> &ArgVector,
213                                     std::set<std::string> &SavedStrings) {
214   // Put target and mode arguments at the start of argument list so that
215   // arguments specified in command line could override them. Avoid putting
216   // them at index 0, as an option like '-cc1' must remain the first.
217   int InsertionPoint = 0;
218   if (ArgVector.size() > 0)
219     ++InsertionPoint;
220 
221   if (NameParts.DriverMode) {
222     // Add the mode flag to the arguments.
223     ArgVector.insert(ArgVector.begin() + InsertionPoint,
224                      GetStableCStr(SavedStrings, NameParts.DriverMode));
225   }
226 
227   if (NameParts.TargetIsValid) {
228     const char *arr[] = {"-target", GetStableCStr(SavedStrings,
229                                                   NameParts.TargetPrefix)};
230     ArgVector.insert(ArgVector.begin() + InsertionPoint,
231                      std::begin(arr), std::end(arr));
232   }
233 }
234 
235 static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver,
236                                SmallVectorImpl<const char *> &Opts) {
237   llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
238   // The first instance of '#' should be replaced with '=' in each option.
239   for (const char *Opt : Opts)
240     if (char *NumberSignPtr = const_cast<char *>(::strchr(Opt, '#')))
241       *NumberSignPtr = '=';
242 }
243 
244 static int ExecuteCC1Tool(ArrayRef<const char *> argv);
245 
246 static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
247   // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
248   TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
249   if (TheDriver.CCPrintOptions)
250     TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
251 
252   // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
253   TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
254   if (TheDriver.CCPrintHeaders)
255     TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
256 
257   // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
258   TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
259   if (TheDriver.CCLogDiagnostics)
260     TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
261 }
262 
263 static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
264                                    const std::string &Path) {
265   // If the clang binary happens to be named cl.exe for compatibility reasons,
266   // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
267   StringRef ExeBasename(llvm::sys::path::stem(Path));
268   if (ExeBasename.equals_lower("cl"))
269     ExeBasename = "clang-cl";
270   DiagClient->setPrefix(ExeBasename);
271 }
272 
273 // This lets us create the DiagnosticsEngine with a properly-filled-out
274 // DiagnosticOptions instance.
275 static DiagnosticOptions *
276 CreateAndPopulateDiagOpts(ArrayRef<const char *> argv, bool &UseNewCC1Process) {
277   auto *DiagOpts = new DiagnosticOptions;
278   unsigned MissingArgIndex, MissingArgCount;
279   InputArgList Args = getDriverOptTable().ParseArgs(
280       argv.slice(1), MissingArgIndex, MissingArgCount);
281   // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
282   // Any errors that would be diagnosed here will also be diagnosed later,
283   // when the DiagnosticsEngine actually exists.
284   (void)ParseDiagnosticArgs(*DiagOpts, Args);
285 
286   UseNewCC1Process =
287       Args.hasFlag(clang::driver::options::OPT_fno_integrated_cc1,
288                    clang::driver::options::OPT_fintegrated_cc1,
289                    /*Default=*/CLANG_SPAWN_CC1);
290 
291   return DiagOpts;
292 }
293 
294 static void SetInstallDir(SmallVectorImpl<const char *> &argv,
295                           Driver &TheDriver, bool CanonicalPrefixes) {
296   // Attempt to find the original path used to invoke the driver, to determine
297   // the installed path. We do this manually, because we want to support that
298   // path being a symlink.
299   SmallString<128> InstalledPath(argv[0]);
300 
301   // Do a PATH lookup, if there are no directory components.
302   if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
303     if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
304             llvm::sys::path::filename(InstalledPath.str())))
305       InstalledPath = *Tmp;
306 
307   // FIXME: We don't actually canonicalize this, we just make it absolute.
308   if (CanonicalPrefixes)
309     llvm::sys::fs::make_absolute(InstalledPath);
310 
311   StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
312   if (llvm::sys::fs::exists(InstalledPathParent))
313     TheDriver.setInstalledDir(InstalledPathParent);
314 }
315 
316 static int ExecuteCC1Tool(ArrayRef<const char *> argv) {
317   // If we call the cc1 tool from the clangDriver library (through
318   // Driver::CC1Main), we need to clean up the options usage count. The options
319   // are currently global, and they might have been used previously by the
320   // driver.
321   llvm::cl::ResetAllOptionOccurrences();
322   StringRef Tool = argv[1];
323   void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
324   if (Tool == "-cc1")
325     return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
326   if (Tool == "-cc1as")
327     return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP);
328   if (Tool == "-cc1gen-reproducer")
329     return cc1gen_reproducer_main(argv.slice(2), argv[0], GetExecutablePathVP);
330 
331   // Reject unknown tools.
332   llvm::errs() << "error: unknown integrated tool '" << Tool << "'. "
333                << "Valid tools include '-cc1' and '-cc1as'.\n";
334   return 1;
335 }
336 
337 int main(int argc_, const char **argv_) {
338   noteBottomOfStack();
339   llvm::InitLLVM X(argc_, argv_);
340   SmallVector<const char *, 256> argv(argv_, argv_ + argc_);
341 
342   if (llvm::sys::Process::FixupStandardFileDescriptors())
343     return 1;
344 
345   llvm::InitializeAllTargets();
346   auto TargetAndMode = ToolChain::getTargetAndModeFromProgramName(argv[0]);
347 
348   llvm::BumpPtrAllocator A;
349   llvm::StringSaver Saver(A);
350 
351   // Parse response files using the GNU syntax, unless we're in CL mode. There
352   // are two ways to put clang in CL compatibility mode: argv[0] is either
353   // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
354   // command line parsing can't happen until after response file parsing, so we
355   // have to manually search for a --driver-mode=cl argument the hard way.
356   // Finally, our -cc1 tools don't care which tokenization mode we use because
357   // response files written by clang will tokenize the same way in either mode.
358   bool ClangCLMode = false;
359   if (StringRef(TargetAndMode.DriverMode).equals("--driver-mode=cl") ||
360       llvm::find_if(argv, [](const char *F) {
361         return F && strcmp(F, "--driver-mode=cl") == 0;
362       }) != argv.end()) {
363     ClangCLMode = true;
364   }
365   enum { Default, POSIX, Windows } RSPQuoting = Default;
366   for (const char *F : argv) {
367     if (strcmp(F, "--rsp-quoting=posix") == 0)
368       RSPQuoting = POSIX;
369     else if (strcmp(F, "--rsp-quoting=windows") == 0)
370       RSPQuoting = Windows;
371   }
372 
373   // Determines whether we want nullptr markers in argv to indicate response
374   // files end-of-lines. We only use this for the /LINK driver argument with
375   // clang-cl.exe on Windows.
376   bool MarkEOLs = ClangCLMode;
377 
378   llvm::cl::TokenizerCallback Tokenizer;
379   if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode))
380     Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
381   else
382     Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
383 
384   if (MarkEOLs && argv.size() > 1 && StringRef(argv[1]).startswith("-cc1"))
385     MarkEOLs = false;
386   llvm::cl::ExpandResponseFiles(Saver, Tokenizer, argv, MarkEOLs);
387 
388   // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
389   // file.
390   auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
391                                [](const char *A) { return A != nullptr; });
392   if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
393     // If -cc1 came from a response file, remove the EOL sentinels.
394     if (MarkEOLs) {
395       auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
396       argv.resize(newEnd - argv.begin());
397     }
398     return ExecuteCC1Tool(argv);
399   }
400 
401   // Handle options that need handling before the real command line parsing in
402   // Driver::BuildCompilation()
403   bool CanonicalPrefixes = true;
404   for (int i = 1, size = argv.size(); i < size; ++i) {
405     // Skip end-of-line response file markers
406     if (argv[i] == nullptr)
407       continue;
408     if (StringRef(argv[i]) == "-no-canonical-prefixes") {
409       CanonicalPrefixes = false;
410       break;
411     }
412   }
413 
414   // Handle CL and _CL_ which permits additional command line options to be
415   // prepended or appended.
416   if (ClangCLMode) {
417     // Arguments in "CL" are prepended.
418     llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
419     if (OptCL.hasValue()) {
420       SmallVector<const char *, 8> PrependedOpts;
421       getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts);
422 
423       // Insert right after the program name to prepend to the argument list.
424       argv.insert(argv.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
425     }
426     // Arguments in "_CL_" are appended.
427     llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
428     if (Opt_CL_.hasValue()) {
429       SmallVector<const char *, 8> AppendedOpts;
430       getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts);
431 
432       // Insert at the end of the argument list to append.
433       argv.append(AppendedOpts.begin(), AppendedOpts.end());
434     }
435   }
436 
437   std::set<std::string> SavedStrings;
438   // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
439   // scenes.
440   if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
441     // FIXME: Driver shouldn't take extra initial argument.
442     ApplyQAOverride(argv, OverrideStr, SavedStrings);
443   }
444 
445   std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
446 
447   // Whether the cc1 tool should be called inside the current process, or if we
448   // should spawn a new clang subprocess (old behavior).
449   // Not having an additional process saves some execution time of Windows,
450   // and makes debugging and profiling easier.
451   bool UseNewCC1Process;
452 
453   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
454       CreateAndPopulateDiagOpts(argv, UseNewCC1Process);
455 
456   TextDiagnosticPrinter *DiagClient
457     = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
458   FixupDiagPrefixExeName(DiagClient, Path);
459 
460   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
461 
462   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
463 
464   if (!DiagOpts->DiagnosticSerializationFile.empty()) {
465     auto SerializedConsumer =
466         clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
467                                         &*DiagOpts, /*MergeChildRecords=*/true);
468     Diags.setClient(new ChainedDiagnosticConsumer(
469         Diags.takeClient(), std::move(SerializedConsumer)));
470   }
471 
472   ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
473 
474   Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
475   SetInstallDir(argv, TheDriver, CanonicalPrefixes);
476   TheDriver.setTargetAndMode(TargetAndMode);
477 
478   insertTargetAndModeArgs(TargetAndMode, argv, SavedStrings);
479 
480   SetBackdoorDriverOutputsFromEnvVars(TheDriver);
481 
482   if (!UseNewCC1Process) {
483     TheDriver.CC1Main = &ExecuteCC1Tool;
484     // Ensure the CC1Command actually catches cc1 crashes
485     llvm::CrashRecoveryContext::Enable();
486   }
487 
488   std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
489   int Res = 1;
490   if (C && !C->containsError()) {
491     SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
492     Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
493 
494     // Force a crash to test the diagnostics.
495     if (TheDriver.GenReproducer) {
496       Diags.Report(diag::err_drv_force_crash)
497         << !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH");
498 
499       // Pretend that every command failed.
500       FailingCommands.clear();
501       for (const auto &J : C->getJobs())
502         if (const Command *C = dyn_cast<Command>(&J))
503           FailingCommands.push_back(std::make_pair(-1, C));
504     }
505 
506     for (const auto &P : FailingCommands) {
507       int CommandRes = P.first;
508       const Command *FailingCommand = P.second;
509       if (!Res)
510         Res = CommandRes;
511 
512       // If result status is < 0, then the driver command signalled an error.
513       // If result status is 70, then the driver command reported a fatal error.
514       // On Windows, abort will return an exit code of 3.  In these cases,
515       // generate additional diagnostic information if possible.
516       bool DiagnoseCrash = CommandRes < 0 || CommandRes == 70;
517 #ifdef _WIN32
518       DiagnoseCrash |= CommandRes == 3;
519 #endif
520       if (DiagnoseCrash) {
521         TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
522         break;
523       }
524     }
525   }
526 
527   Diags.getClient()->finish();
528 
529   // If any timers were active but haven't been destroyed yet, print their
530   // results now.  This happens in -disable-free mode.
531   llvm::TimerGroup::printAll(llvm::errs());
532   llvm::TimerGroup::clearAll();
533 
534 #ifdef _WIN32
535   // Exit status should not be negative on Win32, unless abnormal termination.
536   // Once abnormal termination was caught, negative status should not be
537   // propagated.
538   if (Res < 0)
539     Res = 1;
540 #endif
541 
542   // If we have multiple failing commands, we return the result of the first
543   // failing command.
544   return Res;
545 }
546