blob: c5fec6838445a1f6d3d5969cbbcc99fa8dea547f [file] [log] [blame]
Manuel Klimek47c245a2012-04-04 12:07:46 +00001//===--- 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"
Manuel Klimek47c245a2012-04-04 12:07:46 +000016#include "clang/Driver/Compilation.h"
17#include "clang/Driver/Driver.h"
18#include "clang/Driver/Tool.h"
19#include "clang/Frontend/CompilerInstance.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000020#include "clang/Frontend/FrontendDiagnostic.h"
21#include "clang/Frontend/TextDiagnosticPrinter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Tooling/ArgumentsAdjusters.h"
23#include "clang/Tooling/CompilationDatabase.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000024#include "llvm/ADT/STLExtras.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000025#include "llvm/Option/Option.h"
Edwin Vane34794c52013-03-15 20:14:01 +000026#include "llvm/Support/Debug.h"
NAKAMURA Takumif0c87792012-04-04 13:59:36 +000027#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000028#include "llvm/Support/Host.h"
29#include "llvm/Support/raw_ostream.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000030
Manuel Klimek74cec542012-05-07 09:45:46 +000031// For chdir, see the comment in ClangTool::run for more information.
Manuel Klimekf33dcb02012-05-07 10:02:55 +000032#ifdef _WIN32
Manuel Klimek74cec542012-05-07 09:45:46 +000033# include <direct.h>
Manuel Klimekf33dcb02012-05-07 10:02:55 +000034#else
35# include <unistd.h>
Manuel Klimek74cec542012-05-07 09:45:46 +000036#endif
37
Manuel Klimek47c245a2012-04-04 12:07:46 +000038namespace clang {
39namespace tooling {
40
41FrontendActionFactory::~FrontendActionFactory() {}
42
43// FIXME: This file contains structural duplication with other parts of the
44// code that sets up a compiler to run tools on it, and we should refactor
45// it to be based on the same framework.
46
47/// \brief Builds a clang driver initialized for running clang tools.
48static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
49 const char *BinaryName) {
50 const std::string DefaultOutputName = "a.out";
51 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Alexander Kornienko8388d242012-06-04 19:02:59 +000052 BinaryName, llvm::sys::getDefaultTargetTriple(),
Rafael Espindolab0448cd2012-11-27 16:10:37 +000053 DefaultOutputName, *Diagnostics);
Manuel Klimek47c245a2012-04-04 12:07:46 +000054 CompilerDriver->setTitle("clang_based_tool");
55 return CompilerDriver;
56}
57
58/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
59///
60/// Returns NULL on error.
Reid Kleckner898229a2013-06-14 17:17:23 +000061static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +000062 clang::DiagnosticsEngine *Diagnostics,
63 clang::driver::Compilation *Compilation) {
64 // We expect to get back exactly one Command job, if we didn't something
65 // failed. Extract that job from the Compilation.
66 const clang::driver::JobList &Jobs = Compilation->getJobs();
67 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000068 SmallString<256> error_msg;
Manuel Klimek47c245a2012-04-04 12:07:46 +000069 llvm::raw_svector_ostream error_stream(error_msg);
70 Compilation->PrintJob(error_stream, Compilation->getJobs(), "; ", true);
71 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
72 << error_stream.str();
73 return NULL;
74 }
75
76 // The one job we find should be to invoke clang again.
77 const clang::driver::Command *Cmd =
78 cast<clang::driver::Command>(*Jobs.begin());
79 if (StringRef(Cmd->getCreator().getName()) != "clang") {
80 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
81 return NULL;
82 }
83
84 return &Cmd->getArguments();
85}
86
87/// \brief Returns a clang build invocation initialized from the CC1 flags.
88static clang::CompilerInvocation *newInvocation(
89 clang::DiagnosticsEngine *Diagnostics,
Reid Kleckner898229a2013-06-14 17:17:23 +000090 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000091 assert(!CC1Args.empty() && "Must at least contain the program name!");
92 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
93 clang::CompilerInvocation::CreateFromArgs(
94 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
95 *Diagnostics);
96 Invocation->getFrontendOpts().DisableFree = false;
Nick Lewycky39dc9f82013-06-25 17:01:21 +000097 Invocation->getCodeGenOpts().DisableFree = false;
Manuel Klimek47c245a2012-04-04 12:07:46 +000098 return Invocation;
99}
100
101bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
102 const Twine &FileName) {
Nico Weber077a53e2012-08-30 02:02:19 +0000103 return runToolOnCodeWithArgs(
104 ToolAction, Code, std::vector<std::string>(), FileName);
105}
106
107bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
108 const std::vector<std::string> &Args,
109 const Twine &FileName) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000110 SmallString<16> FileNameStorage;
111 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Nico Weber077a53e2012-08-30 02:02:19 +0000112 std::vector<std::string> Commands;
113 Commands.push_back("clang-tool");
114 Commands.push_back("-fsyntax-only");
115 Commands.insert(Commands.end(), Args.begin(), Args.end());
116 Commands.push_back(FileNameRef.data());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000117 FileManager Files((FileSystemOptions()));
Nico Weber077a53e2012-08-30 02:02:19 +0000118 ToolInvocation Invocation(Commands, ToolAction, &Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000119
120 SmallString<1024> CodeStorage;
121 Invocation.mapVirtualFile(FileNameRef,
122 Code.toNullTerminatedStringRef(CodeStorage));
123 return Invocation.run();
124}
125
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000126std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000127 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000128 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000129 if (RelativePath.startswith("./")) {
130 RelativePath = RelativePath.substr(strlen("./"));
131 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000132
133 SmallString<1024> AbsolutePath = RelativePath;
134 llvm::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
135 assert(!EC);
136 SmallString<1024> PathStorage;
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000137 llvm::sys::path::native(Twine(AbsolutePath), PathStorage);
138 return PathStorage.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000139}
140
141ToolInvocation::ToolInvocation(
142 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
143 FileManager *Files)
144 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) {
145}
146
147void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000148 SmallString<1024> PathStorage;
149 llvm::sys::path::native(FilePath, PathStorage);
150 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000151}
152
153bool ToolInvocation::run() {
154 std::vector<const char*> Argv;
155 for (int I = 0, E = CommandLine.size(); I != E; ++I)
156 Argv.push_back(CommandLine[I].c_str());
157 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000158 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000159 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000160 llvm::errs(), &*DiagOpts);
161 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000162 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
Douglas Gregor811db4e2012-10-23 22:26:28 +0000163 &*DiagOpts, &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000164
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000165 const OwningPtr<clang::driver::Driver> Driver(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000166 newDriver(&Diagnostics, BinaryName));
167 // Since the input might only be virtual, don't check whether it exists.
168 Driver->setCheckInputsExist(false);
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000169 const OwningPtr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000170 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Kleckner898229a2013-06-14 17:17:23 +0000171 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000172 &Diagnostics, Compilation.get());
173 if (CC1Args == NULL) {
174 return false;
175 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000176 OwningPtr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000177 newInvocation(&Diagnostics, *CC1Args));
Sean Silvaf1b49e22013-01-20 01:58:28 +0000178 return runInvocation(BinaryName, Compilation.get(), Invocation.take());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000179}
180
Manuel Klimek47c245a2012-04-04 12:07:46 +0000181bool ToolInvocation::runInvocation(
182 const char *BinaryName,
183 clang::driver::Compilation *Compilation,
Sean Silvaf1b49e22013-01-20 01:58:28 +0000184 clang::CompilerInvocation *Invocation) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000185 // Show the invocation, with -v.
186 if (Invocation->getHeaderSearchOpts().Verbose) {
187 llvm::errs() << "clang Invocation:\n";
188 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true);
189 llvm::errs() << "\n";
190 }
191
192 // Create a compiler instance to handle the actual work.
193 clang::CompilerInstance Compiler;
194 Compiler.setInvocation(Invocation);
195 Compiler.setFileManager(Files);
196 // FIXME: What about LangOpts?
197
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000198 // ToolAction can have lifetime requirements for Compiler or its members, and
199 // we need to ensure it's deleted earlier than Compiler. So we pass it to an
200 // OwningPtr declared after the Compiler variable.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000201 OwningPtr<FrontendAction> ScopedToolAction(ToolAction.take());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000202
Manuel Klimek47c245a2012-04-04 12:07:46 +0000203 // Create the compilers actual diagnostics engine.
Sean Silvaf1b49e22013-01-20 01:58:28 +0000204 Compiler.createDiagnostics();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000205 if (!Compiler.hasDiagnostics())
206 return false;
207
208 Compiler.createSourceManager(*Files);
209 addFileMappingsTo(Compiler.getSourceManager());
210
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000211 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000212
213 Compiler.resetAndLeakFileManager();
Manuel Klimek3aad8552012-07-31 13:56:54 +0000214 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000215 return Success;
216}
217
218void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
219 for (llvm::StringMap<StringRef>::const_iterator
220 It = MappedFileContents.begin(), End = MappedFileContents.end();
221 It != End; ++It) {
222 // Inject the code as the given file name into the preprocessor options.
223 const llvm::MemoryBuffer *Input =
224 llvm::MemoryBuffer::getMemBuffer(It->getValue());
225 // FIXME: figure out what '0' stands for.
226 const FileEntry *FromFile = Files->getVirtualFile(
227 It->getKey(), Input->getBufferSize(), 0);
Alexander Kornienko9e8d2282012-05-30 12:10:28 +0000228 Sources.overrideFileContents(FromFile, Input);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000229 }
230}
231
232ClangTool::ClangTool(const CompilationDatabase &Compilations,
233 ArrayRef<std::string> SourcePaths)
Pavel Labathdee20c12013-06-06 11:52:19 +0000234 : Files((FileSystemOptions())) {
235 ArgsAdjusters.push_back(new ClangStripOutputAdjuster());
236 ArgsAdjusters.push_back(new ClangSyntaxOnlyAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000237 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000238 SmallString<1024> File(getAbsolutePath(SourcePaths[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000239
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000240 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimek47c245a2012-04-04 12:07:46 +0000241 Compilations.getCompileCommands(File.str());
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000242 if (!CompileCommandsForFile.empty()) {
243 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
244 CompileCommands.push_back(std::make_pair(File.str(),
245 CompileCommandsForFile[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000246 }
247 } else {
248 // FIXME: There are two use cases here: doing a fuzzy
249 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
250 // about the .cc files that were not found, and the use case where I
251 // specify all files I want to run over explicitly, where this should
252 // be an error. We'll want to add an option for this.
253 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
254 }
255 }
256}
257
258void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
259 MappedFileContents.push_back(std::make_pair(FilePath, Content));
260}
261
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000262void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
Manuel Klimekd91ac932013-06-04 14:44:44 +0000263 clearArgumentsAdjusters();
264 appendArgumentsAdjuster(Adjuster);
265}
266
267void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
268 ArgsAdjusters.push_back(Adjuster);
269}
270
271void ClangTool::clearArgumentsAdjusters() {
272 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
273 delete ArgsAdjusters[I];
274 ArgsAdjusters.clear();
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000275}
276
Manuel Klimek47c245a2012-04-04 12:07:46 +0000277int ClangTool::run(FrontendActionFactory *ActionFactory) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000278 // Exists solely for the purpose of lookup of the resource path.
279 // This just needs to be some symbol in the binary.
280 static int StaticSymbol;
281 // The driver detects the builtin header path based on the path of the
282 // executable.
283 // FIXME: On linux, GetMainExecutable is independent of the value of the
284 // first argument, thus allowing ClangTool and runToolOnCode to just
285 // pass in made-up names here. Make sure this works on other platforms.
286 std::string MainExecutable =
Rafael Espindola9678d272013-06-26 05:03:40 +0000287 llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000288
Manuel Klimek47c245a2012-04-04 12:07:46 +0000289 bool ProcessingFailed = false;
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000290 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
291 std::string File = CompileCommands[I].first;
292 // FIXME: chdir is thread hostile; on the other hand, creating the same
293 // behavior as chdir is complex: chdir resolves the path once, thus
294 // guaranteeing that all subsequent relative path operations work
295 // on the same path the original chdir resulted in. This makes a difference
Alexander Kornienko8388d242012-06-04 19:02:59 +0000296 // for example on network filesystems, where symlinks might be switched
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000297 // during runtime of the tool. Fixing this depends on having a file system
298 // abstraction that allows openat() style interactions.
299 if (chdir(CompileCommands[I].second.Directory.c_str()))
300 llvm::report_fatal_error("Cannot chdir into \"" +
301 CompileCommands[I].second.Directory + "\n!");
Manuel Klimekd91ac932013-06-04 14:44:44 +0000302 std::vector<std::string> CommandLine = CompileCommands[I].second.CommandLine;
303 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
304 CommandLine = ArgsAdjusters[I]->Adjust(CommandLine);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000305 assert(!CommandLine.empty());
306 CommandLine[0] = MainExecutable;
Edwin Vane34794c52013-03-15 20:14:01 +0000307 // FIXME: We need a callback mechanism for the tool writer to output a
308 // customized message for each file.
309 DEBUG({
310 llvm::dbgs() << "Processing: " << File << ".\n";
311 });
Manuel Klimek47c245a2012-04-04 12:07:46 +0000312 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
313 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
314 Invocation.mapVirtualFile(MappedFileContents[I].first,
315 MappedFileContents[I].second);
316 }
317 if (!Invocation.run()) {
Edwin Vane34794c52013-03-15 20:14:01 +0000318 // FIXME: Diagnostics should be used instead.
319 llvm::errs() << "Error while processing " << File << ".\n";
Manuel Klimek47c245a2012-04-04 12:07:46 +0000320 ProcessingFailed = true;
321 }
322 }
323 return ProcessingFailed ? 1 : 0;
324}
325
326} // end namespace tooling
327} // end namespace clang