Coverage Report

Created: 2020-02-15 09:57

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