Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Tooling/Tooling.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Tooling.cpp - Running clang standalone tools -----------------------===//
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 file implements functions to run clang tools standalone instead
10
//  of running them as a plugin.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Tooling/Tooling.h"
15
#include "clang/Basic/Diagnostic.h"
16
#include "clang/Basic/DiagnosticIDs.h"
17
#include "clang/Basic/DiagnosticOptions.h"
18
#include "clang/Basic/FileManager.h"
19
#include "clang/Basic/FileSystemOptions.h"
20
#include "clang/Basic/LLVM.h"
21
#include "clang/Driver/Compilation.h"
22
#include "clang/Driver/Driver.h"
23
#include "clang/Driver/Job.h"
24
#include "clang/Driver/Options.h"
25
#include "clang/Driver/Tool.h"
26
#include "clang/Driver/ToolChain.h"
27
#include "clang/Frontend/ASTUnit.h"
28
#include "clang/Frontend/CompilerInstance.h"
29
#include "clang/Frontend/CompilerInvocation.h"
30
#include "clang/Frontend/FrontendDiagnostic.h"
31
#include "clang/Frontend/FrontendOptions.h"
32
#include "clang/Frontend/TextDiagnosticPrinter.h"
33
#include "clang/Lex/HeaderSearchOptions.h"
34
#include "clang/Lex/PreprocessorOptions.h"
35
#include "clang/Tooling/ArgumentsAdjusters.h"
36
#include "clang/Tooling/CompilationDatabase.h"
37
#include "llvm/ADT/ArrayRef.h"
38
#include "llvm/ADT/IntrusiveRefCntPtr.h"
39
#include "llvm/ADT/SmallString.h"
40
#include "llvm/ADT/StringRef.h"
41
#include "llvm/ADT/Twine.h"
42
#include "llvm/Option/ArgList.h"
43
#include "llvm/Option/OptTable.h"
44
#include "llvm/Option/Option.h"
45
#include "llvm/Support/Casting.h"
46
#include "llvm/Support/Debug.h"
47
#include "llvm/Support/ErrorHandling.h"
48
#include "llvm/Support/FileSystem.h"
49
#include "llvm/Support/Host.h"
50
#include "llvm/Support/MemoryBuffer.h"
51
#include "llvm/Support/Path.h"
52
#include "llvm/Support/VirtualFileSystem.h"
53
#include "llvm/Support/raw_ostream.h"
54
#include <cassert>
55
#include <cstring>
56
#include <memory>
57
#include <string>
58
#include <system_error>
59
#include <utility>
60
#include <vector>
61
62
#define DEBUG_TYPE "clang-tooling"
63
64
using namespace clang;
65
using namespace tooling;
66
67
39.2k
ToolAction::~ToolAction() = default;
68
69
32.7k
FrontendActionFactory::~FrontendActionFactory() = default;
70
71
// FIXME: This file contains structural duplication with other parts of the
72
// code that sets up a compiler to run tools on it, and we should refactor
73
// it to be based on the same framework.
74
75
/// Builds a clang driver initialized for running clang tools.
76
static driver::Driver *
77
newDriver(DiagnosticsEngine *Diagnostics, const char *BinaryName,
78
23.3k
          IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
79
23.3k
  driver::Driver *CompilerDriver =
80
23.3k
      new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
81
23.3k
                         *Diagnostics, "clang LLVM compiler", std::move(VFS));
82
23.3k
  CompilerDriver->setTitle("clang_based_tool");
83
23.3k
  return CompilerDriver;
84
23.3k
}
85
86
/// Decide whether extra compiler frontend commands can be ignored.
87
3
static bool ignoreExtraCC1Commands(const driver::Compilation *Compilation) {
88
3
  const driver::JobList &Jobs = Compilation->getJobs();
89
3
  const driver::ActionList &Actions = Compilation->getActions();
90
91
3
  bool OffloadCompilation = false;
92
93
  // Jobs and Actions look very different depending on whether the Clang tool
94
  // injected -fsyntax-only or not. Try to handle both cases here.
95
96
3
  for (const auto &Job : Jobs)
97
7
    if (StringRef(Job.getExecutable()) == "clang-offload-bundler")
98
0
      OffloadCompilation = true;
99
100
3
  if (Jobs.size() > 1) {
101
5
    for (auto A : Actions){
102
      // On MacOSX real actions may end up being wrapped in BindArchAction
103
5
      if (isa<driver::BindArchAction>(A))
104
4
        A = *A->input_begin();
105
5
      if (isa<driver::OffloadAction>(A)) {
106
        // Offload compilation has 2 top-level actions, one (at the front) is
107
        // the original host compilation and the other is offload action
108
        // composed of at least one device compilation. For such case, general
109
        // tooling will consider host-compilation only. For tooling on device
110
        // compilation, device compilation only option, such as
111
        // `--cuda-device-only`, needs specifying.
112
1
        assert(Actions.size() > 1);
113
0
        assert(
114
1
            isa<driver::CompileJobAction>(Actions.front()) ||
115
            // On MacOSX real actions may end up being wrapped in
116
            // BindArchAction.
117
1
            (isa<driver::BindArchAction>(Actions.front()) &&
118
1
             isa<driver::CompileJobAction>(*Actions.front()->input_begin())));
119
0
        OffloadCompilation = true;
120
1
        break;
121
1
      }
122
5
    }
123
3
  }
124
125
3
  return OffloadCompilation;
126
3
}
127
128
namespace clang {
129
namespace tooling {
130
131
const llvm::opt::ArgStringList *
132
getCC1Arguments(DiagnosticsEngine *Diagnostics,
133
23.3k
                driver::Compilation *Compilation) {
134
23.3k
  const driver::JobList &Jobs = Compilation->getJobs();
135
136
23.3k
  auto IsCC1Command = [](const driver::Command &Cmd) {
137
23.3k
    return StringRef(Cmd.getCreator().getName()) == "clang";
138
23.3k
  };
139
140
23.3k
  auto IsSrcFile = [](const driver::InputInfo &II) {
141
23.3k
    return isSrcFile(II.getType());
142
23.3k
  };
143
144
23.3k
  llvm::SmallVector<const driver::Command *, 1> CC1Jobs;
145
23.3k
  for (const driver::Command &Job : Jobs)
146
23.3k
    if (IsCC1Command(Job) && 
llvm::all_of(Job.getInputInfos(), IsSrcFile)23.3k
)
147
23.3k
      CC1Jobs.push_back(&Job);
148
149
23.3k
  if (CC1Jobs.empty() ||
150
23.3k
      
(23.3k
CC1Jobs.size() > 123.3k
&&
!ignoreExtraCC1Commands(Compilation)3
)) {
151
4
    SmallString<256> error_msg;
152
4
    llvm::raw_svector_ostream error_stream(error_msg);
153
4
    Jobs.Print(error_stream, "; ", true);
154
4
    Diagnostics->Report(diag::err_fe_expected_compiler_job)
155
4
        << error_stream.str();
156
4
    return nullptr;
157
4
  }
158
159
23.3k
  return &CC1Jobs[0]->getArguments();
160
23.3k
}
161
162
/// Returns a clang build invocation initialized from the CC1 flags.
163
CompilerInvocation *newInvocation(DiagnosticsEngine *Diagnostics,
164
                                  const llvm::opt::ArgStringList &CC1Args,
165
23.3k
                                  const char *const BinaryName) {
166
23.3k
  assert(!CC1Args.empty() && "Must at least contain the program name!");
167
0
  CompilerInvocation *Invocation = new CompilerInvocation;
168
23.3k
  CompilerInvocation::CreateFromArgs(*Invocation, CC1Args, *Diagnostics,
169
23.3k
                                     BinaryName);
170
23.3k
  Invocation->getFrontendOpts().DisableFree = false;
171
23.3k
  Invocation->getCodeGenOpts().DisableFree = false;
172
23.3k
  return Invocation;
173
23.3k
}
174
175
bool runToolOnCode(std::unique_ptr<FrontendAction> ToolAction,
176
                   const Twine &Code, const Twine &FileName,
177
128
                   std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
178
128
  return runToolOnCodeWithArgs(std::move(ToolAction), Code,
179
128
                               std::vector<std::string>(), FileName,
180
128
                               "clang-tool", std::move(PCHContainerOps));
181
128
}
182
183
} // namespace tooling
184
} // namespace clang
185
186
static std::vector<std::string>
187
getSyntaxOnlyToolArgs(const Twine &ToolName,
188
                      const std::vector<std::string> &ExtraArgs,
189
22.8k
                      StringRef FileName) {
190
22.8k
  std::vector<std::string> Args;
191
22.8k
  Args.push_back(ToolName.str());
192
22.8k
  Args.push_back("-fsyntax-only");
193
22.8k
  Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
194
22.8k
  Args.push_back(FileName.str());
195
22.8k
  return Args;
196
22.8k
}
197
198
namespace clang {
199
namespace tooling {
200
201
bool runToolOnCodeWithArgs(
202
    std::unique_ptr<FrontendAction> ToolAction, const Twine &Code,
203
    llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
204
    const std::vector<std::string> &Args, const Twine &FileName,
205
    const Twine &ToolName,
206
16.5k
    std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
207
16.5k
  SmallString<16> FileNameStorage;
208
16.5k
  StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
209
210
16.5k
  llvm::IntrusiveRefCntPtr<FileManager> Files(
211
16.5k
      new FileManager(FileSystemOptions(), VFS));
212
16.5k
  ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();
213
16.5k
  ToolInvocation Invocation(
214
16.5k
      getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
215
16.5k
      std::move(ToolAction), Files.get(), std::move(PCHContainerOps));
216
16.5k
  return Invocation.run();
217
16.5k
}
218
219
bool runToolOnCodeWithArgs(
220
    std::unique_ptr<FrontendAction> ToolAction, const Twine &Code,
221
    const std::vector<std::string> &Args, const Twine &FileName,
222
    const Twine &ToolName,
223
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
224
16.5k
    const FileContentMappings &VirtualMappedFiles) {
225
16.5k
  llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
226
16.5k
      new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
227
16.5k
  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
228
16.5k
      new llvm::vfs::InMemoryFileSystem);
229
16.5k
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
230
231
16.5k
  SmallString<1024> CodeStorage;
232
16.5k
  InMemoryFileSystem->addFile(FileName, 0,
233
16.5k
                              llvm::MemoryBuffer::getMemBuffer(
234
16.5k
                                  Code.toNullTerminatedStringRef(CodeStorage)));
235
236
16.5k
  for (auto &FilenameWithContent : VirtualMappedFiles) {
237
1.11k
    InMemoryFileSystem->addFile(
238
1.11k
        FilenameWithContent.first, 0,
239
1.11k
        llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
240
1.11k
  }
241
242
16.5k
  return runToolOnCodeWithArgs(std::move(ToolAction), Code, OverlayFileSystem,
243
16.5k
                               Args, FileName, ToolName);
244
16.5k
}
245
246
llvm::Expected<std::string> getAbsolutePath(llvm::vfs::FileSystem &FS,
247
512
                                            StringRef File) {
248
512
  StringRef RelativePath(File);
249
  // FIXME: Should '.\\' be accepted on Win32?
250
512
  if (RelativePath.startswith("./")) {
251
0
    RelativePath = RelativePath.substr(strlen("./"));
252
0
  }
253
254
512
  SmallString<1024> AbsolutePath = RelativePath;
255
512
  if (auto EC = FS.makeAbsolute(AbsolutePath))
256
0
    return llvm::errorCodeToError(EC);
257
512
  llvm::sys::path::native(AbsolutePath);
258
512
  return std::string(AbsolutePath.str());
259
512
}
260
261
22
std::string getAbsolutePath(StringRef File) {
262
22
  return llvm::cantFail(getAbsolutePath(*llvm::vfs::getRealFileSystem(), File));
263
22
}
264
265
void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
266
26
                                    StringRef InvokedAs) {
267
26
  if (CommandLine.empty() || InvokedAs.empty())
268
1
    return;
269
25
  const auto &Table = driver::getDriverOptTable();
270
  // --target=X
271
25
  const std::string TargetOPT =
272
25
      Table.getOption(driver::options::OPT_target).getPrefixedName();
273
  // -target X
274
25
  const std::string TargetOPTLegacy =
275
25
      Table.getOption(driver::options::OPT_target_legacy_spelling)
276
25
          .getPrefixedName();
277
  // --driver-mode=X
278
25
  const std::string DriverModeOPT =
279
25
      Table.getOption(driver::options::OPT_driver_mode).getPrefixedName();
280
25
  auto TargetMode =
281
25
      driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
282
  // No need to search for target args if we don't have a target/mode to insert.
283
25
  bool ShouldAddTarget = TargetMode.TargetIsValid;
284
25
  bool ShouldAddMode = TargetMode.DriverMode != nullptr;
285
  // Skip CommandLine[0].
286
96
  for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
287
71
       ++Token) {
288
71
    StringRef TokenRef(*Token);
289
71
    ShouldAddTarget = ShouldAddTarget && 
!TokenRef.startswith(TargetOPT)8
&&
290
71
                      
!TokenRef.equals(TargetOPTLegacy)7
;
291
71
    ShouldAddMode = ShouldAddMode && 
!TokenRef.startswith(DriverModeOPT)62
;
292
71
  }
293
25
  if (ShouldAddMode) {
294
20
    CommandLine.insert(++CommandLine.begin(), TargetMode.DriverMode);
295
20
  }
296
25
  if (ShouldAddTarget) {
297
3
    CommandLine.insert(++CommandLine.begin(),
298
3
                       TargetOPT + TargetMode.TargetPrefix);
299
3
  }
300
25
}
301
302
} // namespace tooling
303
} // namespace clang
304
305
namespace {
306
307
class SingleFrontendActionFactory : public FrontendActionFactory {
308
  std::unique_ptr<FrontendAction> Action;
309
310
public:
311
  SingleFrontendActionFactory(std::unique_ptr<FrontendAction> Action)
312
16.5k
      : Action(std::move(Action)) {}
313
314
16.5k
  std::unique_ptr<FrontendAction> create() override {
315
16.5k
    return std::move(Action);
316
16.5k
  }
317
};
318
319
} // namespace
320
321
ToolInvocation::ToolInvocation(
322
    std::vector<std::string> CommandLine, ToolAction *Action,
323
    FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
324
    : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
325
6.77k
      Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {}
326
327
ToolInvocation::ToolInvocation(
328
    std::vector<std::string> CommandLine,
329
    std::unique_ptr<FrontendAction> FAction, FileManager *Files,
330
    std::shared_ptr<PCHContainerOperations> PCHContainerOps)
331
    : CommandLine(std::move(CommandLine)),
332
      Action(new SingleFrontendActionFactory(std::move(FAction))),
333
      OwnsAction(true), Files(Files),
334
16.5k
      PCHContainerOps(std::move(PCHContainerOps)) {}
335
336
23.3k
ToolInvocation::~ToolInvocation() {
337
23.3k
  if (OwnsAction)
338
16.5k
    delete Action;
339
23.3k
}
340
341
23.3k
bool ToolInvocation::run() {
342
23.3k
  std::vector<const char*> Argv;
343
23.3k
  for (const std::string &Str : CommandLine)
344
225k
    Argv.push_back(Str.c_str());
345
23.3k
  const char *const BinaryName = Argv[0];
346
23.3k
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
347
23.3k
  unsigned MissingArgIndex, MissingArgCount;
348
23.3k
  llvm::opt::InputArgList ParsedArgs = driver::getDriverOptTable().ParseArgs(
349
23.3k
      ArrayRef<const char *>(Argv).slice(1), MissingArgIndex, MissingArgCount);
350
23.3k
  ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
351
23.3k
  TextDiagnosticPrinter DiagnosticPrinter(
352
23.3k
      llvm::errs(), &*DiagOpts);
353
23.3k
  DiagnosticsEngine Diagnostics(
354
23.3k
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
355
23.3k
      DiagConsumer ? 
DiagConsumer159
:
&DiagnosticPrinter23.1k
, false);
356
  // Although `Diagnostics` are used only for command-line parsing, the custom
357
  // `DiagConsumer` might expect a `SourceManager` to be present.
358
23.3k
  SourceManager SrcMgr(Diagnostics, *Files);
359
23.3k
  Diagnostics.setSourceManager(&SrcMgr);
360
361
23.3k
  const std::unique_ptr<driver::Driver> Driver(
362
23.3k
      newDriver(&Diagnostics, BinaryName, &Files->getVirtualFileSystem()));
363
  // The "input file not found" diagnostics from the driver are useful.
364
  // The driver is only aware of the VFS working directory, but some clients
365
  // change this at the FileManager level instead.
366
  // In this case the checks have false positives, so skip them.
367
23.3k
  if (!Files->getFileSystemOpts().WorkingDir.empty())
368
67
    Driver->setCheckInputsExist(false);
369
23.3k
  const std::unique_ptr<driver::Compilation> Compilation(
370
23.3k
      Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
371
23.3k
  if (!Compilation)
372
0
    return false;
373
23.3k
  const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
374
23.3k
      &Diagnostics, Compilation.get());
375
23.3k
  if (!CC1Args)
376
2
    return false;
377
23.3k
  std::unique_ptr<CompilerInvocation> Invocation(
378
23.3k
      newInvocation(&Diagnostics, *CC1Args, BinaryName));
379
23.3k
  return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
380
23.3k
                       std::move(PCHContainerOps));
381
23.3k
}
382
383
bool ToolInvocation::runInvocation(
384
    const char *BinaryName, driver::Compilation *Compilation,
385
    std::shared_ptr<CompilerInvocation> Invocation,
386
23.3k
    std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
387
  // Show the invocation, with -v.
388
23.3k
  if (Invocation->getHeaderSearchOpts().Verbose) {
389
1
    llvm::errs() << "clang Invocation:\n";
390
1
    Compilation->getJobs().Print(llvm::errs(), "\n", true);
391
1
    llvm::errs() << "\n";
392
1
  }
393
394
23.3k
  return Action->runInvocation(std::move(Invocation), Files,
395
23.3k
                               std::move(PCHContainerOps), DiagConsumer);
396
23.3k
}
397
398
bool FrontendActionFactory::runInvocation(
399
    std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
400
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
401
16.8k
    DiagnosticConsumer *DiagConsumer) {
402
  // Create a compiler instance to handle the actual work.
403
16.8k
  CompilerInstance Compiler(std::move(PCHContainerOps));
404
16.8k
  Compiler.setInvocation(std::move(Invocation));
405
16.8k
  Compiler.setFileManager(Files);
406
407
  // The FrontendAction can have lifetime requirements for Compiler or its
408
  // members, and we need to ensure it's deleted earlier than Compiler. So we
409
  // pass it to an std::unique_ptr declared after the Compiler variable.
410
16.8k
  std::unique_ptr<FrontendAction> ScopedToolAction(create());
411
412
  // Create the compiler's actual diagnostics engine.
413
16.8k
  Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
414
16.8k
  if (!Compiler.hasDiagnostics())
415
0
    return false;
416
417
16.8k
  Compiler.createSourceManager(*Files);
418
419
16.8k
  const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
420
421
16.8k
  Files->clearStatCache();
422
16.8k
  return Success;
423
16.8k
}
424
425
ClangTool::ClangTool(const CompilationDatabase &Compilations,
426
                     ArrayRef<std::string> SourcePaths,
427
                     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
428
                     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
429
                     IntrusiveRefCntPtr<FileManager> Files)
430
    : Compilations(Compilations), SourcePaths(SourcePaths),
431
      PCHContainerOps(std::move(PCHContainerOps)),
432
      OverlayFileSystem(new llvm::vfs::OverlayFileSystem(std::move(BaseFS))),
433
      InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem),
434
      Files(Files ? Files
435
419
                  : new FileManager(FileSystemOptions(), OverlayFileSystem)) {
436
419
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
437
419
  appendArgumentsAdjuster(getClangStripOutputAdjuster());
438
419
  appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
439
419
  appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
440
419
  if (Files)
441
151
    Files->setVirtualFileSystem(OverlayFileSystem);
442
419
}
443
444
421
ClangTool::~ClangTool() = default;
445
446
9.38k
void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
447
9.38k
  MappedFileContents.push_back(std::make_pair(FilePath, Content));
448
9.38k
}
449
450
1.59k
void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
451
1.59k
  ArgsAdjuster = combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
452
1.59k
}
453
454
201
void ClangTool::clearArgumentsAdjusters() {
455
201
  ArgsAdjuster = nullptr;
456
201
}
457
458
static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
459
495
                              void *MainAddr) {
460
  // Allow users to override the resource dir.
461
495
  for (StringRef Arg : Args)
462
2.48k
    if (Arg.startswith("-resource-dir"))
463
0
      return;
464
465
  // If there's no override in place add our resource dir.
466
495
  Args = getInsertArgumentAdjuster(
467
495
      ("-resource-dir=" + CompilerInvocation::GetResourcesPath(Argv0, MainAddr))
468
495
          .c_str())(Args, "");
469
495
}
470
471
487
int ClangTool::run(ToolAction *Action) {
472
  // Exists solely for the purpose of lookup of the resource path.
473
  // This just needs to be some symbol in the binary.
474
487
  static int StaticSymbol;
475
476
  // First insert all absolute paths into the in-memory VFS. These are global
477
  // for all compile commands.
478
487
  if (SeenWorkingDirectories.insert("/").second)
479
418
    for (const auto &MappedFile : MappedFileContents)
480
9.59k
      if (llvm::sys::path::is_absolute(MappedFile.first))
481
13
        InMemoryFileSystem->addFile(
482
13
            MappedFile.first, 0,
483
13
            llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
484
485
487
  bool ProcessingFailed = false;
486
487
  bool FileSkipped = false;
487
  // Compute all absolute paths before we run any actions, as those will change
488
  // the working directory.
489
487
  std::vector<std::string> AbsolutePaths;
490
487
  AbsolutePaths.reserve(SourcePaths.size());
491
491
  for (const auto &SourcePath : SourcePaths) {
492
491
    auto AbsPath = getAbsolutePath(*OverlayFileSystem, SourcePath);
493
491
    if (!AbsPath) {
494
0
      llvm::errs() << "Skipping " << SourcePath
495
0
                   << ". Error while getting an absolute path: "
496
0
                   << llvm::toString(AbsPath.takeError()) << "\n";
497
0
      continue;
498
0
    }
499
491
    AbsolutePaths.push_back(std::move(*AbsPath));
500
491
  }
501
502
  // Remember the working directory in case we need to restore it.
503
487
  std::string InitialWorkingDir;
504
487
  if (RestoreCWD) {
505
335
    if (auto 
CWD334
= OverlayFileSystem->getCurrentWorkingDirectory()) {
506
335
      InitialWorkingDir = std::move(*CWD);
507
18.4E
    } else {
508
18.4E
      llvm::errs() << "Could not get working directory: "
509
18.4E
                   << CWD.getError().message() << "\n";
510
18.4E
    }
511
334
  }
512
513
487
  for (llvm::StringRef File : AbsolutePaths) {
514
    // Currently implementations of CompilationDatabase::getCompileCommands can
515
    // change the state of the file system (e.g.  prepare generated headers), so
516
    // this method needs to run right before we invoke the tool, as the next
517
    // file may require a different (incompatible) state of the file system.
518
    //
519
    // FIXME: Make the compilation database interface more explicit about the
520
    // requirements to the order of invocation of its members.
521
484
    std::vector<CompileCommand> CompileCommandsForFile =
522
484
        Compilations.getCompileCommands(File);
523
484
    if (CompileCommandsForFile.empty()) {
524
0
      llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
525
0
      FileSkipped = true;
526
0
      continue;
527
0
    }
528
495
    
for (CompileCommand &CompileCommand : CompileCommandsForFile)484
{
529
      // FIXME: chdir is thread hostile; on the other hand, creating the same
530
      // behavior as chdir is complex: chdir resolves the path once, thus
531
      // guaranteeing that all subsequent relative path operations work
532
      // on the same path the original chdir resulted in. This makes a
533
      // difference for example on network filesystems, where symlinks might be
534
      // switched during runtime of the tool. Fixing this depends on having a
535
      // file system abstraction that allows openat() style interactions.
536
495
      if (OverlayFileSystem->setCurrentWorkingDirectory(
537
495
              CompileCommand.Directory))
538
0
        llvm::report_fatal_error("Cannot chdir into \"" +
539
0
                                 Twine(CompileCommand.Directory) + "\"!");
540
541
      // Now fill the in-memory VFS with the relative file mappings so it will
542
      // have the correct relative paths. We never remove mappings but that
543
      // should be fine.
544
495
      if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
545
406
        for (const auto &MappedFile : MappedFileContents)
546
9.98k
          if (!llvm::sys::path::is_absolute(MappedFile.first))
547
9.94k
            InMemoryFileSystem->addFile(
548
9.94k
                MappedFile.first, 0,
549
9.94k
                llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
550
551
495
      std::vector<std::string> CommandLine = CompileCommand.CommandLine;
552
495
      if (ArgsAdjuster)
553
334
        CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
554
495
      assert(!CommandLine.empty());
555
556
      // Add the resource dir based on the binary of this tool. argv[0] in the
557
      // compilation database may refer to a different compiler and we want to
558
      // pick up the very same standard library that compiler is using. The
559
      // builtin headers in the resource dir need to match the exact clang
560
      // version the tool is using.
561
      // FIXME: On linux, GetMainExecutable is independent of the value of the
562
      // first argument, thus allowing ClangTool and runToolOnCode to just
563
      // pass in made-up names here. Make sure this works on other platforms.
564
0
      injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
565
566
      // FIXME: We need a callback mechanism for the tool writer to output a
567
      // customized message for each file.
568
495
      LLVM_DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
569
495
      ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
570
495
                                PCHContainerOps);
571
495
      Invocation.setDiagnosticConsumer(DiagConsumer);
572
573
495
      if (!Invocation.run()) {
574
        // FIXME: Diagnostics should be used instead.
575
23
        if (PrintErrorMessage)
576
17
          llvm::errs() << "Error while processing " << File << ".\n";
577
23
        ProcessingFailed = true;
578
23
      }
579
495
    }
580
484
  }
581
582
487
  if (!InitialWorkingDir.empty()) {
583
335
    if (auto EC =
584
335
            OverlayFileSystem->setCurrentWorkingDirectory(InitialWorkingDir))
585
0
      llvm::errs() << "Error when trying to restore working dir: "
586
0
                   << EC.message() << "\n";
587
335
  }
588
487
  return ProcessingFailed ? 
123
:
(464
FileSkipped464
?
20
:
0464
);
589
487
}
590
591
namespace {
592
593
class ASTBuilderAction : public ToolAction {
594
  std::vector<std::unique_ptr<ASTUnit>> &ASTs;
595
596
public:
597
6.30k
  ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
598
599
  bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
600
                     FileManager *Files,
601
                     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
602
6.30k
                     DiagnosticConsumer *DiagConsumer) override {
603
6.30k
    std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
604
6.30k
        Invocation, std::move(PCHContainerOps),
605
6.30k
        CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
606
6.30k
                                            DiagConsumer,
607
6.30k
                                            /*ShouldOwnClient=*/false),
608
6.30k
        Files);
609
6.30k
    if (!AST)
610
0
      return false;
611
612
6.30k
    ASTs.push_back(std::move(AST));
613
6.30k
    return true;
614
6.30k
  }
615
};
616
617
} // namespace
618
619
19
int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
620
19
  ASTBuilderAction Action(ASTs);
621
19
  return run(&Action);
622
19
}
623
624
153
void ClangTool::setRestoreWorkingDir(bool RestoreCWD) {
625
153
  this->RestoreCWD = RestoreCWD;
626
153
}
627
628
154
void ClangTool::setPrintErrorMessage(bool PrintErrorMessage) {
629
154
  this->PrintErrorMessage = PrintErrorMessage;
630
154
}
631
632
namespace clang {
633
namespace tooling {
634
635
std::unique_ptr<ASTUnit>
636
buildASTFromCode(StringRef Code, StringRef FileName,
637
175
                 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
638
175
  return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
639
175
                                  "clang-tool", std::move(PCHContainerOps));
640
175
}
641
642
std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
643
    StringRef Code, const std::vector<std::string> &Args, StringRef FileName,
644
    StringRef ToolName, std::shared_ptr<PCHContainerOperations> PCHContainerOps,
645
    ArgumentsAdjuster Adjuster, const FileContentMappings &VirtualMappedFiles,
646
6.28k
    DiagnosticConsumer *DiagConsumer) {
647
6.28k
  std::vector<std::unique_ptr<ASTUnit>> ASTs;
648
6.28k
  ASTBuilderAction Action(ASTs);
649
6.28k
  llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
650
6.28k
      new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
651
6.28k
  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
652
6.28k
      new llvm::vfs::InMemoryFileSystem);
653
6.28k
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
654
6.28k
  llvm::IntrusiveRefCntPtr<FileManager> Files(
655
6.28k
      new FileManager(FileSystemOptions(), OverlayFileSystem));
656
657
6.28k
  ToolInvocation Invocation(
658
6.28k
      getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileName), FileName),
659
6.28k
      &Action, Files.get(), std::move(PCHContainerOps));
660
6.28k
  Invocation.setDiagnosticConsumer(DiagConsumer);
661
662
6.28k
  InMemoryFileSystem->addFile(FileName, 0,
663
6.28k
                              llvm::MemoryBuffer::getMemBufferCopy(Code));
664
6.28k
  for (auto &FilenameWithContent : VirtualMappedFiles) {
665
0
    InMemoryFileSystem->addFile(
666
0
        FilenameWithContent.first, 0,
667
0
        llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
668
0
  }
669
670
6.28k
  if (!Invocation.run())
671
0
    return nullptr;
672
 
673
6.28k
  assert(ASTs.size() == 1);
674
0
  return std::move(ASTs[0]);
675
6.28k
}
676
677
} // namespace tooling
678
} // namespace clang