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