1 //===--- Tooling.cpp - Running clang standalone tools ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements functions to run clang tools standalone instead
11 //  of running them as a plugin.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Tooling/Tooling.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/Driver/Compilation.h"
18 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/Tool.h"
20 #include "clang/Frontend/ASTUnit.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Frontend/FrontendDiagnostic.h"
23 #include "clang/Frontend/TextDiagnosticPrinter.h"
24 #include "clang/Tooling/ArgumentsAdjusters.h"
25 #include "clang/Tooling/CompilationDatabase.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Config/config.h"
28 #include "llvm/Option/Option.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/raw_ostream.h"
33 
34 // For chdir, see the comment in ClangTool::run for more information.
35 #ifdef LLVM_ON_WIN32
36 #  include <direct.h>
37 #else
38 #  include <unistd.h>
39 #endif
40 
41 #define DEBUG_TYPE "clang-tooling"
42 
43 namespace clang {
44 namespace tooling {
45 
46 ToolAction::~ToolAction() {}
47 
48 FrontendActionFactory::~FrontendActionFactory() {}
49 
50 // FIXME: This file contains structural duplication with other parts of the
51 // code that sets up a compiler to run tools on it, and we should refactor
52 // it to be based on the same framework.
53 
54 /// \brief Builds a clang driver initialized for running clang tools.
55 static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
56                                         const char *BinaryName) {
57   const char *DefaultOutputName = "a.out";
58   clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
59     BinaryName, llvm::sys::getDefaultTargetTriple(),
60     DefaultOutputName, *Diagnostics);
61   CompilerDriver->setTitle("clang_based_tool");
62   return CompilerDriver;
63 }
64 
65 /// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
66 ///
67 /// Returns NULL on error.
68 static const llvm::opt::ArgStringList *getCC1Arguments(
69     clang::DiagnosticsEngine *Diagnostics,
70     clang::driver::Compilation *Compilation) {
71   // We expect to get back exactly one Command job, if we didn't something
72   // failed. Extract that job from the Compilation.
73   const clang::driver::JobList &Jobs = Compilation->getJobs();
74   if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
75     SmallString<256> error_msg;
76     llvm::raw_svector_ostream error_stream(error_msg);
77     Jobs.Print(error_stream, "; ", true);
78     Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
79         << error_stream.str();
80     return NULL;
81   }
82 
83   // The one job we find should be to invoke clang again.
84   const clang::driver::Command *Cmd =
85       cast<clang::driver::Command>(*Jobs.begin());
86   if (StringRef(Cmd->getCreator().getName()) != "clang") {
87     Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
88     return NULL;
89   }
90 
91   return &Cmd->getArguments();
92 }
93 
94 /// \brief Returns a clang build invocation initialized from the CC1 flags.
95 static clang::CompilerInvocation *newInvocation(
96     clang::DiagnosticsEngine *Diagnostics,
97     const llvm::opt::ArgStringList &CC1Args) {
98   assert(!CC1Args.empty() && "Must at least contain the program name!");
99   clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
100   clang::CompilerInvocation::CreateFromArgs(
101       *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
102       *Diagnostics);
103   Invocation->getFrontendOpts().DisableFree = false;
104   Invocation->getCodeGenOpts().DisableFree = false;
105   Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
106   return Invocation;
107 }
108 
109 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
110                    const Twine &FileName) {
111   return runToolOnCodeWithArgs(
112       ToolAction, Code, std::vector<std::string>(), FileName);
113 }
114 
115 static std::vector<std::string>
116 getSyntaxOnlyToolArgs(const std::vector<std::string> &ExtraArgs,
117                       StringRef FileName) {
118   std::vector<std::string> Args;
119   Args.push_back("clang-tool");
120   Args.push_back("-fsyntax-only");
121   Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
122   Args.push_back(FileName.str());
123   return Args;
124 }
125 
126 bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
127                            const std::vector<std::string> &Args,
128                            const Twine &FileName) {
129   SmallString<16> FileNameStorage;
130   StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
131   llvm::IntrusiveRefCntPtr<FileManager> Files(
132       new FileManager(FileSystemOptions()));
133   ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), ToolAction,
134                             Files.getPtr());
135 
136   SmallString<1024> CodeStorage;
137   Invocation.mapVirtualFile(FileNameRef,
138                             Code.toNullTerminatedStringRef(CodeStorage));
139   return Invocation.run();
140 }
141 
142 std::string getAbsolutePath(StringRef File) {
143   StringRef RelativePath(File);
144   // FIXME: Should '.\\' be accepted on Win32?
145   if (RelativePath.startswith("./")) {
146     RelativePath = RelativePath.substr(strlen("./"));
147   }
148 
149   SmallString<1024> AbsolutePath = RelativePath;
150   llvm::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
151   assert(!EC);
152   (void)EC;
153   llvm::sys::path::native(AbsolutePath);
154   return AbsolutePath.str();
155 }
156 
157 namespace {
158 
159 class SingleFrontendActionFactory : public FrontendActionFactory {
160   FrontendAction *Action;
161 
162 public:
163   SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
164 
165   FrontendAction *create() override { return Action; }
166 };
167 
168 }
169 
170 ToolInvocation::ToolInvocation(std::vector<std::string> CommandLine,
171                                ToolAction *Action, FileManager *Files)
172     : CommandLine(std::move(CommandLine)),
173       Action(Action),
174       OwnsAction(false),
175       Files(Files),
176       DiagConsumer(NULL) {}
177 
178 ToolInvocation::ToolInvocation(std::vector<std::string> CommandLine,
179                                FrontendAction *FAction, FileManager *Files)
180     : CommandLine(std::move(CommandLine)),
181       Action(new SingleFrontendActionFactory(FAction)),
182       OwnsAction(true),
183       Files(Files),
184       DiagConsumer(NULL) {}
185 
186 ToolInvocation::~ToolInvocation() {
187   if (OwnsAction)
188     delete Action;
189 }
190 
191 void ToolInvocation::setDiagnosticConsumer(DiagnosticConsumer *D) {
192   DiagConsumer = D;
193 }
194 
195 void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
196   SmallString<1024> PathStorage;
197   llvm::sys::path::native(FilePath, PathStorage);
198   MappedFileContents[PathStorage] = Content;
199 }
200 
201 bool ToolInvocation::run() {
202   std::vector<const char*> Argv;
203   for (const std::string &Str : CommandLine)
204     Argv.push_back(Str.c_str());
205   const char *const BinaryName = Argv[0];
206   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
207   TextDiagnosticPrinter DiagnosticPrinter(
208       llvm::errs(), &*DiagOpts);
209   DiagnosticsEngine Diagnostics(
210       IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
211       DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
212 
213   const std::unique_ptr<clang::driver::Driver> Driver(
214       newDriver(&Diagnostics, BinaryName));
215   // Since the input might only be virtual, don't check whether it exists.
216   Driver->setCheckInputsExist(false);
217   const std::unique_ptr<clang::driver::Compilation> Compilation(
218       Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
219   const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
220       &Diagnostics, Compilation.get());
221   if (CC1Args == NULL) {
222     return false;
223   }
224   std::unique_ptr<clang::CompilerInvocation> Invocation(
225       newInvocation(&Diagnostics, *CC1Args));
226   for (const auto &It : MappedFileContents) {
227     // Inject the code as the given file name into the preprocessor options.
228     auto *Input = llvm::MemoryBuffer::getMemBuffer(It.getValue());
229     Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(), Input);
230   }
231   return runInvocation(BinaryName, Compilation.get(), Invocation.release());
232 }
233 
234 bool ToolInvocation::runInvocation(
235     const char *BinaryName,
236     clang::driver::Compilation *Compilation,
237     clang::CompilerInvocation *Invocation) {
238   // Show the invocation, with -v.
239   if (Invocation->getHeaderSearchOpts().Verbose) {
240     llvm::errs() << "clang Invocation:\n";
241     Compilation->getJobs().Print(llvm::errs(), "\n", true);
242     llvm::errs() << "\n";
243   }
244 
245   return Action->runInvocation(Invocation, Files, DiagConsumer);
246 }
247 
248 bool FrontendActionFactory::runInvocation(CompilerInvocation *Invocation,
249                                           FileManager *Files,
250                                           DiagnosticConsumer *DiagConsumer) {
251   // Create a compiler instance to handle the actual work.
252   clang::CompilerInstance Compiler;
253   Compiler.setInvocation(Invocation);
254   Compiler.setFileManager(Files);
255 
256   // The FrontendAction can have lifetime requirements for Compiler or its
257   // members, and we need to ensure it's deleted earlier than Compiler. So we
258   // pass it to an std::unique_ptr declared after the Compiler variable.
259   std::unique_ptr<FrontendAction> ScopedToolAction(create());
260 
261   // Create the compilers actual diagnostics engine.
262   Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
263   if (!Compiler.hasDiagnostics())
264     return false;
265 
266   Compiler.createSourceManager(*Files);
267 
268   const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
269 
270   Files->clearStatCaches();
271   return Success;
272 }
273 
274 ClangTool::ClangTool(const CompilationDatabase &Compilations,
275                      ArrayRef<std::string> SourcePaths)
276     : Files(new FileManager(FileSystemOptions())), DiagConsumer(NULL) {
277   ArgsAdjusters.push_back(new ClangStripOutputAdjuster());
278   ArgsAdjusters.push_back(new ClangSyntaxOnlyAdjuster());
279   for (const auto &SourcePath : SourcePaths) {
280     std::string File(getAbsolutePath(SourcePath));
281 
282     std::vector<CompileCommand> CompileCommandsForFile =
283       Compilations.getCompileCommands(File);
284     if (!CompileCommandsForFile.empty()) {
285       for (CompileCommand &CompileCommand : CompileCommandsForFile) {
286         CompileCommands.push_back(
287             std::make_pair(File, std::move(CompileCommand)));
288       }
289     } else {
290       // FIXME: There are two use cases here: doing a fuzzy
291       // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
292       // about the .cc files that were not found, and the use case where I
293       // specify all files I want to run over explicitly, where this should
294       // be an error. We'll want to add an option for this.
295       llvm::outs() << "Skipping " << File << ". Command line not found.\n";
296     }
297   }
298 }
299 
300 void ClangTool::setDiagnosticConsumer(DiagnosticConsumer *D) {
301   DiagConsumer = D;
302 }
303 
304 void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
305   MappedFileContents.push_back(std::make_pair(FilePath, Content));
306 }
307 
308 void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
309   clearArgumentsAdjusters();
310   appendArgumentsAdjuster(Adjuster);
311 }
312 
313 void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
314   ArgsAdjusters.push_back(Adjuster);
315 }
316 
317 void ClangTool::clearArgumentsAdjusters() {
318   for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
319     delete ArgsAdjusters[I];
320   ArgsAdjusters.clear();
321 }
322 
323 int ClangTool::run(ToolAction *Action) {
324   // Exists solely for the purpose of lookup of the resource path.
325   // This just needs to be some symbol in the binary.
326   static int StaticSymbol;
327   // The driver detects the builtin header path based on the path of the
328   // executable.
329   // FIXME: On linux, GetMainExecutable is independent of the value of the
330   // first argument, thus allowing ClangTool and runToolOnCode to just
331   // pass in made-up names here. Make sure this works on other platforms.
332   std::string MainExecutable =
333       llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol);
334 
335   bool ProcessingFailed = false;
336   for (const auto &Command : CompileCommands) {
337     // FIXME: chdir is thread hostile; on the other hand, creating the same
338     // behavior as chdir is complex: chdir resolves the path once, thus
339     // guaranteeing that all subsequent relative path operations work
340     // on the same path the original chdir resulted in. This makes a difference
341     // for example on network filesystems, where symlinks might be switched
342     // during runtime of the tool. Fixing this depends on having a file system
343     // abstraction that allows openat() style interactions.
344     if (chdir(Command.second.Directory.c_str()))
345       llvm::report_fatal_error("Cannot chdir into \"" +
346                                Twine(Command.second.Directory) + "\n!");
347     std::vector<std::string> CommandLine = Command.second.CommandLine;
348     for (ArgumentsAdjuster *Adjuster : ArgsAdjusters)
349       CommandLine = Adjuster->Adjust(CommandLine);
350     assert(!CommandLine.empty());
351     CommandLine[0] = MainExecutable;
352     // FIXME: We need a callback mechanism for the tool writer to output a
353     // customized message for each file.
354     DEBUG({
355       llvm::dbgs() << "Processing: " << Command.first << ".\n";
356     });
357     ToolInvocation Invocation(std::move(CommandLine), Action, Files.getPtr());
358     Invocation.setDiagnosticConsumer(DiagConsumer);
359     for (const auto &MappedFile : MappedFileContents) {
360       Invocation.mapVirtualFile(MappedFile.first, MappedFile.second);
361     }
362     if (!Invocation.run()) {
363       // FIXME: Diagnostics should be used instead.
364       llvm::errs() << "Error while processing " << Command.first << ".\n";
365       ProcessingFailed = true;
366     }
367   }
368   return ProcessingFailed ? 1 : 0;
369 }
370 
371 namespace {
372 
373 class ASTBuilderAction : public ToolAction {
374   std::vector<ASTUnit *> &ASTs;
375 
376 public:
377   ASTBuilderAction(std::vector<ASTUnit *> &ASTs) : ASTs(ASTs) {}
378 
379   bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
380                      DiagnosticConsumer *DiagConsumer) override {
381     // FIXME: This should use the provided FileManager.
382     ASTUnit *AST = ASTUnit::LoadFromCompilerInvocation(
383         Invocation, CompilerInstance::createDiagnostics(
384                         &Invocation->getDiagnosticOpts(), DiagConsumer,
385                         /*ShouldOwnClient=*/false));
386     if (!AST)
387       return false;
388 
389     ASTs.push_back(AST);
390     return true;
391   }
392 };
393 
394 }
395 
396 int ClangTool::buildASTs(std::vector<ASTUnit *> &ASTs) {
397   ASTBuilderAction Action(ASTs);
398   return run(&Action);
399 }
400 
401 ASTUnit *buildASTFromCode(const Twine &Code, const Twine &FileName) {
402   return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName);
403 }
404 
405 ASTUnit *buildASTFromCodeWithArgs(const Twine &Code,
406                                   const std::vector<std::string> &Args,
407                                   const Twine &FileName) {
408   SmallString<16> FileNameStorage;
409   StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
410 
411   std::vector<ASTUnit *> ASTs;
412   ASTBuilderAction Action(ASTs);
413   ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), &Action, 0);
414 
415   SmallString<1024> CodeStorage;
416   Invocation.mapVirtualFile(FileNameRef,
417                             Code.toNullTerminatedStringRef(CodeStorage));
418   if (!Invocation.run())
419     return 0;
420 
421   assert(ASTs.size() == 1);
422   return ASTs[0];
423 }
424 
425 } // end namespace tooling
426 } // end namespace clang
427