Coverage Report

Created: 2022-07-16 07:03

/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
42.0k
ToolAction::~ToolAction() = default;
68
69
34.5k
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
25.3k
          IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
79
25.3k
  driver::Driver *CompilerDriver =
80
25.3k
      new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
81
25.3k
                         *Diagnostics, "clang LLVM compiler", std::move(VFS));
82
25.3k
  CompilerDriver->setTitle("clang_based_tool");
83
25.3k
  return CompilerDriver;
84
25.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
25.3k
                driver::Compilation *Compilation) {
134
25.3k
  const driver::JobList &Jobs = Compilation->getJobs();
135
136
25.3k
  auto IsCC1Command = [](const driver::Command &Cmd) {
137
25.3k
    return StringRef(Cmd.getCreator().getName()) == "clang";
138
25.3k
  };
139
140
25.3k
  auto IsSrcFile = [](const driver::InputInfo &II) {
141
25.3k
    return isSrcFile(II.getType());
142
25.3k
  };
143
144
25.3k
  llvm::SmallVector<const driver::Command *, 1> CC1Jobs;
145
25.3k
  for (const driver::Command &Job : Jobs)
146
25.3k
    if (IsCC1Command(Job) && 
llvm::all_of(Job.getInputInfos(), IsSrcFile)25.3k
)
147
25.3k
      CC1Jobs.push_back(&Job);
148
149
25.3k
  if (CC1Jobs.empty() ||
150
25.3k
      
(25.3k
CC1Jobs.size() > 125.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
25.3k
  return &CC1Jobs[0]->getArguments();
160
25.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
25.3k
                                  const char *const BinaryName) {
166
25.3k
  assert(!CC1Args.empty() && "Must at least contain the program name!");
167
0
  CompilerInvocation *Invocation = new CompilerInvocation;
168
25.3k
  CompilerInvocation::CreateFromArgs(*Invocation, CC1Args, *Diagnostics,
169
25.3k
                                     BinaryName);
170
25.3k
  Invocation->getFrontendOpts().DisableFree = false;
171
25.3k
  Invocation->getCodeGenOpts().DisableFree = false;
172
25.3k
  return Invocation;
173
25.3k
}
174
175
bool runToolOnCode(std::unique_ptr<FrontendAction> ToolAction,
176
                   const Twine &Code, const Twine &FileName,
177
150
                   std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
178
150
  return runToolOnCodeWithArgs(std::move(ToolAction), Code,
179
150
                               std::vector<std::string>(), FileName,
180
150
                               "clang-tool", std::move(PCHContainerOps));
181
150
}
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
24.8k
                      StringRef FileName) {
190
24.8k
  std::vector<std::string> Args;
191
24.8k
  Args.push_back(ToolName.str());
192
24.8k
  Args.push_back("-fsyntax-only");
193
24.8k
  Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
194
24.8k
  Args.push_back(FileName.str());
195
24.8k
  return Args;
196
24.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
17.5k
    std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
207
17.5k
  SmallString<16> FileNameStorage;
208
17.5k
  StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
209
210
17.5k
  llvm::IntrusiveRefCntPtr<FileManager> Files(
211
17.5k
      new FileManager(FileSystemOptions(), VFS));
212
17.5k
  ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();
213
17.5k
  ToolInvocation Invocation(
214
17.5k
      getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
215
17.5k
      std::move(ToolAction), Files.get(), std::move(PCHContainerOps));
216
17.5k
  return Invocation.run();
217
17.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
17.5k
    const FileContentMappings &VirtualMappedFiles) {
225
17.5k
  llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
226
17.5k
      new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
227
17.5k
  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
228
17.5k
      new llvm::vfs::InMemoryFileSystem);
229
17.5k
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
230
231
17.5k
  SmallString<1024> CodeStorage;
232
17.5k
  InMemoryFileSystem->addFile(FileName, 0,
233
17.5k
                              llvm::MemoryBuffer::getMemBuffer(
234
17.5k
                                  Code.toNullTerminatedStringRef(CodeStorage)));
235
236
17.5k
  for (auto &FilenameWithContent : VirtualMappedFiles) {
237
1.12k
    InMemoryFileSystem->addFile(
238
1.12k
        FilenameWithContent.first, 0,
239
1.12k
        llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
240
1.12k
  }
241
242
17.5k
  return runToolOnCodeWithArgs(std::move(ToolAction), Code, OverlayFileSystem,
243
17.5k
                               Args, FileName, ToolName);
244
17.5k
}
245
246
llvm::Expected<std::string> getAbsolutePath(llvm::vfs::FileSystem &FS,
247
366
                                            StringRef File) {
248
366
  StringRef RelativePath(File);
249
  // FIXME: Should '.\\' be accepted on Win32?
250
366
  if (RelativePath.startswith("./")) {
251
0
    RelativePath = RelativePath.substr(strlen("./"));
252
0
  }
253
254
366
  SmallString<1024> AbsolutePath = RelativePath;
255
366
  if (auto EC = FS.makeAbsolute(AbsolutePath))
256
0
    return llvm::errorCodeToError(EC);
257
366
  llvm::sys::path::native(AbsolutePath);
258
366
  return std::string(AbsolutePath.str());
259
366
}
260
261
23
std::string getAbsolutePath(StringRef File) {
262
23
  return llvm::cantFail(getAbsolutePath(*llvm::vfs::getRealFileSystem(), File));
263
23
}
264
265
void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
266
27
                                    StringRef InvokedAs) {
267
27
  if (CommandLine.empty() || InvokedAs.empty())
268
1
    return;
269
26
  const auto &Table = driver::getDriverOptTable();
270
  // --target=X
271
26
  const std::string TargetOPT =
272
26
      Table.getOption(driver::options::OPT_target).getPrefixedName();
273
  // -target X
274
26
  const std::string TargetOPTLegacy =
275
26
      Table.getOption(driver::options::OPT_target_legacy_spelling)
276
26
          .getPrefixedName();
277
  // --driver-mode=X
278
26
  const std::string DriverModeOPT =
279
26
      Table.getOption(driver::options::OPT_driver_mode).getPrefixedName();
280
26
  auto TargetMode =
281
26
      driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
282
  // No need to search for target args if we don't have a target/mode to insert.
283
26
  bool ShouldAddTarget = TargetMode.TargetIsValid;
284
26
  bool ShouldAddMode = TargetMode.DriverMode != nullptr;
285
  // Skip CommandLine[0].
286
103
  for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
287
77
       ++Token) {
288
77
    StringRef TokenRef(*Token);
289
77
    ShouldAddTarget = ShouldAddTarget && 
!TokenRef.startswith(TargetOPT)8
&&
290
77
                      
!TokenRef.equals(TargetOPTLegacy)7
;
291
77
    ShouldAddMode = ShouldAddMode && 
!TokenRef.startswith(DriverModeOPT)68
;
292
77
  }
293
26
  if (ShouldAddMode) {
294
21
    CommandLine.insert(++CommandLine.begin(), TargetMode.DriverMode);
295
21
  }
296
26
  if (ShouldAddTarget) {
297
3
    CommandLine.insert(++CommandLine.begin(),
298
3
                       TargetOPT + TargetMode.TargetPrefix);
299
3
  }
300
26
}
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
17.5k
      : Action(std::move(Action)) {}
313
314
17.5k
  std::unique_ptr<FrontendAction> create() override {
315
17.5k
    return std::move(Action);
316
17.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
7.82k
      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
17.5k
      PCHContainerOps(std::move(PCHContainerOps)) {}
335
336
25.3k
ToolInvocation::~ToolInvocation() {
337
25.3k
  if (OwnsAction)
338
17.5k
    delete Action;
339
25.3k
}
340
341
25.3k
bool ToolInvocation::run() {
342
25.3k
  std::vector<const char*> Argv;
343
25.3k
  for (const std::string &Str : CommandLine)
344
242k
    Argv.push_back(Str.c_str());
345
25.3k
  const char *const BinaryName = Argv[0];
346
347
  // Parse diagnostic options from the driver command-line only if none were
348
  // explicitly set.
349
25.3k
  IntrusiveRefCntPtr<DiagnosticOptions> ParsedDiagOpts;
350
25.3k
  DiagnosticOptions *DiagOpts = this->DiagOpts;
351
25.3k
  if (!DiagOpts) {
352
25.1k
    ParsedDiagOpts = CreateAndPopulateDiagOpts(Argv);
353
25.1k
    DiagOpts = &*ParsedDiagOpts;
354
25.1k
  }
355
356
25.3k
  TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), DiagOpts);
357
25.3k
  IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics =
358
25.3k
      CompilerInstance::createDiagnostics(
359
25.3k
          &*DiagOpts, DiagConsumer ? 
DiagConsumer230
:
&DiagnosticPrinter25.1k
, false);
360
  // Although `Diagnostics` are used only for command-line parsing, the custom
361
  // `DiagConsumer` might expect a `SourceManager` to be present.
362
25.3k
  SourceManager SrcMgr(*Diagnostics, *Files);
363
25.3k
  Diagnostics->setSourceManager(&SrcMgr);
364
365
25.3k
  const std::unique_ptr<driver::Driver> Driver(
366
25.3k
      newDriver(&*Diagnostics, BinaryName, &Files->getVirtualFileSystem()));
367
  // The "input file not found" diagnostics from the driver are useful.
368
  // The driver is only aware of the VFS working directory, but some clients
369
  // change this at the FileManager level instead.
370
  // In this case the checks have false positives, so skip them.
371
25.3k
  if (!Files->getFileSystemOpts().WorkingDir.empty())
372
67
    Driver->setCheckInputsExist(false);
373
25.3k
  const std::unique_ptr<driver::Compilation> Compilation(
374
25.3k
      Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
375
25.3k
  if (!Compilation)
376
0
    return false;
377
25.3k
  const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
378
25.3k
      &*Diagnostics, Compilation.get());
379
25.3k
  if (!CC1Args)
380
2
    return false;
381
25.3k
  std::unique_ptr<CompilerInvocation> Invocation(
382
25.3k
      newInvocation(&*Diagnostics, *CC1Args, BinaryName));
383
25.3k
  return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
384
25.3k
                       std::move(PCHContainerOps));
385
25.3k
}
386
387
bool ToolInvocation::runInvocation(
388
    const char *BinaryName, driver::Compilation *Compilation,
389
    std::shared_ptr<CompilerInvocation> Invocation,
390
25.3k
    std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
391
  // Show the invocation, with -v.
392
25.3k
  if (Invocation->getHeaderSearchOpts().Verbose) {
393
2
    llvm::errs() << "clang Invocation:\n";
394
2
    Compilation->getJobs().Print(llvm::errs(), "\n", true);
395
2
    llvm::errs() << "\n";
396
2
  }
397
398
25.3k
  return Action->runInvocation(std::move(Invocation), Files,
399
25.3k
                               std::move(PCHContainerOps), DiagConsumer);
400
25.3k
}
401
402
bool FrontendActionFactory::runInvocation(
403
    std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
404
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
405
17.8k
    DiagnosticConsumer *DiagConsumer) {
406
  // Create a compiler instance to handle the actual work.
407
17.8k
  CompilerInstance Compiler(std::move(PCHContainerOps));
408
17.8k
  Compiler.setInvocation(std::move(Invocation));
409
17.8k
  Compiler.setFileManager(Files);
410
411
  // The FrontendAction can have lifetime requirements for Compiler or its
412
  // members, and we need to ensure it's deleted earlier than Compiler. So we
413
  // pass it to an std::unique_ptr declared after the Compiler variable.
414
17.8k
  std::unique_ptr<FrontendAction> ScopedToolAction(create());
415
416
  // Create the compiler's actual diagnostics engine.
417
17.8k
  Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
418
17.8k
  if (!Compiler.hasDiagnostics())
419
0
    return false;
420
421
17.8k
  Compiler.createSourceManager(*Files);
422
423
17.8k
  const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
424
425
17.8k
  Files->clearStatCache();
426
17.8k
  return Success;
427
17.8k
}
428
429
ClangTool::ClangTool(const CompilationDatabase &Compilations,
430
                     ArrayRef<std::string> SourcePaths,
431
                     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
432
                     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
433
                     IntrusiveRefCntPtr<FileManager> Files)
434
    : Compilations(Compilations), SourcePaths(SourcePaths),
435
      PCHContainerOps(std::move(PCHContainerOps)),
436
      OverlayFileSystem(new llvm::vfs::OverlayFileSystem(std::move(BaseFS))),
437
      InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem),
438
      Files(Files ? Files
439
269
                  : new FileManager(FileSystemOptions(), OverlayFileSystem)) {
440
269
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
441
269
  appendArgumentsAdjuster(getClangStripOutputAdjuster());
442
269
  appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
443
269
  appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
444
269
  if (Files)
445
0
    Files->setVirtualFileSystem(OverlayFileSystem);
446
269
}
447
448
269
ClangTool::~ClangTool() = default;
449
450
9.69k
void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
451
9.69k
  MappedFileContents.push_back(std::make_pair(FilePath, Content));
452
9.69k
}
453
454
1.04k
void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
455
1.04k
  ArgsAdjuster = combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
456
1.04k
}
457
458
15
void ClangTool::clearArgumentsAdjusters() {
459
15
  ArgsAdjuster = nullptr;
460
15
}
461
462
static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
463
343
                              void *MainAddr) {
464
  // Allow users to override the resource dir.
465
343
  for (StringRef Arg : Args)
466
1.17k
    if (Arg.startswith("-resource-dir"))
467
0
      return;
468
469
  // If there's no override in place add our resource dir.
470
343
  Args = getInsertArgumentAdjuster(
471
343
      ("-resource-dir=" + CompilerInvocation::GetResourcesPath(Argv0, MainAddr))
472
343
          .c_str())(Args, "");
473
343
}
474
475
338
int ClangTool::run(ToolAction *Action) {
476
  // Exists solely for the purpose of lookup of the resource path.
477
  // This just needs to be some symbol in the binary.
478
338
  static int StaticSymbol;
479
480
  // First insert all absolute paths into the in-memory VFS. These are global
481
  // for all compile commands.
482
338
  if (SeenWorkingDirectories.insert("/").second)
483
267
    for (const auto &MappedFile : MappedFileContents)
484
9.48k
      if (llvm::sys::path::is_absolute(MappedFile.first))
485
13
        InMemoryFileSystem->addFile(
486
13
            MappedFile.first, 0,
487
13
            llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
488
489
338
  bool ProcessingFailed = false;
490
338
  bool FileSkipped = false;
491
  // Compute all absolute paths before we run any actions, as those will change
492
  // the working directory.
493
338
  std::vector<std::string> AbsolutePaths;
494
338
  AbsolutePaths.reserve(SourcePaths.size());
495
343
  for (const auto &SourcePath : SourcePaths) {
496
343
    auto AbsPath = getAbsolutePath(*OverlayFileSystem, SourcePath);
497
343
    if (!AbsPath) {
498
0
      llvm::errs() << "Skipping " << SourcePath
499
0
                   << ". Error while getting an absolute path: "
500
0
                   << llvm::toString(AbsPath.takeError()) << "\n";
501
0
      continue;
502
0
    }
503
343
    AbsolutePaths.push_back(std::move(*AbsPath));
504
343
  }
505
506
  // Remember the working directory in case we need to restore it.
507
338
  std::string InitialWorkingDir;
508
338
  if (RestoreCWD) {
509
338
    if (auto CWD = OverlayFileSystem->getCurrentWorkingDirectory()) {
510
338
      InitialWorkingDir = std::move(*CWD);
511
338
    } else {
512
0
      llvm::errs() << "Could not get working directory: "
513
0
                   << CWD.getError().message() << "\n";
514
0
    }
515
338
  }
516
517
343
  for (llvm::StringRef File : AbsolutePaths) {
518
    // Currently implementations of CompilationDatabase::getCompileCommands can
519
    // change the state of the file system (e.g.  prepare generated headers), so
520
    // this method needs to run right before we invoke the tool, as the next
521
    // file may require a different (incompatible) state of the file system.
522
    //
523
    // FIXME: Make the compilation database interface more explicit about the
524
    // requirements to the order of invocation of its members.
525
343
    std::vector<CompileCommand> CompileCommandsForFile =
526
343
        Compilations.getCompileCommands(File);
527
343
    if (CompileCommandsForFile.empty()) {
528
0
      llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
529
0
      FileSkipped = true;
530
0
      continue;
531
0
    }
532
343
    for (CompileCommand &CompileCommand : CompileCommandsForFile) {
533
      // FIXME: chdir is thread hostile; on the other hand, creating the same
534
      // behavior as chdir is complex: chdir resolves the path once, thus
535
      // guaranteeing that all subsequent relative path operations work
536
      // on the same path the original chdir resulted in. This makes a
537
      // difference for example on network filesystems, where symlinks might be
538
      // switched during runtime of the tool. Fixing this depends on having a
539
      // file system abstraction that allows openat() style interactions.
540
343
      if (OverlayFileSystem->setCurrentWorkingDirectory(
541
343
              CompileCommand.Directory))
542
0
        llvm::report_fatal_error("Cannot chdir into \"" +
543
0
                                 Twine(CompileCommand.Directory) + "\"!");
544
545
      // Now fill the in-memory VFS with the relative file mappings so it will
546
      // have the correct relative paths. We never remove mappings but that
547
      // should be fine.
548
343
      if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
549
255
        for (const auto &MappedFile : MappedFileContents)
550
9.97k
          if (!llvm::sys::path::is_absolute(MappedFile.first))
551
9.89k
            InMemoryFileSystem->addFile(
552
9.89k
                MappedFile.first, 0,
553
9.89k
                llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
554
555
343
      std::vector<std::string> CommandLine = CompileCommand.CommandLine;
556
343
      if (ArgsAdjuster)
557
337
        CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
558
343
      assert(!CommandLine.empty());
559
560
      // Add the resource dir based on the binary of this tool. argv[0] in the
561
      // compilation database may refer to a different compiler and we want to
562
      // pick up the very same standard library that compiler is using. The
563
      // builtin headers in the resource dir need to match the exact clang
564
      // version the tool is using.
565
      // FIXME: On linux, GetMainExecutable is independent of the value of the
566
      // first argument, thus allowing ClangTool and runToolOnCode to just
567
      // pass in made-up names here. Make sure this works on other platforms.
568
0
      injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
569
570
      // FIXME: We need a callback mechanism for the tool writer to output a
571
      // customized message for each file.
572
343
      LLVM_DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
573
343
      ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
574
343
                                PCHContainerOps);
575
343
      Invocation.setDiagnosticConsumer(DiagConsumer);
576
577
343
      if (!Invocation.run()) {
578
        // FIXME: Diagnostics should be used instead.
579
17
        if (PrintErrorMessage)
580
17
          llvm::errs() << "Error while processing " << File << ".\n";
581
17
        ProcessingFailed = true;
582
17
      }
583
343
    }
584
343
  }
585
586
338
  if (!InitialWorkingDir.empty()) {
587
338
    if (auto EC =
588
338
            OverlayFileSystem->setCurrentWorkingDirectory(InitialWorkingDir))
589
0
      llvm::errs() << "Error when trying to restore working dir: "
590
0
                   << EC.message() << "\n";
591
338
  }
592
338
  return ProcessingFailed ? 
117
:
(321
FileSkipped321
?
20
:
0321
);
593
338
}
594
595
namespace {
596
597
class ASTBuilderAction : public ToolAction {
598
  std::vector<std::unique_ptr<ASTUnit>> &ASTs;
599
600
public:
601
7.31k
  ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
602
603
  bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
604
                     FileManager *Files,
605
                     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
606
7.31k
                     DiagnosticConsumer *DiagConsumer) override {
607
7.31k
    std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
608
7.31k
        Invocation, std::move(PCHContainerOps),
609
7.31k
        CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
610
7.31k
                                            DiagConsumer,
611
7.31k
                                            /*ShouldOwnClient=*/false),
612
7.31k
        Files);
613
7.31k
    if (!AST)
614
0
      return false;
615
616
7.31k
    ASTs.push_back(std::move(AST));
617
7.31k
    return true;
618
7.31k
  }
619
};
620
621
} // namespace
622
623
19
int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
624
19
  ASTBuilderAction Action(ASTs);
625
19
  return run(&Action);
626
19
}
627
628
0
void ClangTool::setRestoreWorkingDir(bool RestoreCWD) {
629
0
  this->RestoreCWD = RestoreCWD;
630
0
}
631
632
0
void ClangTool::setPrintErrorMessage(bool PrintErrorMessage) {
633
0
  this->PrintErrorMessage = PrintErrorMessage;
634
0
}
635
636
namespace clang {
637
namespace tooling {
638
639
std::unique_ptr<ASTUnit>
640
buildASTFromCode(StringRef Code, StringRef FileName,
641
209
                 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
642
209
  return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
643
209
                                  "clang-tool", std::move(PCHContainerOps));
644
209
}
645
646
std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
647
    StringRef Code, const std::vector<std::string> &Args, StringRef FileName,
648
    StringRef ToolName, std::shared_ptr<PCHContainerOperations> PCHContainerOps,
649
    ArgumentsAdjuster Adjuster, const FileContentMappings &VirtualMappedFiles,
650
7.29k
    DiagnosticConsumer *DiagConsumer) {
651
7.29k
  std::vector<std::unique_ptr<ASTUnit>> ASTs;
652
7.29k
  ASTBuilderAction Action(ASTs);
653
7.29k
  llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
654
7.29k
      new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
655
7.29k
  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
656
7.29k
      new llvm::vfs::InMemoryFileSystem);
657
7.29k
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
658
7.29k
  llvm::IntrusiveRefCntPtr<FileManager> Files(
659
7.29k
      new FileManager(FileSystemOptions(), OverlayFileSystem));
660
661
7.29k
  ToolInvocation Invocation(
662
7.29k
      getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileName), FileName),
663
7.29k
      &Action, Files.get(), std::move(PCHContainerOps));
664
7.29k
  Invocation.setDiagnosticConsumer(DiagConsumer);
665
666
7.29k
  InMemoryFileSystem->addFile(FileName, 0,
667
7.29k
                              llvm::MemoryBuffer::getMemBufferCopy(Code));
668
7.29k
  for (auto &FilenameWithContent : VirtualMappedFiles) {
669
2.44k
    InMemoryFileSystem->addFile(
670
2.44k
        FilenameWithContent.first, 0,
671
2.44k
        llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
672
2.44k
  }
673
674
7.29k
  if (!Invocation.run())
675
0
    return nullptr;
676
 
677
7.29k
  assert(ASTs.size() == 1);
678
0
  return std::move(ASTs[0]);
679
7.29k
}
680
681
} // namespace tooling
682
} // namespace clang