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/Option/Option.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/raw_ostream.h"
32 
33 // For chdir, see the comment in ClangTool::run for more information.
34 #ifdef _WIN32
35 #  include <direct.h>
36 #else
37 #  include <unistd.h>
38 #endif
39 
40 namespace clang {
41 namespace tooling {
42 
43 ToolAction::~ToolAction() {}
44 
45 FrontendActionFactory::~FrontendActionFactory() {}
46 
47 // FIXME: This file contains structural duplication with other parts of the
48 // code that sets up a compiler to run tools on it, and we should refactor
49 // it to be based on the same framework.
50 
51 /// \brief Builds a clang driver initialized for running clang tools.
52 static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
53                                         const char *BinaryName) {
54   const std::string DefaultOutputName = "a.out";
55   clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
56     BinaryName, llvm::sys::getDefaultTargetTriple(),
57     DefaultOutputName, *Diagnostics);
58   CompilerDriver->setTitle("clang_based_tool");
59   return CompilerDriver;
60 }
61 
62 /// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
63 ///
64 /// Returns NULL on error.
65 static const llvm::opt::ArgStringList *getCC1Arguments(
66     clang::DiagnosticsEngine *Diagnostics,
67     clang::driver::Compilation *Compilation) {
68   // We expect to get back exactly one Command job, if we didn't something
69   // failed. Extract that job from the Compilation.
70   const clang::driver::JobList &Jobs = Compilation->getJobs();
71   if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
72     SmallString<256> error_msg;
73     llvm::raw_svector_ostream error_stream(error_msg);
74     Jobs.Print(error_stream, "; ", true);
75     Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
76         << error_stream.str();
77     return NULL;
78   }
79 
80   // The one job we find should be to invoke clang again.
81   const clang::driver::Command *Cmd =
82       cast<clang::driver::Command>(*Jobs.begin());
83   if (StringRef(Cmd->getCreator().getName()) != "clang") {
84     Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
85     return NULL;
86   }
87 
88   return &Cmd->getArguments();
89 }
90 
91 /// \brief Returns a clang build invocation initialized from the CC1 flags.
92 static clang::CompilerInvocation *newInvocation(
93     clang::DiagnosticsEngine *Diagnostics,
94     const llvm::opt::ArgStringList &CC1Args) {
95   assert(!CC1Args.empty() && "Must at least contain the program name!");
96   clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
97   clang::CompilerInvocation::CreateFromArgs(
98       *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
99       *Diagnostics);
100   Invocation->getFrontendOpts().DisableFree = false;
101   Invocation->getCodeGenOpts().DisableFree = false;
102   Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
103   return Invocation;
104 }
105 
106 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
107                    const Twine &FileName) {
108   return runToolOnCodeWithArgs(
109       ToolAction, Code, std::vector<std::string>(), FileName);
110 }
111 
112 static std::vector<std::string>
113 getSyntaxOnlyToolArgs(const std::vector<std::string> &ExtraArgs,
114                       StringRef FileName) {
115   std::vector<std::string> Args;
116   Args.push_back("clang-tool");
117   Args.push_back("-fsyntax-only");
118   Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
119   Args.push_back(FileName.str());
120   return Args;
121 }
122 
123 bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
124                            const std::vector<std::string> &Args,
125                            const Twine &FileName) {
126   SmallString<16> FileNameStorage;
127   StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
128   llvm::IntrusiveRefCntPtr<FileManager> Files(
129       new FileManager(FileSystemOptions()));
130   ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), ToolAction,
131                             Files.getPtr());
132 
133   SmallString<1024> CodeStorage;
134   Invocation.mapVirtualFile(FileNameRef,
135                             Code.toNullTerminatedStringRef(CodeStorage));
136   return Invocation.run();
137 }
138 
139 std::string getAbsolutePath(StringRef File) {
140   StringRef RelativePath(File);
141   // FIXME: Should '.\\' be accepted on Win32?
142   if (RelativePath.startswith("./")) {
143     RelativePath = RelativePath.substr(strlen("./"));
144   }
145 
146   SmallString<1024> AbsolutePath = RelativePath;
147   llvm::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
148   assert(!EC);
149   (void)EC;
150   llvm::sys::path::native(AbsolutePath);
151   return AbsolutePath.str();
152 }
153 
154 namespace {
155 
156 class SingleFrontendActionFactory : public FrontendActionFactory {
157   FrontendAction *Action;
158 
159 public:
160   SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
161 
162   FrontendAction *create() { return Action; }
163 };
164 
165 }
166 
167 ToolInvocation::ToolInvocation(ArrayRef<std::string> CommandLine,
168                                ToolAction *Action, FileManager *Files)
169     : CommandLine(CommandLine.vec()),
170       Action(Action),
171       OwnsAction(false),
172       Files(Files),
173       DiagConsumer(NULL) {}
174 
175 ToolInvocation::ToolInvocation(ArrayRef<std::string> CommandLine,
176                                FrontendAction *FAction, FileManager *Files)
177     : CommandLine(CommandLine.vec()),
178       Action(new SingleFrontendActionFactory(FAction)),
179       OwnsAction(true),
180       Files(Files),
181       DiagConsumer(NULL) {}
182 
183 ToolInvocation::~ToolInvocation() {
184   if (OwnsAction)
185     delete Action;
186 }
187 
188 void ToolInvocation::setDiagnosticConsumer(DiagnosticConsumer *D) {
189   DiagConsumer = D;
190 }
191 
192 void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
193   SmallString<1024> PathStorage;
194   llvm::sys::path::native(FilePath, PathStorage);
195   MappedFileContents[PathStorage] = Content;
196 }
197 
198 bool ToolInvocation::run() {
199   std::vector<const char*> Argv;
200   for (int I = 0, E = CommandLine.size(); I != E; ++I)
201     Argv.push_back(CommandLine[I].c_str());
202   const char *const BinaryName = Argv[0];
203   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
204   TextDiagnosticPrinter DiagnosticPrinter(
205       llvm::errs(), &*DiagOpts);
206   DiagnosticsEngine Diagnostics(
207       IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
208       DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
209 
210   const OwningPtr<clang::driver::Driver> Driver(
211       newDriver(&Diagnostics, BinaryName));
212   // Since the input might only be virtual, don't check whether it exists.
213   Driver->setCheckInputsExist(false);
214   const OwningPtr<clang::driver::Compilation> Compilation(
215       Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
216   const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
217       &Diagnostics, Compilation.get());
218   if (CC1Args == NULL) {
219     return false;
220   }
221   OwningPtr<clang::CompilerInvocation> Invocation(
222       newInvocation(&Diagnostics, *CC1Args));
223   for (llvm::StringMap<StringRef>::const_iterator
224            It = MappedFileContents.begin(), End = MappedFileContents.end();
225        It != End; ++It) {
226     // Inject the code as the given file name into the preprocessor options.
227     const llvm::MemoryBuffer *Input =
228         llvm::MemoryBuffer::getMemBuffer(It->getValue());
229     Invocation->getPreprocessorOpts().addRemappedFile(It->getKey(), Input);
230   }
231   return runInvocation(BinaryName, Compilation.get(), Invocation.take());
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 OwningPtr declared after the Compiler variable.
259   OwningPtr<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 (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
280     SmallString<1024> File(getAbsolutePath(SourcePaths[I]));
281 
282     std::vector<CompileCommand> CompileCommandsForFile =
283       Compilations.getCompileCommands(File.str());
284     if (!CompileCommandsForFile.empty()) {
285       for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
286         CompileCommands.push_back(std::make_pair(File.str(),
287                                   CompileCommandsForFile[I]));
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 (unsigned I = 0; I < CompileCommands.size(); ++I) {
337     std::string File = CompileCommands[I].first;
338     // FIXME: chdir is thread hostile; on the other hand, creating the same
339     // behavior as chdir is complex: chdir resolves the path once, thus
340     // guaranteeing that all subsequent relative path operations work
341     // on the same path the original chdir resulted in. This makes a difference
342     // for example on network filesystems, where symlinks might be switched
343     // during runtime of the tool. Fixing this depends on having a file system
344     // abstraction that allows openat() style interactions.
345     if (chdir(CompileCommands[I].second.Directory.c_str()))
346       llvm::report_fatal_error("Cannot chdir into \"" +
347                                CompileCommands[I].second.Directory + "\n!");
348     std::vector<std::string> CommandLine = CompileCommands[I].second.CommandLine;
349     for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
350       CommandLine = ArgsAdjusters[I]->Adjust(CommandLine);
351     assert(!CommandLine.empty());
352     CommandLine[0] = MainExecutable;
353     // FIXME: We need a callback mechanism for the tool writer to output a
354     // customized message for each file.
355     DEBUG({
356       llvm::dbgs() << "Processing: " << File << ".\n";
357     });
358     ToolInvocation Invocation(CommandLine, Action, Files.getPtr());
359     Invocation.setDiagnosticConsumer(DiagConsumer);
360     for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
361       Invocation.mapVirtualFile(MappedFileContents[I].first,
362                                 MappedFileContents[I].second);
363     }
364     if (!Invocation.run()) {
365       // FIXME: Diagnostics should be used instead.
366       llvm::errs() << "Error while processing " << File << ".\n";
367       ProcessingFailed = true;
368     }
369   }
370   return ProcessingFailed ? 1 : 0;
371 }
372 
373 namespace {
374 
375 class ASTBuilderAction : public ToolAction {
376   std::vector<ASTUnit *> &ASTs;
377 
378 public:
379   ASTBuilderAction(std::vector<ASTUnit *> &ASTs) : ASTs(ASTs) {}
380 
381   bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
382                      DiagnosticConsumer *DiagConsumer) {
383     // FIXME: This should use the provided FileManager.
384     ASTUnit *AST = ASTUnit::LoadFromCompilerInvocation(
385         Invocation, CompilerInstance::createDiagnostics(
386                         &Invocation->getDiagnosticOpts(), DiagConsumer,
387                         /*ShouldOwnClient=*/false));
388     if (!AST)
389       return false;
390 
391     ASTs.push_back(AST);
392     return true;
393   }
394 };
395 
396 }
397 
398 int ClangTool::buildASTs(std::vector<ASTUnit *> &ASTs) {
399   ASTBuilderAction Action(ASTs);
400   return run(&Action);
401 }
402 
403 ASTUnit *buildASTFromCode(const Twine &Code, const Twine &FileName) {
404   return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName);
405 }
406 
407 ASTUnit *buildASTFromCodeWithArgs(const Twine &Code,
408                                   const std::vector<std::string> &Args,
409                                   const Twine &FileName) {
410   SmallString<16> FileNameStorage;
411   StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
412 
413   std::vector<ASTUnit *> ASTs;
414   ASTBuilderAction Action(ASTs);
415   ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), &Action, 0);
416 
417   SmallString<1024> CodeStorage;
418   Invocation.mapVirtualFile(FileNameRef,
419                             Code.toNullTerminatedStringRef(CodeStorage));
420   if (!Invocation.run())
421     return 0;
422 
423   assert(ASTs.size() == 1);
424   return ASTs[0];
425 }
426 
427 } // end namespace tooling
428 } // end namespace clang
429