blob: e7bfba7e1269734093b8595671f6277602f7c024 [file] [log] [blame]
Manuel Klimekcb971c62012-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 Klimekcb971c62012-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 Klimekcb971c62012-04-04 12:07:46 +000020#include "clang/Frontend/FrontendDiagnostic.h"
21#include "clang/Frontend/TextDiagnosticPrinter.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Tooling/ArgumentsAdjusters.h"
23#include "clang/Tooling/CompilationDatabase.h"
NAKAMURA Takumi01b8ca52012-04-04 13:59:41 +000024#include "llvm/ADT/STLExtras.h"
Reid Klecknerb1e25a12013-06-14 17:17:23 +000025#include "llvm/Option/Option.h"
Edwin Vanead7e1602013-03-15 20:14:01 +000026#include "llvm/Support/Debug.h"
NAKAMURA Takumib175d0f2012-04-04 13:59:36 +000027#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi01b8ca52012-04-04 13:59:41 +000028#include "llvm/Support/Host.h"
29#include "llvm/Support/raw_ostream.h"
Manuel Klimekcb971c62012-04-04 12:07:46 +000030
Manuel Klimek3b6e3192012-05-07 09:45:46 +000031// For chdir, see the comment in ClangTool::run for more information.
Manuel Klimeked5ee482012-05-07 10:02:55 +000032#ifdef _WIN32
Manuel Klimek3b6e3192012-05-07 09:45:46 +000033# include <direct.h>
Manuel Klimeked5ee482012-05-07 10:02:55 +000034#else
35# include <unistd.h>
Manuel Klimek3b6e3192012-05-07 09:45:46 +000036#endif
37
Manuel Klimekcb971c62012-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 Kornienko30c009b2012-06-04 19:02:59 +000052 BinaryName, llvm::sys::getDefaultTargetTriple(),
Rafael Espindola17c874a2012-11-27 16:10:37 +000053 DefaultOutputName, *Diagnostics);
Manuel Klimekcb971c62012-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 Klecknerb1e25a12013-06-14 17:17:23 +000061static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimekcb971c62012-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 Gribenkocfa88f82013-01-12 19:30:44 +000068 SmallString<256> error_msg;
Manuel Klimekcb971c62012-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 Klecknerb1e25a12013-06-14 17:17:23 +000090 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimekcb971c62012-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;
97 return Invocation;
98}
99
100bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
101 const Twine &FileName) {
Nico Weber56669882012-08-30 02:02:19 +0000102 return runToolOnCodeWithArgs(
103 ToolAction, Code, std::vector<std::string>(), FileName);
104}
105
106bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
107 const std::vector<std::string> &Args,
108 const Twine &FileName) {
Manuel Klimekcb971c62012-04-04 12:07:46 +0000109 SmallString<16> FileNameStorage;
110 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Nico Weber56669882012-08-30 02:02:19 +0000111 std::vector<std::string> Commands;
112 Commands.push_back("clang-tool");
113 Commands.push_back("-fsyntax-only");
114 Commands.insert(Commands.end(), Args.begin(), Args.end());
115 Commands.push_back(FileNameRef.data());
Manuel Klimekcb971c62012-04-04 12:07:46 +0000116 FileManager Files((FileSystemOptions()));
Nico Weber56669882012-08-30 02:02:19 +0000117 ToolInvocation Invocation(Commands, ToolAction, &Files);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000118
119 SmallString<1024> CodeStorage;
120 Invocation.mapVirtualFile(FileNameRef,
121 Code.toNullTerminatedStringRef(CodeStorage));
122 return Invocation.run();
123}
124
Manuel Klimek8fa2fb82012-07-10 13:10:51 +0000125std::string getAbsolutePath(StringRef File) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000126 SmallString<1024> BaseDirectory;
Manuel Klimek8fa2fb82012-07-10 13:10:51 +0000127 if (const char *PWD = ::getenv("PWD"))
128 BaseDirectory = PWD;
129 else
130 llvm::sys::fs::current_path(BaseDirectory);
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000131 SmallString<1024> PathStorage;
Manuel Klimekcb971c62012-04-04 12:07:46 +0000132 if (llvm::sys::path::is_absolute(File)) {
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000133 llvm::sys::path::native(File, PathStorage);
134 return PathStorage.str();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000135 }
136 StringRef RelativePath(File);
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000137 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimekcb971c62012-04-04 12:07:46 +0000138 if (RelativePath.startswith("./")) {
139 RelativePath = RelativePath.substr(strlen("./"));
140 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000141 SmallString<1024> AbsolutePath(BaseDirectory);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000142 llvm::sys::path::append(AbsolutePath, RelativePath);
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000143 llvm::sys::path::native(Twine(AbsolutePath), PathStorage);
144 return PathStorage.str();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000145}
146
147ToolInvocation::ToolInvocation(
148 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
149 FileManager *Files)
150 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) {
151}
152
153void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi0ef8db22012-06-02 15:34:21 +0000154 SmallString<1024> PathStorage;
155 llvm::sys::path::native(FilePath, PathStorage);
156 MappedFileContents[PathStorage] = Content;
Manuel Klimekcb971c62012-04-04 12:07:46 +0000157}
158
159bool ToolInvocation::run() {
160 std::vector<const char*> Argv;
161 for (int I = 0, E = CommandLine.size(); I != E; ++I)
162 Argv.push_back(CommandLine[I].c_str());
163 const char *const BinaryName = Argv[0];
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000164 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000165 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000166 llvm::errs(), &*DiagOpts);
167 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000168 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000169 &*DiagOpts, &DiagnosticPrinter, false);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000170
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000171 const OwningPtr<clang::driver::Driver> Driver(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000172 newDriver(&Diagnostics, BinaryName));
173 // Since the input might only be virtual, don't check whether it exists.
174 Driver->setCheckInputsExist(false);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000175 const OwningPtr<clang::driver::Compilation> Compilation(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000176 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Klecknerb1e25a12013-06-14 17:17:23 +0000177 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000178 &Diagnostics, Compilation.get());
179 if (CC1Args == NULL) {
180 return false;
181 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000182 OwningPtr<clang::CompilerInvocation> Invocation(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000183 newInvocation(&Diagnostics, *CC1Args));
Sean Silvad47afb92013-01-20 01:58:28 +0000184 return runInvocation(BinaryName, Compilation.get(), Invocation.take());
Manuel Klimekcb971c62012-04-04 12:07:46 +0000185}
186
Manuel Klimekcb971c62012-04-04 12:07:46 +0000187bool ToolInvocation::runInvocation(
188 const char *BinaryName,
189 clang::driver::Compilation *Compilation,
Sean Silvad47afb92013-01-20 01:58:28 +0000190 clang::CompilerInvocation *Invocation) {
Manuel Klimekcb971c62012-04-04 12:07:46 +0000191 // Show the invocation, with -v.
192 if (Invocation->getHeaderSearchOpts().Verbose) {
193 llvm::errs() << "clang Invocation:\n";
194 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true);
195 llvm::errs() << "\n";
196 }
197
198 // Create a compiler instance to handle the actual work.
199 clang::CompilerInstance Compiler;
200 Compiler.setInvocation(Invocation);
201 Compiler.setFileManager(Files);
202 // FIXME: What about LangOpts?
203
Alexander Kornienko14a19242012-05-31 17:58:43 +0000204 // ToolAction can have lifetime requirements for Compiler or its members, and
205 // we need to ensure it's deleted earlier than Compiler. So we pass it to an
206 // OwningPtr declared after the Compiler variable.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000207 OwningPtr<FrontendAction> ScopedToolAction(ToolAction.take());
Alexander Kornienko14a19242012-05-31 17:58:43 +0000208
Manuel Klimekcb971c62012-04-04 12:07:46 +0000209 // Create the compilers actual diagnostics engine.
Sean Silvad47afb92013-01-20 01:58:28 +0000210 Compiler.createDiagnostics();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000211 if (!Compiler.hasDiagnostics())
212 return false;
213
214 Compiler.createSourceManager(*Files);
215 addFileMappingsTo(Compiler.getSourceManager());
216
Alexander Kornienko14a19242012-05-31 17:58:43 +0000217 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000218
219 Compiler.resetAndLeakFileManager();
Manuel Klimek98be8602012-07-31 13:56:54 +0000220 Files->clearStatCaches();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000221 return Success;
222}
223
224void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
225 for (llvm::StringMap<StringRef>::const_iterator
226 It = MappedFileContents.begin(), End = MappedFileContents.end();
227 It != End; ++It) {
228 // Inject the code as the given file name into the preprocessor options.
229 const llvm::MemoryBuffer *Input =
230 llvm::MemoryBuffer::getMemBuffer(It->getValue());
231 // FIXME: figure out what '0' stands for.
232 const FileEntry *FromFile = Files->getVirtualFile(
233 It->getKey(), Input->getBufferSize(), 0);
Alexander Kornienko240193b2012-05-30 12:10:28 +0000234 Sources.overrideFileContents(FromFile, Input);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000235 }
236}
237
238ClangTool::ClangTool(const CompilationDatabase &Compilations,
239 ArrayRef<std::string> SourcePaths)
Pavel Labath63d53352013-06-06 11:52:19 +0000240 : Files((FileSystemOptions())) {
241 ArgsAdjusters.push_back(new ClangStripOutputAdjuster());
242 ArgsAdjusters.push_back(new ClangSyntaxOnlyAdjuster());
Manuel Klimekcb971c62012-04-04 12:07:46 +0000243 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000244 SmallString<1024> File(getAbsolutePath(SourcePaths[I]));
Manuel Klimekcb971c62012-04-04 12:07:46 +0000245
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000246 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimekcb971c62012-04-04 12:07:46 +0000247 Compilations.getCompileCommands(File.str());
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000248 if (!CompileCommandsForFile.empty()) {
249 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
250 CompileCommands.push_back(std::make_pair(File.str(),
251 CompileCommandsForFile[I]));
Manuel Klimekcb971c62012-04-04 12:07:46 +0000252 }
253 } else {
254 // FIXME: There are two use cases here: doing a fuzzy
255 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
256 // about the .cc files that were not found, and the use case where I
257 // specify all files I want to run over explicitly, where this should
258 // be an error. We'll want to add an option for this.
259 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
260 }
261 }
262}
263
264void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
265 MappedFileContents.push_back(std::make_pair(FilePath, Content));
266}
267
Simon Atanasyana01ddc72012-05-09 16:18:30 +0000268void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
Manuel Klimek48b3f0f2013-06-04 14:44:44 +0000269 clearArgumentsAdjusters();
270 appendArgumentsAdjuster(Adjuster);
271}
272
273void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
274 ArgsAdjusters.push_back(Adjuster);
275}
276
277void ClangTool::clearArgumentsAdjusters() {
278 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
279 delete ArgsAdjusters[I];
280 ArgsAdjusters.clear();
Simon Atanasyana01ddc72012-05-09 16:18:30 +0000281}
282
Manuel Klimekcb971c62012-04-04 12:07:46 +0000283int ClangTool::run(FrontendActionFactory *ActionFactory) {
Alexander Kornienko30c009b2012-06-04 19:02:59 +0000284 // Exists solely for the purpose of lookup of the resource path.
285 // This just needs to be some symbol in the binary.
286 static int StaticSymbol;
287 // The driver detects the builtin header path based on the path of the
288 // executable.
289 // FIXME: On linux, GetMainExecutable is independent of the value of the
290 // first argument, thus allowing ClangTool and runToolOnCode to just
291 // pass in made-up names here. Make sure this works on other platforms.
292 std::string MainExecutable =
293 llvm::sys::Path::GetMainExecutable("clang_tool", &StaticSymbol).str();
294
Manuel Klimekcb971c62012-04-04 12:07:46 +0000295 bool ProcessingFailed = false;
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000296 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
297 std::string File = CompileCommands[I].first;
298 // FIXME: chdir is thread hostile; on the other hand, creating the same
299 // behavior as chdir is complex: chdir resolves the path once, thus
300 // guaranteeing that all subsequent relative path operations work
301 // on the same path the original chdir resulted in. This makes a difference
Alexander Kornienko30c009b2012-06-04 19:02:59 +0000302 // for example on network filesystems, where symlinks might be switched
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000303 // during runtime of the tool. Fixing this depends on having a file system
304 // abstraction that allows openat() style interactions.
305 if (chdir(CompileCommands[I].second.Directory.c_str()))
306 llvm::report_fatal_error("Cannot chdir into \"" +
307 CompileCommands[I].second.Directory + "\n!");
Manuel Klimek48b3f0f2013-06-04 14:44:44 +0000308 std::vector<std::string> CommandLine = CompileCommands[I].second.CommandLine;
309 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
310 CommandLine = ArgsAdjusters[I]->Adjust(CommandLine);
Alexander Kornienko30c009b2012-06-04 19:02:59 +0000311 assert(!CommandLine.empty());
312 CommandLine[0] = MainExecutable;
Edwin Vanead7e1602013-03-15 20:14:01 +0000313 // FIXME: We need a callback mechanism for the tool writer to output a
314 // customized message for each file.
315 DEBUG({
316 llvm::dbgs() << "Processing: " << File << ".\n";
317 });
Manuel Klimekcb971c62012-04-04 12:07:46 +0000318 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
319 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
320 Invocation.mapVirtualFile(MappedFileContents[I].first,
321 MappedFileContents[I].second);
322 }
323 if (!Invocation.run()) {
Edwin Vanead7e1602013-03-15 20:14:01 +0000324 // FIXME: Diagnostics should be used instead.
325 llvm::errs() << "Error while processing " << File << ".\n";
Manuel Klimekcb971c62012-04-04 12:07:46 +0000326 ProcessingFailed = true;
327 }
328 }
329 return ProcessingFailed ? 1 : 0;
330}
331
332} // end namespace tooling
333} // end namespace clang