Coverage Report

Created: 2020-09-19 12:23

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Driver/Job.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Job.cpp - Command to Execute ---------------------------------------===//
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
#include "clang/Driver/Job.h"
10
#include "InputInfo.h"
11
#include "clang/Basic/LLVM.h"
12
#include "clang/Driver/Driver.h"
13
#include "clang/Driver/DriverDiagnostic.h"
14
#include "clang/Driver/Tool.h"
15
#include "clang/Driver/ToolChain.h"
16
#include "llvm/ADT/ArrayRef.h"
17
#include "llvm/ADT/SmallString.h"
18
#include "llvm/ADT/SmallVector.h"
19
#include "llvm/ADT/StringRef.h"
20
#include "llvm/ADT/StringSet.h"
21
#include "llvm/ADT/StringSwitch.h"
22
#include "llvm/Support/CrashRecoveryContext.h"
23
#include "llvm/Support/FileSystem.h"
24
#include "llvm/Support/Path.h"
25
#include "llvm/Support/PrettyStackTrace.h"
26
#include "llvm/Support/Program.h"
27
#include "llvm/Support/raw_ostream.h"
28
#include <algorithm>
29
#include <cassert>
30
#include <cstddef>
31
#include <string>
32
#include <system_error>
33
#include <utility>
34
35
using namespace clang;
36
using namespace driver;
37
38
Command::Command(const Action &Source, const Tool &Creator,
39
                 ResponseFileSupport ResponseSupport, const char *Executable,
40
                 const llvm::opt::ArgStringList &Arguments,
41
                 ArrayRef<InputInfo> Inputs)
42
    : Source(Source), Creator(Creator), ResponseSupport(ResponseSupport),
43
51.2k
      Executable(Executable), Arguments(Arguments) {
44
51.2k
  for (const auto &II : Inputs)
45
53.4k
    if (II.isFilename())
46
52.2k
      InputFilenames.push_back(II.getFilename());
47
51.2k
}
48
49
/// Check if the compiler flag in question should be skipped when
50
/// emitting a reproducer. Also track how many arguments it has and if the
51
/// option is some kind of include path.
52
static bool skipArgs(const char *Flag, bool HaveCrashVFS, int &SkipNum,
53
1.53k
                     bool &IsInclude) {
54
1.53k
  SkipNum = 2;
55
  // These flags are all of the form -Flag <Arg> and are treated as two
56
  // arguments.  Therefore, we need to skip the flag and the next argument.
57
1.53k
  bool ShouldSkip = llvm::StringSwitch<bool>(Flag)
58
1.53k
    .Cases("-MF", "-MT", "-MQ", "-serialize-diagnostic-file", true)
59
1.53k
    .Cases("-o", "-dependency-file", true)
60
1.53k
    .Cases("-fdebug-compilation-dir", "-diagnostic-log-file", true)
61
1.53k
    .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
62
1.53k
    .Default(false);
63
1.53k
  if (ShouldSkip)
64
48
    return true;
65
1.48k
66
  // Some include flags shouldn't be skipped if we have a crash VFS
67
1.48k
  IsInclude = llvm::StringSwitch<bool>(Flag)
68
1.48k
    .Cases("-include", "-header-include-file", true)
69
1.48k
    .Cases("-idirafter", "-internal-isystem", "-iwithprefix", true)
70
1.48k
    .Cases("-internal-externc-isystem", "-iprefix", true)
71
1.48k
    .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
72
1.48k
    .Cases("-isysroot", "-I", "-F", "-resource-dir", true)
73
1.48k
    .Cases("-iframework", "-include-pch", true)
74
1.48k
    .Default(false);
75
1.48k
  if (IsInclude)
76
172
    return !HaveCrashVFS;
77
1.31k
78
  // The remaining flags are treated as a single argument.
79
1.31k
80
  // These flags are all of the form -Flag and have no second argument.
81
1.31k
  ShouldSkip = llvm::StringSwitch<bool>(Flag)
82
1.31k
    .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
83
1.31k
    .Case("-MMD", true)
84
1.31k
    .Default(false);
85
1.31k
86
  // Match found.
87
1.31k
  SkipNum = 1;
88
1.31k
  if (ShouldSkip)
89
0
    return true;
90
1.31k
91
  // These flags are treated as a single argument (e.g., -F<Dir>).
92
1.31k
  StringRef FlagRef(Flag);
93
1.31k
  IsInclude = FlagRef.startswith("-F") || 
FlagRef.startswith("-I")1.31k
;
94
1.31k
  if (IsInclude)
95
7
    return !HaveCrashVFS;
96
1.31k
  if (FlagRef.startswith("-fmodules-cache-path="))
97
14
    return true;
98
1.29k
99
1.29k
  SkipNum = 0;
100
1.29k
  return false;
101
1.29k
}
102
103
1
void Command::writeResponseFile(raw_ostream &OS) const {
104
  // In a file list, we only write the set of inputs to the response file
105
1
  if (ResponseSupport.ResponseKind == ResponseFileSupport::RF_FileList) {
106
0
    for (const auto *Arg : InputFileList) {
107
0
      OS << Arg << '\n';
108
0
    }
109
0
    return;
110
0
  }
111
1
112
  // In regular response files, we send all arguments to the response file.
113
  // Wrapping all arguments in double quotes ensures that both Unix tools and
114
  // Windows tools understand the response file.
115
600k
  
for (const auto *Arg : Arguments)1
{
116
600k
    OS << '"';
117
600k
118
2.40M
    for (; *Arg != '\0'; 
Arg++1.80M
) {
119
1.80M
      if (*Arg == '\"' || *Arg == '\\') {
120
0
        OS << '\\';
121
0
      }
122
1.80M
      OS << *Arg;
123
1.80M
    }
124
600k
125
600k
    OS << "\" ";
126
600k
  }
127
1
}
128
129
void Command::buildArgvForResponseFile(
130
1
    llvm::SmallVectorImpl<const char *> &Out) const {
131
  // When not a file list, all arguments are sent to the response file.
132
  // This leaves us to set the argv to a single parameter, requesting the tool
133
  // to read the response file.
134
1
  if (ResponseSupport.ResponseKind != ResponseFileSupport::RF_FileList) {
135
1
    Out.push_back(Executable);
136
1
    Out.push_back(ResponseFileFlag.c_str());
137
1
    return;
138
1
  }
139
0
140
0
  llvm::StringSet<> Inputs;
141
0
  for (const auto *InputName : InputFileList)
142
0
    Inputs.insert(InputName);
143
0
  Out.push_back(Executable);
144
  // In a file list, build args vector ignoring parameters that will go in the
145
  // response file (elements of the InputFileList vector)
146
0
  bool FirstInput = true;
147
0
  for (const auto *Arg : Arguments) {
148
0
    if (Inputs.count(Arg) == 0) {
149
0
      Out.push_back(Arg);
150
0
    } else if (FirstInput) {
151
0
      FirstInput = false;
152
0
      Out.push_back(ResponseSupport.ResponseFlag);
153
0
      Out.push_back(ResponseFile);
154
0
    }
155
0
  }
156
0
}
157
158
/// Rewrite relative include-like flag paths to absolute ones.
159
static void
160
rewriteIncludes(const llvm::ArrayRef<const char *> &Args, size_t Idx,
161
                size_t NumArgs,
162
69
                llvm::SmallVectorImpl<llvm::SmallString<128>> &IncFlags) {
163
69
  using namespace llvm;
164
69
  using namespace sys;
165
69
166
69
  auto getAbsPath = [](StringRef InInc, SmallVectorImpl<char> &OutInc) -> bool {
167
69
    if (path::is_absolute(InInc)) // Nothing to do here...
168
68
      return false;
169
1
    std::error_code EC = fs::current_path(OutInc);
170
1
    if (EC)
171
0
      return false;
172
1
    path::append(OutInc, InInc);
173
1
    return true;
174
1
  };
175
69
176
69
  SmallString<128> NewInc;
177
69
  if (NumArgs == 1) {
178
2
    StringRef FlagRef(Args[Idx + NumArgs - 1]);
179
2
    assert((FlagRef.startswith("-F") || FlagRef.startswith("-I")) &&
180
2
            "Expecting -I or -F");
181
2
    StringRef Inc = FlagRef.slice(2, StringRef::npos);
182
2
    if (getAbsPath(Inc, NewInc)) {
183
0
      SmallString<128> NewArg(FlagRef.slice(0, 2));
184
0
      NewArg += NewInc;
185
0
      IncFlags.push_back(std::move(NewArg));
186
0
    }
187
2
    return;
188
2
  }
189
67
190
67
  assert(NumArgs == 2 && "Not expecting more than two arguments");
191
67
  StringRef Inc(Args[Idx + NumArgs - 1]);
192
67
  if (!getAbsPath(Inc, NewInc))
193
66
    return;
194
1
  IncFlags.push_back(SmallString<128>(Args[Idx]));
195
1
  IncFlags.push_back(std::move(NewInc));
196
1
}
197
198
void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
199
13.6k
                    CrashReportInfo *CrashInfo) const {
200
  // Always quote the exe.
201
13.6k
  OS << ' ';
202
13.6k
  llvm::sys::printArg(OS, Executable, /*Quote=*/true);
203
13.6k
204
13.6k
  ArrayRef<const char *> Args = Arguments;
205
13.6k
  SmallVector<const char *, 128> ArgsRespFile;
206
13.6k
  if (ResponseFile != nullptr) {
207
1
    buildArgvForResponseFile(ArgsRespFile);
208
1
    Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
209
1
  }
210
13.6k
211
13.6k
  bool HaveCrashVFS = CrashInfo && 
!CrashInfo->VFSPath.empty()27
;
212
573k
  for (size_t i = 0, e = Args.size(); i < e; 
++i560k
) {
213
560k
    const char *const Arg = Args[i];
214
560k
215
560k
    if (CrashInfo) {
216
1.53k
      int NumArgs = 0;
217
1.53k
      bool IsInclude = false;
218
1.53k
      if (skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) {
219
172
        i += NumArgs - 1;
220
172
        continue;
221
172
      }
222
1.36k
223
      // Relative includes need to be expanded to absolute paths.
224
1.36k
      if (HaveCrashVFS && 
IsInclude789
) {
225
69
        SmallVector<SmallString<128>, 2> NewIncFlags;
226
69
        rewriteIncludes(Args, i, NumArgs, NewIncFlags);
227
69
        if (!NewIncFlags.empty()) {
228
2
          for (auto &F : NewIncFlags) {
229
2
            OS << ' ';
230
2
            llvm::sys::printArg(OS, F.c_str(), Quote);
231
2
          }
232
1
          i += NumArgs - 1;
233
1
          continue;
234
1
        }
235
1.36k
      }
236
1.36k
237
1.36k
      auto Found = llvm::find_if(InputFilenames,
238
1.36k
                                 [&Arg](StringRef IF) { return IF == Arg; });
239
1.36k
      if (Found != InputFilenames.end() &&
240
27
          (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
241
        // Replace the input file name with the crashinfo's file name.
242
27
        OS << ' ';
243
27
        StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
244
27
        llvm::sys::printArg(OS, ShortName.str(), Quote);
245
27
        continue;
246
27
      }
247
559k
    }
248
559k
249
559k
    OS << ' ';
250
559k
    llvm::sys::printArg(OS, Arg, Quote);
251
559k
  }
252
13.6k
253
13.6k
  if (CrashInfo && 
HaveCrashVFS27
) {
254
14
    OS << ' ';
255
14
    llvm::sys::printArg(OS, "-ivfsoverlay", Quote);
256
14
    OS << ' ';
257
14
    llvm::sys::printArg(OS, CrashInfo->VFSPath.str(), Quote);
258
14
259
    // The leftover modules from the crash are stored in
260
    //  <name>.cache/vfs/modules
261
    // Leave it untouched for pcm inspection and provide a clean/empty dir
262
    // path to contain the future generated module cache:
263
    //  <name>.cache/vfs/repro-modules
264
14
    SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
265
14
        llvm::sys::path::parent_path(CrashInfo->VFSPath));
266
14
    llvm::sys::path::append(RelModCacheDir, "repro-modules");
267
14
268
14
    std::string ModCachePath = "-fmodules-cache-path=";
269
14
    ModCachePath.append(RelModCacheDir.c_str());
270
14
271
14
    OS << ' ';
272
14
    llvm::sys::printArg(OS, ModCachePath, Quote);
273
14
  }
274
13.6k
275
13.6k
  if (ResponseFile != nullptr) {
276
1
    OS << "\n Arguments passed via response file:\n";
277
1
    writeResponseFile(OS);
278
    // Avoiding duplicated newline terminator, since FileLists are
279
    // newline-separated.
280
1
    if (ResponseSupport.ResponseKind != ResponseFileSupport::RF_FileList)
281
1
      OS << "\n";
282
1
    OS << " (end of response file)";
283
1
  }
284
13.6k
285
13.6k
  OS << Terminator;
286
13.6k
}
287
288
1
void Command::setResponseFile(const char *FileName) {
289
1
  ResponseFile = FileName;
290
1
  ResponseFileFlag = ResponseSupport.ResponseFlag;
291
1
  ResponseFileFlag += FileName;
292
1
}
293
294
0
void Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
295
0
  Environment.reserve(NewEnvironment.size() + 1);
296
0
  Environment.assign(NewEnvironment.begin(), NewEnvironment.end());
297
0
  Environment.push_back(nullptr);
298
0
}
299
300
11.0k
void Command::PrintFileNames() const {
301
11.0k
  if (PrintInputFilenames) {
302
4
    for (const char *Arg : InputFilenames)
303
4
      llvm::outs() << llvm::sys::path::filename(Arg) << "\n";
304
4
    llvm::outs().flush();
305
4
  }
306
11.0k
}
307
308
int Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
309
3.17k
                     std::string *ErrMsg, bool *ExecutionFailed) const {
310
3.17k
  PrintFileNames();
311
3.17k
312
3.17k
  SmallVector<const char *, 128> Argv;
313
3.17k
  if (ResponseFile == nullptr) {
314
3.17k
    Argv.push_back(Executable);
315
3.17k
    Argv.append(Arguments.begin(), Arguments.end());
316
3.17k
    Argv.push_back(nullptr);
317
0
  } else {
318
    // If the command is too large, we need to put arguments in a response file.
319
0
    std::string RespContents;
320
0
    llvm::raw_string_ostream SS(RespContents);
321
0
322
    // Write file contents and build the Argv vector
323
0
    writeResponseFile(SS);
324
0
    buildArgvForResponseFile(Argv);
325
0
    Argv.push_back(nullptr);
326
0
    SS.flush();
327
0
328
    // Save the response file in the appropriate encoding
329
0
    if (std::error_code EC = writeFileWithEncoding(
330
0
            ResponseFile, RespContents, ResponseSupport.ResponseEncoding)) {
331
0
      if (ErrMsg)
332
0
        *ErrMsg = EC.message();
333
0
      if (ExecutionFailed)
334
0
        *ExecutionFailed = true;
335
      // Return -1 by convention (see llvm/include/llvm/Support/Program.h) to
336
      // indicate the requested executable cannot be started.
337
0
      return -1;
338
0
    }
339
3.17k
  }
340
3.17k
341
3.17k
  Optional<ArrayRef<StringRef>> Env;
342
3.17k
  std::vector<StringRef> ArgvVectorStorage;
343
3.17k
  if (!Environment.empty()) {
344
0
    assert(Environment.back() == nullptr &&
345
0
           "Environment vector should be null-terminated by now");
346
0
    ArgvVectorStorage = llvm::toStringRefArray(Environment.data());
347
0
    Env = makeArrayRef(ArgvVectorStorage);
348
0
  }
349
3.17k
350
3.17k
  auto Args = llvm::toStringRefArray(Argv.data());
351
3.17k
  return llvm::sys::ExecuteAndWait(Executable, Args, Env, Redirects,
352
3.17k
                                   /*secondsToWait*/ 0,
353
3.17k
                                   /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
354
3.17k
}
355
356
CC1Command::CC1Command(const Action &Source, const Tool &Creator,
357
                       ResponseFileSupport ResponseSupport,
358
                       const char *Executable,
359
                       const llvm::opt::ArgStringList &Arguments,
360
                       ArrayRef<InputInfo> Inputs)
361
16.3k
    : Command(Source, Creator, ResponseSupport, Executable, Arguments, Inputs) {
362
16.3k
  InProcess = true;
363
16.3k
}
364
365
void CC1Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
366
8.20k
                       CrashReportInfo *CrashInfo) const {
367
8.20k
  if (InProcess)
368
3.51k
    OS << " (in-process)\n";
369
8.20k
  Command::Print(OS, Terminator, Quote, CrashInfo);
370
8.20k
}
371
372
int CC1Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
373
8.10k
                        std::string *ErrMsg, bool *ExecutionFailed) const {
374
  // FIXME: Currently, if there're more than one job, we disable
375
  // -fintegrate-cc1. If we're no longer a integrated-cc1 job, fallback to
376
  // out-of-process execution. See discussion in https://reviews.llvm.org/D74447
377
8.10k
  if (!InProcess)
378
248
    return Command::Execute(Redirects, ErrMsg, ExecutionFailed);
379
7.86k
380
7.86k
  PrintFileNames();
381
7.86k
382
7.86k
  SmallVector<const char *, 128> Argv;
383
7.86k
  Argv.push_back(getExecutable());
384
7.86k
  Argv.append(getArguments().begin(), getArguments().end());
385
7.86k
  Argv.push_back(nullptr);
386
7.86k
387
  // This flag simply indicates that the program couldn't start, which isn't
388
  // applicable here.
389
7.86k
  if (ExecutionFailed)
390
7.86k
    *ExecutionFailed = false;
391
7.86k
392
7.86k
  llvm::CrashRecoveryContext CRC;
393
7.86k
  CRC.DumpStackAndCleanupOnFailure = true;
394
7.86k
395
7.86k
  const void *PrettyState = llvm::SavePrettyStackState();
396
7.86k
  const Driver &D = getCreator().getToolChain().getDriver();
397
7.86k
398
7.86k
  int R = 0;
399
  // Enter ExecuteCC1Tool() instead of starting up a new process
400
7.86k
  if (!CRC.RunSafely([&]() { R = D.CC1Main(Argv); })) {
401
10
    llvm::RestorePrettyStackState(PrettyState);
402
10
    return CRC.RetCode;
403
10
  }
404
7.85k
  return R;
405
7.85k
}
406
407
0
void CC1Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
408
  // We don't support set a new environment when calling into ExecuteCC1Tool()
409
0
  llvm_unreachable(
410
0
      "The CC1Command doesn't support changing the environment vars!");
411
0
}
412
413
FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
414
                                 ResponseFileSupport ResponseSupport,
415
                                 const char *Executable_,
416
                                 const llvm::opt::ArgStringList &Arguments_,
417
                                 ArrayRef<InputInfo> Inputs,
418
                                 std::unique_ptr<Command> Fallback_)
419
    : Command(Source_, Creator_, ResponseSupport, Executable_, Arguments_,
420
              Inputs),
421
15
      Fallback(std::move(Fallback_)) {}
422
423
void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
424
14
                            bool Quote, CrashReportInfo *CrashInfo) const {
425
14
  Command::Print(OS, "", Quote, CrashInfo);
426
14
  OS << " ||";
427
14
  Fallback->Print(OS, Terminator, Quote, CrashInfo);
428
14
}
429
430
1
static bool ShouldFallback(int ExitCode) {
431
  // FIXME: We really just want to fall back for internal errors, such
432
  // as when some symbol cannot be mangled, when we should be able to
433
  // parse something but can't, etc.
434
1
  return ExitCode != 0;
435
1
}
436
437
int FallbackCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
438
1
                             std::string *ErrMsg, bool *ExecutionFailed) const {
439
1
  int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
440
1
  if (!ShouldFallback(PrimaryStatus))
441
0
    return PrimaryStatus;
442
1
443
  // Clear ExecutionFailed and ErrMsg before falling back.
444
1
  if (ErrMsg)
445
1
    ErrMsg->clear();
446
1
  if (ExecutionFailed)
447
1
    *ExecutionFailed = false;
448
1
449
1
  const Driver &D = getCreator().getToolChain().getDriver();
450
1
  D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
451
1
452
1
  int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
453
1
  return SecondaryStatus;
454
1
}
455
456
ForceSuccessCommand::ForceSuccessCommand(
457
    const Action &Source_, const Tool &Creator_,
458
    ResponseFileSupport ResponseSupport, const char *Executable_,
459
    const llvm::opt::ArgStringList &Arguments_, ArrayRef<InputInfo> Inputs)
460
    : Command(Source_, Creator_, ResponseSupport, Executable_, Arguments_,
461
1
              Inputs) {}
462
463
void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
464
1
                            bool Quote, CrashReportInfo *CrashInfo) const {
465
1
  Command::Print(OS, "", Quote, CrashInfo);
466
1
  OS << " || (exit 0)" << Terminator;
467
1
}
468
469
int ForceSuccessCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
470
                                 std::string *ErrMsg,
471
0
                                 bool *ExecutionFailed) const {
472
0
  int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
473
0
  (void)Status;
474
0
  if (ExecutionFailed)
475
0
    *ExecutionFailed = false;
476
0
  return 0;
477
0
}
478
479
void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
480
7.82k
                    CrashReportInfo *CrashInfo) const {
481
7.82k
  for (const auto &Job : *this)
482
13.5k
    Job.Print(OS, Terminator, Quote, CrashInfo);
483
7.82k
}
484
485
27
void JobList::clear() { Jobs.clear(); }