Coverage Report

Created: 2021-09-21 08:58

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