xref: /aosp_15_r20/external/clang/lib/Tooling/Tooling.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- Tooling.cpp - Running clang standalone tools ---------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li //  This file implements functions to run clang tools standalone instead
11*67e74705SXin Li //  of running them as a plugin.
12*67e74705SXin Li //
13*67e74705SXin Li //===----------------------------------------------------------------------===//
14*67e74705SXin Li 
15*67e74705SXin Li #include "clang/Tooling/Tooling.h"
16*67e74705SXin Li #include "clang/AST/ASTConsumer.h"
17*67e74705SXin Li #include "clang/Driver/Compilation.h"
18*67e74705SXin Li #include "clang/Driver/Driver.h"
19*67e74705SXin Li #include "clang/Driver/Tool.h"
20*67e74705SXin Li #include "clang/Driver/ToolChain.h"
21*67e74705SXin Li #include "clang/Frontend/ASTUnit.h"
22*67e74705SXin Li #include "clang/Frontend/CompilerInstance.h"
23*67e74705SXin Li #include "clang/Frontend/FrontendDiagnostic.h"
24*67e74705SXin Li #include "clang/Frontend/TextDiagnosticPrinter.h"
25*67e74705SXin Li #include "clang/Tooling/ArgumentsAdjusters.h"
26*67e74705SXin Li #include "clang/Tooling/CompilationDatabase.h"
27*67e74705SXin Li #include "llvm/ADT/STLExtras.h"
28*67e74705SXin Li #include "llvm/Config/llvm-config.h"
29*67e74705SXin Li #include "llvm/Option/Option.h"
30*67e74705SXin Li #include "llvm/Support/Debug.h"
31*67e74705SXin Li #include "llvm/Support/FileSystem.h"
32*67e74705SXin Li #include "llvm/Support/Host.h"
33*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
34*67e74705SXin Li #include <utility>
35*67e74705SXin Li 
36*67e74705SXin Li #define DEBUG_TYPE "clang-tooling"
37*67e74705SXin Li 
38*67e74705SXin Li namespace clang {
39*67e74705SXin Li namespace tooling {
40*67e74705SXin Li 
~ToolAction()41*67e74705SXin Li ToolAction::~ToolAction() {}
42*67e74705SXin Li 
~FrontendActionFactory()43*67e74705SXin Li FrontendActionFactory::~FrontendActionFactory() {}
44*67e74705SXin Li 
45*67e74705SXin Li // FIXME: This file contains structural duplication with other parts of the
46*67e74705SXin Li // code that sets up a compiler to run tools on it, and we should refactor
47*67e74705SXin Li // it to be based on the same framework.
48*67e74705SXin Li 
49*67e74705SXin Li /// \brief Builds a clang driver initialized for running clang tools.
newDriver(clang::DiagnosticsEngine * Diagnostics,const char * BinaryName,IntrusiveRefCntPtr<vfs::FileSystem> VFS)50*67e74705SXin Li static clang::driver::Driver *newDriver(
51*67e74705SXin Li     clang::DiagnosticsEngine *Diagnostics, const char *BinaryName,
52*67e74705SXin Li     IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
53*67e74705SXin Li   clang::driver::Driver *CompilerDriver =
54*67e74705SXin Li       new clang::driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
55*67e74705SXin Li                                 *Diagnostics, std::move(VFS));
56*67e74705SXin Li   CompilerDriver->setTitle("clang_based_tool");
57*67e74705SXin Li   return CompilerDriver;
58*67e74705SXin Li }
59*67e74705SXin Li 
60*67e74705SXin Li /// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
61*67e74705SXin Li ///
62*67e74705SXin Li /// Returns NULL on error.
getCC1Arguments(clang::DiagnosticsEngine * Diagnostics,clang::driver::Compilation * Compilation)63*67e74705SXin Li static const llvm::opt::ArgStringList *getCC1Arguments(
64*67e74705SXin Li     clang::DiagnosticsEngine *Diagnostics,
65*67e74705SXin Li     clang::driver::Compilation *Compilation) {
66*67e74705SXin Li   // We expect to get back exactly one Command job, if we didn't something
67*67e74705SXin Li   // failed. Extract that job from the Compilation.
68*67e74705SXin Li   const clang::driver::JobList &Jobs = Compilation->getJobs();
69*67e74705SXin Li   if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
70*67e74705SXin Li     SmallString<256> error_msg;
71*67e74705SXin Li     llvm::raw_svector_ostream error_stream(error_msg);
72*67e74705SXin Li     Jobs.Print(error_stream, "; ", true);
73*67e74705SXin Li     Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
74*67e74705SXin Li         << error_stream.str();
75*67e74705SXin Li     return nullptr;
76*67e74705SXin Li   }
77*67e74705SXin Li 
78*67e74705SXin Li   // The one job we find should be to invoke clang again.
79*67e74705SXin Li   const clang::driver::Command &Cmd =
80*67e74705SXin Li       cast<clang::driver::Command>(*Jobs.begin());
81*67e74705SXin Li   if (StringRef(Cmd.getCreator().getName()) != "clang") {
82*67e74705SXin Li     Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
83*67e74705SXin Li     return nullptr;
84*67e74705SXin Li   }
85*67e74705SXin Li 
86*67e74705SXin Li   return &Cmd.getArguments();
87*67e74705SXin Li }
88*67e74705SXin Li 
89*67e74705SXin Li /// \brief Returns a clang build invocation initialized from the CC1 flags.
newInvocation(clang::DiagnosticsEngine * Diagnostics,const llvm::opt::ArgStringList & CC1Args)90*67e74705SXin Li clang::CompilerInvocation *newInvocation(
91*67e74705SXin Li     clang::DiagnosticsEngine *Diagnostics,
92*67e74705SXin Li     const llvm::opt::ArgStringList &CC1Args) {
93*67e74705SXin Li   assert(!CC1Args.empty() && "Must at least contain the program name!");
94*67e74705SXin Li   clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
95*67e74705SXin Li   clang::CompilerInvocation::CreateFromArgs(
96*67e74705SXin Li       *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
97*67e74705SXin Li       *Diagnostics);
98*67e74705SXin Li   Invocation->getFrontendOpts().DisableFree = false;
99*67e74705SXin Li   Invocation->getCodeGenOpts().DisableFree = false;
100*67e74705SXin Li   Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
101*67e74705SXin Li   return Invocation;
102*67e74705SXin Li }
103*67e74705SXin Li 
runToolOnCode(clang::FrontendAction * ToolAction,const Twine & Code,const Twine & FileName,std::shared_ptr<PCHContainerOperations> PCHContainerOps)104*67e74705SXin Li bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
105*67e74705SXin Li                    const Twine &FileName,
106*67e74705SXin Li                    std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
107*67e74705SXin Li   return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
108*67e74705SXin Li                                FileName, "clang-tool",
109*67e74705SXin Li                                std::move(PCHContainerOps));
110*67e74705SXin Li }
111*67e74705SXin Li 
112*67e74705SXin Li static std::vector<std::string>
getSyntaxOnlyToolArgs(const Twine & ToolName,const std::vector<std::string> & ExtraArgs,StringRef FileName)113*67e74705SXin Li getSyntaxOnlyToolArgs(const Twine &ToolName,
114*67e74705SXin Li                       const std::vector<std::string> &ExtraArgs,
115*67e74705SXin Li                       StringRef FileName) {
116*67e74705SXin Li   std::vector<std::string> Args;
117*67e74705SXin Li   Args.push_back(ToolName.str());
118*67e74705SXin Li   Args.push_back("-fsyntax-only");
119*67e74705SXin Li   Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
120*67e74705SXin Li   Args.push_back(FileName.str());
121*67e74705SXin Li   return Args;
122*67e74705SXin Li }
123*67e74705SXin Li 
runToolOnCodeWithArgs(clang::FrontendAction * ToolAction,const Twine & Code,const std::vector<std::string> & Args,const Twine & FileName,const Twine & ToolName,std::shared_ptr<PCHContainerOperations> PCHContainerOps,const FileContentMappings & VirtualMappedFiles)124*67e74705SXin Li bool runToolOnCodeWithArgs(
125*67e74705SXin Li     clang::FrontendAction *ToolAction, const Twine &Code,
126*67e74705SXin Li     const std::vector<std::string> &Args, const Twine &FileName,
127*67e74705SXin Li     const Twine &ToolName,
128*67e74705SXin Li     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
129*67e74705SXin Li     const FileContentMappings &VirtualMappedFiles) {
130*67e74705SXin Li 
131*67e74705SXin Li   SmallString<16> FileNameStorage;
132*67e74705SXin Li   StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
133*67e74705SXin Li   llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
134*67e74705SXin Li       new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
135*67e74705SXin Li   llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
136*67e74705SXin Li       new vfs::InMemoryFileSystem);
137*67e74705SXin Li   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
138*67e74705SXin Li   llvm::IntrusiveRefCntPtr<FileManager> Files(
139*67e74705SXin Li       new FileManager(FileSystemOptions(), OverlayFileSystem));
140*67e74705SXin Li   ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
141*67e74705SXin Li                             ToolAction, Files.get(),
142*67e74705SXin Li                             std::move(PCHContainerOps));
143*67e74705SXin Li 
144*67e74705SXin Li   SmallString<1024> CodeStorage;
145*67e74705SXin Li   InMemoryFileSystem->addFile(FileNameRef, 0,
146*67e74705SXin Li                               llvm::MemoryBuffer::getMemBuffer(
147*67e74705SXin Li                                   Code.toNullTerminatedStringRef(CodeStorage)));
148*67e74705SXin Li 
149*67e74705SXin Li   for (auto &FilenameWithContent : VirtualMappedFiles) {
150*67e74705SXin Li     InMemoryFileSystem->addFile(
151*67e74705SXin Li         FilenameWithContent.first, 0,
152*67e74705SXin Li         llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
153*67e74705SXin Li   }
154*67e74705SXin Li 
155*67e74705SXin Li   return Invocation.run();
156*67e74705SXin Li }
157*67e74705SXin Li 
getAbsolutePath(StringRef File)158*67e74705SXin Li std::string getAbsolutePath(StringRef File) {
159*67e74705SXin Li   StringRef RelativePath(File);
160*67e74705SXin Li   // FIXME: Should '.\\' be accepted on Win32?
161*67e74705SXin Li   if (RelativePath.startswith("./")) {
162*67e74705SXin Li     RelativePath = RelativePath.substr(strlen("./"));
163*67e74705SXin Li   }
164*67e74705SXin Li 
165*67e74705SXin Li   SmallString<1024> AbsolutePath = RelativePath;
166*67e74705SXin Li   std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
167*67e74705SXin Li   assert(!EC);
168*67e74705SXin Li   (void)EC;
169*67e74705SXin Li   llvm::sys::path::native(AbsolutePath);
170*67e74705SXin Li   return AbsolutePath.str();
171*67e74705SXin Li }
172*67e74705SXin Li 
addTargetAndModeForProgramName(std::vector<std::string> & CommandLine,StringRef InvokedAs)173*67e74705SXin Li void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
174*67e74705SXin Li                                     StringRef InvokedAs) {
175*67e74705SXin Li   if (!CommandLine.empty() && !InvokedAs.empty()) {
176*67e74705SXin Li     bool AlreadyHasTarget = false;
177*67e74705SXin Li     bool AlreadyHasMode = false;
178*67e74705SXin Li     // Skip CommandLine[0].
179*67e74705SXin Li     for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
180*67e74705SXin Li          ++Token) {
181*67e74705SXin Li       StringRef TokenRef(*Token);
182*67e74705SXin Li       AlreadyHasTarget |=
183*67e74705SXin Li           (TokenRef == "-target" || TokenRef.startswith("-target="));
184*67e74705SXin Li       AlreadyHasMode |= (TokenRef == "--driver-mode" ||
185*67e74705SXin Li                          TokenRef.startswith("--driver-mode="));
186*67e74705SXin Li     }
187*67e74705SXin Li     auto TargetMode =
188*67e74705SXin Li         clang::driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
189*67e74705SXin Li     if (!AlreadyHasMode && !TargetMode.second.empty()) {
190*67e74705SXin Li       CommandLine.insert(++CommandLine.begin(), TargetMode.second);
191*67e74705SXin Li     }
192*67e74705SXin Li     if (!AlreadyHasTarget && !TargetMode.first.empty()) {
193*67e74705SXin Li       CommandLine.insert(++CommandLine.begin(), {"-target", TargetMode.first});
194*67e74705SXin Li     }
195*67e74705SXin Li   }
196*67e74705SXin Li }
197*67e74705SXin Li 
198*67e74705SXin Li namespace {
199*67e74705SXin Li 
200*67e74705SXin Li class SingleFrontendActionFactory : public FrontendActionFactory {
201*67e74705SXin Li   FrontendAction *Action;
202*67e74705SXin Li 
203*67e74705SXin Li public:
SingleFrontendActionFactory(FrontendAction * Action)204*67e74705SXin Li   SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
205*67e74705SXin Li 
create()206*67e74705SXin Li   FrontendAction *create() override { return Action; }
207*67e74705SXin Li };
208*67e74705SXin Li 
209*67e74705SXin Li }
210*67e74705SXin Li 
ToolInvocation(std::vector<std::string> CommandLine,ToolAction * Action,FileManager * Files,std::shared_ptr<PCHContainerOperations> PCHContainerOps)211*67e74705SXin Li ToolInvocation::ToolInvocation(
212*67e74705SXin Li     std::vector<std::string> CommandLine, ToolAction *Action,
213*67e74705SXin Li     FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
214*67e74705SXin Li     : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
215*67e74705SXin Li       Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
216*67e74705SXin Li       DiagConsumer(nullptr) {}
217*67e74705SXin Li 
ToolInvocation(std::vector<std::string> CommandLine,FrontendAction * FAction,FileManager * Files,std::shared_ptr<PCHContainerOperations> PCHContainerOps)218*67e74705SXin Li ToolInvocation::ToolInvocation(
219*67e74705SXin Li     std::vector<std::string> CommandLine, FrontendAction *FAction,
220*67e74705SXin Li     FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
221*67e74705SXin Li     : CommandLine(std::move(CommandLine)),
222*67e74705SXin Li       Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
223*67e74705SXin Li       Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
224*67e74705SXin Li       DiagConsumer(nullptr) {}
225*67e74705SXin Li 
~ToolInvocation()226*67e74705SXin Li ToolInvocation::~ToolInvocation() {
227*67e74705SXin Li   if (OwnsAction)
228*67e74705SXin Li     delete Action;
229*67e74705SXin Li }
230*67e74705SXin Li 
mapVirtualFile(StringRef FilePath,StringRef Content)231*67e74705SXin Li void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
232*67e74705SXin Li   SmallString<1024> PathStorage;
233*67e74705SXin Li   llvm::sys::path::native(FilePath, PathStorage);
234*67e74705SXin Li   MappedFileContents[PathStorage] = Content;
235*67e74705SXin Li }
236*67e74705SXin Li 
run()237*67e74705SXin Li bool ToolInvocation::run() {
238*67e74705SXin Li   std::vector<const char*> Argv;
239*67e74705SXin Li   for (const std::string &Str : CommandLine)
240*67e74705SXin Li     Argv.push_back(Str.c_str());
241*67e74705SXin Li   const char *const BinaryName = Argv[0];
242*67e74705SXin Li   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
243*67e74705SXin Li   TextDiagnosticPrinter DiagnosticPrinter(
244*67e74705SXin Li       llvm::errs(), &*DiagOpts);
245*67e74705SXin Li   DiagnosticsEngine Diagnostics(
246*67e74705SXin Li       IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
247*67e74705SXin Li       DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
248*67e74705SXin Li 
249*67e74705SXin Li   const std::unique_ptr<clang::driver::Driver> Driver(
250*67e74705SXin Li       newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
251*67e74705SXin Li   // Since the input might only be virtual, don't check whether it exists.
252*67e74705SXin Li   Driver->setCheckInputsExist(false);
253*67e74705SXin Li   const std::unique_ptr<clang::driver::Compilation> Compilation(
254*67e74705SXin Li       Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
255*67e74705SXin Li   const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
256*67e74705SXin Li       &Diagnostics, Compilation.get());
257*67e74705SXin Li   if (!CC1Args) {
258*67e74705SXin Li     return false;
259*67e74705SXin Li   }
260*67e74705SXin Li   std::unique_ptr<clang::CompilerInvocation> Invocation(
261*67e74705SXin Li       newInvocation(&Diagnostics, *CC1Args));
262*67e74705SXin Li   // FIXME: remove this when all users have migrated!
263*67e74705SXin Li   for (const auto &It : MappedFileContents) {
264*67e74705SXin Li     // Inject the code as the given file name into the preprocessor options.
265*67e74705SXin Li     std::unique_ptr<llvm::MemoryBuffer> Input =
266*67e74705SXin Li         llvm::MemoryBuffer::getMemBuffer(It.getValue());
267*67e74705SXin Li     Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
268*67e74705SXin Li                                                       Input.release());
269*67e74705SXin Li   }
270*67e74705SXin Li   return runInvocation(BinaryName, Compilation.get(), Invocation.release(),
271*67e74705SXin Li                        std::move(PCHContainerOps));
272*67e74705SXin Li }
273*67e74705SXin Li 
runInvocation(const char * BinaryName,clang::driver::Compilation * Compilation,clang::CompilerInvocation * Invocation,std::shared_ptr<PCHContainerOperations> PCHContainerOps)274*67e74705SXin Li bool ToolInvocation::runInvocation(
275*67e74705SXin Li     const char *BinaryName, clang::driver::Compilation *Compilation,
276*67e74705SXin Li     clang::CompilerInvocation *Invocation,
277*67e74705SXin Li     std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
278*67e74705SXin Li   // Show the invocation, with -v.
279*67e74705SXin Li   if (Invocation->getHeaderSearchOpts().Verbose) {
280*67e74705SXin Li     llvm::errs() << "clang Invocation:\n";
281*67e74705SXin Li     Compilation->getJobs().Print(llvm::errs(), "\n", true);
282*67e74705SXin Li     llvm::errs() << "\n";
283*67e74705SXin Li   }
284*67e74705SXin Li 
285*67e74705SXin Li   return Action->runInvocation(Invocation, Files, std::move(PCHContainerOps),
286*67e74705SXin Li                                DiagConsumer);
287*67e74705SXin Li }
288*67e74705SXin Li 
runInvocation(CompilerInvocation * Invocation,FileManager * Files,std::shared_ptr<PCHContainerOperations> PCHContainerOps,DiagnosticConsumer * DiagConsumer)289*67e74705SXin Li bool FrontendActionFactory::runInvocation(
290*67e74705SXin Li     CompilerInvocation *Invocation, FileManager *Files,
291*67e74705SXin Li     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
292*67e74705SXin Li     DiagnosticConsumer *DiagConsumer) {
293*67e74705SXin Li   // Create a compiler instance to handle the actual work.
294*67e74705SXin Li   clang::CompilerInstance Compiler(std::move(PCHContainerOps));
295*67e74705SXin Li   Compiler.setInvocation(Invocation);
296*67e74705SXin Li   Compiler.setFileManager(Files);
297*67e74705SXin Li 
298*67e74705SXin Li   // The FrontendAction can have lifetime requirements for Compiler or its
299*67e74705SXin Li   // members, and we need to ensure it's deleted earlier than Compiler. So we
300*67e74705SXin Li   // pass it to an std::unique_ptr declared after the Compiler variable.
301*67e74705SXin Li   std::unique_ptr<FrontendAction> ScopedToolAction(create());
302*67e74705SXin Li 
303*67e74705SXin Li   // Create the compiler's actual diagnostics engine.
304*67e74705SXin Li   Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
305*67e74705SXin Li   if (!Compiler.hasDiagnostics())
306*67e74705SXin Li     return false;
307*67e74705SXin Li 
308*67e74705SXin Li   Compiler.createSourceManager(*Files);
309*67e74705SXin Li 
310*67e74705SXin Li   const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
311*67e74705SXin Li 
312*67e74705SXin Li   Files->clearStatCaches();
313*67e74705SXin Li   return Success;
314*67e74705SXin Li }
315*67e74705SXin Li 
ClangTool(const CompilationDatabase & Compilations,ArrayRef<std::string> SourcePaths,std::shared_ptr<PCHContainerOperations> PCHContainerOps)316*67e74705SXin Li ClangTool::ClangTool(const CompilationDatabase &Compilations,
317*67e74705SXin Li                      ArrayRef<std::string> SourcePaths,
318*67e74705SXin Li                      std::shared_ptr<PCHContainerOperations> PCHContainerOps)
319*67e74705SXin Li     : Compilations(Compilations), SourcePaths(SourcePaths),
320*67e74705SXin Li       PCHContainerOps(std::move(PCHContainerOps)),
321*67e74705SXin Li       OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
322*67e74705SXin Li       InMemoryFileSystem(new vfs::InMemoryFileSystem),
323*67e74705SXin Li       Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
324*67e74705SXin Li       DiagConsumer(nullptr) {
325*67e74705SXin Li   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
326*67e74705SXin Li   appendArgumentsAdjuster(getClangStripOutputAdjuster());
327*67e74705SXin Li   appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
328*67e74705SXin Li }
329*67e74705SXin Li 
~ClangTool()330*67e74705SXin Li ClangTool::~ClangTool() {}
331*67e74705SXin Li 
mapVirtualFile(StringRef FilePath,StringRef Content)332*67e74705SXin Li void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
333*67e74705SXin Li   MappedFileContents.push_back(std::make_pair(FilePath, Content));
334*67e74705SXin Li }
335*67e74705SXin Li 
appendArgumentsAdjuster(ArgumentsAdjuster Adjuster)336*67e74705SXin Li void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
337*67e74705SXin Li   if (ArgsAdjuster)
338*67e74705SXin Li     ArgsAdjuster =
339*67e74705SXin Li         combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
340*67e74705SXin Li   else
341*67e74705SXin Li     ArgsAdjuster = std::move(Adjuster);
342*67e74705SXin Li }
343*67e74705SXin Li 
clearArgumentsAdjusters()344*67e74705SXin Li void ClangTool::clearArgumentsAdjusters() {
345*67e74705SXin Li   ArgsAdjuster = nullptr;
346*67e74705SXin Li }
347*67e74705SXin Li 
injectResourceDir(CommandLineArguments & Args,const char * Argv0,void * MainAddr)348*67e74705SXin Li static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
349*67e74705SXin Li                               void *MainAddr) {
350*67e74705SXin Li   // Allow users to override the resource dir.
351*67e74705SXin Li   for (StringRef Arg : Args)
352*67e74705SXin Li     if (Arg.startswith("-resource-dir"))
353*67e74705SXin Li       return;
354*67e74705SXin Li 
355*67e74705SXin Li   // If there's no override in place add our resource dir.
356*67e74705SXin Li   Args.push_back("-resource-dir=" +
357*67e74705SXin Li                  CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
358*67e74705SXin Li }
359*67e74705SXin Li 
run(ToolAction * Action)360*67e74705SXin Li int ClangTool::run(ToolAction *Action) {
361*67e74705SXin Li   // Exists solely for the purpose of lookup of the resource path.
362*67e74705SXin Li   // This just needs to be some symbol in the binary.
363*67e74705SXin Li   static int StaticSymbol;
364*67e74705SXin Li 
365*67e74705SXin Li   llvm::SmallString<128> InitialDirectory;
366*67e74705SXin Li   if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
367*67e74705SXin Li     llvm::report_fatal_error("Cannot detect current path: " +
368*67e74705SXin Li                              Twine(EC.message()));
369*67e74705SXin Li 
370*67e74705SXin Li   // First insert all absolute paths into the in-memory VFS. These are global
371*67e74705SXin Li   // for all compile commands.
372*67e74705SXin Li   if (SeenWorkingDirectories.insert("/").second)
373*67e74705SXin Li     for (const auto &MappedFile : MappedFileContents)
374*67e74705SXin Li       if (llvm::sys::path::is_absolute(MappedFile.first))
375*67e74705SXin Li         InMemoryFileSystem->addFile(
376*67e74705SXin Li             MappedFile.first, 0,
377*67e74705SXin Li             llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
378*67e74705SXin Li 
379*67e74705SXin Li   bool ProcessingFailed = false;
380*67e74705SXin Li   for (const auto &SourcePath : SourcePaths) {
381*67e74705SXin Li     std::string File(getAbsolutePath(SourcePath));
382*67e74705SXin Li 
383*67e74705SXin Li     // Currently implementations of CompilationDatabase::getCompileCommands can
384*67e74705SXin Li     // change the state of the file system (e.g.  prepare generated headers), so
385*67e74705SXin Li     // this method needs to run right before we invoke the tool, as the next
386*67e74705SXin Li     // file may require a different (incompatible) state of the file system.
387*67e74705SXin Li     //
388*67e74705SXin Li     // FIXME: Make the compilation database interface more explicit about the
389*67e74705SXin Li     // requirements to the order of invocation of its members.
390*67e74705SXin Li     std::vector<CompileCommand> CompileCommandsForFile =
391*67e74705SXin Li         Compilations.getCompileCommands(File);
392*67e74705SXin Li     if (CompileCommandsForFile.empty()) {
393*67e74705SXin Li       // FIXME: There are two use cases here: doing a fuzzy
394*67e74705SXin Li       // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
395*67e74705SXin Li       // about the .cc files that were not found, and the use case where I
396*67e74705SXin Li       // specify all files I want to run over explicitly, where this should
397*67e74705SXin Li       // be an error. We'll want to add an option for this.
398*67e74705SXin Li       llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
399*67e74705SXin Li       continue;
400*67e74705SXin Li     }
401*67e74705SXin Li     for (CompileCommand &CompileCommand : CompileCommandsForFile) {
402*67e74705SXin Li       // FIXME: chdir is thread hostile; on the other hand, creating the same
403*67e74705SXin Li       // behavior as chdir is complex: chdir resolves the path once, thus
404*67e74705SXin Li       // guaranteeing that all subsequent relative path operations work
405*67e74705SXin Li       // on the same path the original chdir resulted in. This makes a
406*67e74705SXin Li       // difference for example on network filesystems, where symlinks might be
407*67e74705SXin Li       // switched during runtime of the tool. Fixing this depends on having a
408*67e74705SXin Li       // file system abstraction that allows openat() style interactions.
409*67e74705SXin Li       if (OverlayFileSystem->setCurrentWorkingDirectory(
410*67e74705SXin Li               CompileCommand.Directory))
411*67e74705SXin Li         llvm::report_fatal_error("Cannot chdir into \"" +
412*67e74705SXin Li                                  Twine(CompileCommand.Directory) + "\n!");
413*67e74705SXin Li 
414*67e74705SXin Li       // Now fill the in-memory VFS with the relative file mappings so it will
415*67e74705SXin Li       // have the correct relative paths. We never remove mappings but that
416*67e74705SXin Li       // should be fine.
417*67e74705SXin Li       if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
418*67e74705SXin Li         for (const auto &MappedFile : MappedFileContents)
419*67e74705SXin Li           if (!llvm::sys::path::is_absolute(MappedFile.first))
420*67e74705SXin Li             InMemoryFileSystem->addFile(
421*67e74705SXin Li                 MappedFile.first, 0,
422*67e74705SXin Li                 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
423*67e74705SXin Li 
424*67e74705SXin Li       std::vector<std::string> CommandLine = CompileCommand.CommandLine;
425*67e74705SXin Li       if (ArgsAdjuster)
426*67e74705SXin Li         CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
427*67e74705SXin Li       assert(!CommandLine.empty());
428*67e74705SXin Li 
429*67e74705SXin Li       // Add the resource dir based on the binary of this tool. argv[0] in the
430*67e74705SXin Li       // compilation database may refer to a different compiler and we want to
431*67e74705SXin Li       // pick up the very same standard library that compiler is using. The
432*67e74705SXin Li       // builtin headers in the resource dir need to match the exact clang
433*67e74705SXin Li       // version the tool is using.
434*67e74705SXin Li       // FIXME: On linux, GetMainExecutable is independent of the value of the
435*67e74705SXin Li       // first argument, thus allowing ClangTool and runToolOnCode to just
436*67e74705SXin Li       // pass in made-up names here. Make sure this works on other platforms.
437*67e74705SXin Li       injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
438*67e74705SXin Li 
439*67e74705SXin Li       // FIXME: We need a callback mechanism for the tool writer to output a
440*67e74705SXin Li       // customized message for each file.
441*67e74705SXin Li       DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
442*67e74705SXin Li       ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
443*67e74705SXin Li                                 PCHContainerOps);
444*67e74705SXin Li       Invocation.setDiagnosticConsumer(DiagConsumer);
445*67e74705SXin Li 
446*67e74705SXin Li       if (!Invocation.run()) {
447*67e74705SXin Li         // FIXME: Diagnostics should be used instead.
448*67e74705SXin Li         llvm::errs() << "Error while processing " << File << ".\n";
449*67e74705SXin Li         ProcessingFailed = true;
450*67e74705SXin Li       }
451*67e74705SXin Li       // Return to the initial directory to correctly resolve next file by
452*67e74705SXin Li       // relative path.
453*67e74705SXin Li       if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
454*67e74705SXin Li         llvm::report_fatal_error("Cannot chdir into \"" +
455*67e74705SXin Li                                  Twine(InitialDirectory) + "\n!");
456*67e74705SXin Li     }
457*67e74705SXin Li   }
458*67e74705SXin Li   return ProcessingFailed ? 1 : 0;
459*67e74705SXin Li }
460*67e74705SXin Li 
461*67e74705SXin Li namespace {
462*67e74705SXin Li 
463*67e74705SXin Li class ASTBuilderAction : public ToolAction {
464*67e74705SXin Li   std::vector<std::unique_ptr<ASTUnit>> &ASTs;
465*67e74705SXin Li 
466*67e74705SXin Li public:
ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> & ASTs)467*67e74705SXin Li   ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
468*67e74705SXin Li 
runInvocation(CompilerInvocation * Invocation,FileManager * Files,std::shared_ptr<PCHContainerOperations> PCHContainerOps,DiagnosticConsumer * DiagConsumer)469*67e74705SXin Li   bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
470*67e74705SXin Li                      std::shared_ptr<PCHContainerOperations> PCHContainerOps,
471*67e74705SXin Li                      DiagnosticConsumer *DiagConsumer) override {
472*67e74705SXin Li     std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
473*67e74705SXin Li         Invocation, std::move(PCHContainerOps),
474*67e74705SXin Li         CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
475*67e74705SXin Li                                             DiagConsumer,
476*67e74705SXin Li                                             /*ShouldOwnClient=*/false),
477*67e74705SXin Li         Files);
478*67e74705SXin Li     if (!AST)
479*67e74705SXin Li       return false;
480*67e74705SXin Li 
481*67e74705SXin Li     ASTs.push_back(std::move(AST));
482*67e74705SXin Li     return true;
483*67e74705SXin Li   }
484*67e74705SXin Li };
485*67e74705SXin Li }
486*67e74705SXin Li 
buildASTs(std::vector<std::unique_ptr<ASTUnit>> & ASTs)487*67e74705SXin Li int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
488*67e74705SXin Li   ASTBuilderAction Action(ASTs);
489*67e74705SXin Li   return run(&Action);
490*67e74705SXin Li }
491*67e74705SXin Li 
492*67e74705SXin Li std::unique_ptr<ASTUnit>
buildASTFromCode(const Twine & Code,const Twine & FileName,std::shared_ptr<PCHContainerOperations> PCHContainerOps)493*67e74705SXin Li buildASTFromCode(const Twine &Code, const Twine &FileName,
494*67e74705SXin Li                  std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
495*67e74705SXin Li   return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
496*67e74705SXin Li                                   "clang-tool", std::move(PCHContainerOps));
497*67e74705SXin Li }
498*67e74705SXin Li 
buildASTFromCodeWithArgs(const Twine & Code,const std::vector<std::string> & Args,const Twine & FileName,const Twine & ToolName,std::shared_ptr<PCHContainerOperations> PCHContainerOps)499*67e74705SXin Li std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
500*67e74705SXin Li     const Twine &Code, const std::vector<std::string> &Args,
501*67e74705SXin Li     const Twine &FileName, const Twine &ToolName,
502*67e74705SXin Li     std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
503*67e74705SXin Li   SmallString<16> FileNameStorage;
504*67e74705SXin Li   StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
505*67e74705SXin Li 
506*67e74705SXin Li   std::vector<std::unique_ptr<ASTUnit>> ASTs;
507*67e74705SXin Li   ASTBuilderAction Action(ASTs);
508*67e74705SXin Li   llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
509*67e74705SXin Li       new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
510*67e74705SXin Li   llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
511*67e74705SXin Li       new vfs::InMemoryFileSystem);
512*67e74705SXin Li   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
513*67e74705SXin Li   llvm::IntrusiveRefCntPtr<FileManager> Files(
514*67e74705SXin Li       new FileManager(FileSystemOptions(), OverlayFileSystem));
515*67e74705SXin Li   ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
516*67e74705SXin Li                             &Action, Files.get(), std::move(PCHContainerOps));
517*67e74705SXin Li 
518*67e74705SXin Li   SmallString<1024> CodeStorage;
519*67e74705SXin Li   InMemoryFileSystem->addFile(FileNameRef, 0,
520*67e74705SXin Li                               llvm::MemoryBuffer::getMemBuffer(
521*67e74705SXin Li                                   Code.toNullTerminatedStringRef(CodeStorage)));
522*67e74705SXin Li   if (!Invocation.run())
523*67e74705SXin Li     return nullptr;
524*67e74705SXin Li 
525*67e74705SXin Li   assert(ASTs.size() == 1);
526*67e74705SXin Li   return std::move(ASTs[0]);
527*67e74705SXin Li }
528*67e74705SXin Li 
529*67e74705SXin Li } // end namespace tooling
530*67e74705SXin Li } // end namespace clang
531