Coverage Report

Created: 2019-07-24 05:18

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