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