blob: a9e7b84808c18fdef411d29667fb55e8053d2b65 [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"
NAKAMURA Takumib175d0f2012-04-04 13:59:36 +000025#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi01b8ca52012-04-04 13:59:41 +000026#include "llvm/Support/Host.h"
27#include "llvm/Support/raw_ostream.h"
Manuel Klimekcb971c62012-04-04 12:07:46 +000028
Manuel Klimek3b6e3192012-05-07 09:45:46 +000029// For chdir, see the comment in ClangTool::run for more information.
Manuel Klimeked5ee482012-05-07 10:02:55 +000030#ifdef _WIN32
Manuel Klimek3b6e3192012-05-07 09:45:46 +000031# include <direct.h>
Manuel Klimeked5ee482012-05-07 10:02:55 +000032#else
33# include <unistd.h>
Manuel Klimek3b6e3192012-05-07 09:45:46 +000034#endif
35
Manuel Klimekcb971c62012-04-04 12:07:46 +000036namespace clang {
37namespace tooling {
38
39FrontendActionFactory::~FrontendActionFactory() {}
40
41// FIXME: This file contains structural duplication with other parts of the
42// code that sets up a compiler to run tools on it, and we should refactor
43// it to be based on the same framework.
44
45/// \brief Builds a clang driver initialized for running clang tools.
46static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
47 const char *BinaryName) {
48 const std::string DefaultOutputName = "a.out";
49 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Alexander Kornienko30c009b2012-06-04 19:02:59 +000050 BinaryName, llvm::sys::getDefaultTargetTriple(),
Rafael Espindola17c874a2012-11-27 16:10:37 +000051 DefaultOutputName, *Diagnostics);
Manuel Klimekcb971c62012-04-04 12:07:46 +000052 CompilerDriver->setTitle("clang_based_tool");
53 return CompilerDriver;
54}
55
56/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
57///
58/// Returns NULL on error.
59static const clang::driver::ArgStringList *getCC1Arguments(
60 clang::DiagnosticsEngine *Diagnostics,
61 clang::driver::Compilation *Compilation) {
62 // We expect to get back exactly one Command job, if we didn't something
63 // failed. Extract that job from the Compilation.
64 const clang::driver::JobList &Jobs = Compilation->getJobs();
65 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000066 SmallString<256> error_msg;
Manuel Klimekcb971c62012-04-04 12:07:46 +000067 llvm::raw_svector_ostream error_stream(error_msg);
68 Compilation->PrintJob(error_stream, Compilation->getJobs(), "; ", true);
69 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
70 << error_stream.str();
71 return NULL;
72 }
73
74 // The one job we find should be to invoke clang again.
75 const clang::driver::Command *Cmd =
76 cast<clang::driver::Command>(*Jobs.begin());
77 if (StringRef(Cmd->getCreator().getName()) != "clang") {
78 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
79 return NULL;
80 }
81
82 return &Cmd->getArguments();
83}
84
85/// \brief Returns a clang build invocation initialized from the CC1 flags.
86static clang::CompilerInvocation *newInvocation(
87 clang::DiagnosticsEngine *Diagnostics,
88 const clang::driver::ArgStringList &CC1Args) {
89 assert(!CC1Args.empty() && "Must at least contain the program name!");
90 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
91 clang::CompilerInvocation::CreateFromArgs(
92 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
93 *Diagnostics);
94 Invocation->getFrontendOpts().DisableFree = false;
95 return Invocation;
96}
97
98bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
99 const Twine &FileName) {
Nico Weber56669882012-08-30 02:02:19 +0000100 return runToolOnCodeWithArgs(
101 ToolAction, Code, std::vector<std::string>(), FileName);
102}
103
104bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
105 const std::vector<std::string> &Args,
106 const Twine &FileName) {
Manuel Klimekcb971c62012-04-04 12:07:46 +0000107 SmallString<16> FileNameStorage;
108 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Nico Weber56669882012-08-30 02:02:19 +0000109 std::vector<std::string> Commands;
110 Commands.push_back("clang-tool");
111 Commands.push_back("-fsyntax-only");
112 Commands.insert(Commands.end(), Args.begin(), Args.end());
113 Commands.push_back(FileNameRef.data());
Manuel Klimekcb971c62012-04-04 12:07:46 +0000114 FileManager Files((FileSystemOptions()));
Nico Weber56669882012-08-30 02:02:19 +0000115 ToolInvocation Invocation(Commands, ToolAction, &Files);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000116
117 SmallString<1024> CodeStorage;
118 Invocation.mapVirtualFile(FileNameRef,
119 Code.toNullTerminatedStringRef(CodeStorage));
120 return Invocation.run();
121}
122
Manuel Klimek8fa2fb82012-07-10 13:10:51 +0000123std::string getAbsolutePath(StringRef File) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000124 SmallString<1024> BaseDirectory;
Manuel Klimek8fa2fb82012-07-10 13:10:51 +0000125 if (const char *PWD = ::getenv("PWD"))
126 BaseDirectory = PWD;
127 else
128 llvm::sys::fs::current_path(BaseDirectory);
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000129 SmallString<1024> PathStorage;
Manuel Klimekcb971c62012-04-04 12:07:46 +0000130 if (llvm::sys::path::is_absolute(File)) {
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000131 llvm::sys::path::native(File, PathStorage);
132 return PathStorage.str();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000133 }
134 StringRef RelativePath(File);
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000135 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimekcb971c62012-04-04 12:07:46 +0000136 if (RelativePath.startswith("./")) {
137 RelativePath = RelativePath.substr(strlen("./"));
138 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000139 SmallString<1024> AbsolutePath(BaseDirectory);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000140 llvm::sys::path::append(AbsolutePath, RelativePath);
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000141 llvm::sys::path::native(Twine(AbsolutePath), PathStorage);
142 return PathStorage.str();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000143}
144
145ToolInvocation::ToolInvocation(
146 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
147 FileManager *Files)
148 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) {
149}
150
151void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi0ef8db22012-06-02 15:34:21 +0000152 SmallString<1024> PathStorage;
153 llvm::sys::path::native(FilePath, PathStorage);
154 MappedFileContents[PathStorage] = Content;
Manuel Klimekcb971c62012-04-04 12:07:46 +0000155}
156
157bool ToolInvocation::run() {
158 std::vector<const char*> Argv;
159 for (int I = 0, E = CommandLine.size(); I != E; ++I)
160 Argv.push_back(CommandLine[I].c_str());
161 const char *const BinaryName = Argv[0];
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000162 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000163 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000164 llvm::errs(), &*DiagOpts);
165 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000166 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000167 &*DiagOpts, &DiagnosticPrinter, false);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000168
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000169 const OwningPtr<clang::driver::Driver> Driver(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000170 newDriver(&Diagnostics, BinaryName));
171 // Since the input might only be virtual, don't check whether it exists.
172 Driver->setCheckInputsExist(false);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000173 const OwningPtr<clang::driver::Compilation> Compilation(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000174 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
175 const clang::driver::ArgStringList *const CC1Args = getCC1Arguments(
176 &Diagnostics, Compilation.get());
177 if (CC1Args == NULL) {
178 return false;
179 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000180 OwningPtr<clang::CompilerInvocation> Invocation(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000181 newInvocation(&Diagnostics, *CC1Args));
Sean Silvad47afb92013-01-20 01:58:28 +0000182 return runInvocation(BinaryName, Compilation.get(), Invocation.take());
Manuel Klimekcb971c62012-04-04 12:07:46 +0000183}
184
Manuel Klimekcb971c62012-04-04 12:07:46 +0000185bool ToolInvocation::runInvocation(
186 const char *BinaryName,
187 clang::driver::Compilation *Compilation,
Sean Silvad47afb92013-01-20 01:58:28 +0000188 clang::CompilerInvocation *Invocation) {
Manuel Klimekcb971c62012-04-04 12:07:46 +0000189 // Show the invocation, with -v.
190 if (Invocation->getHeaderSearchOpts().Verbose) {
191 llvm::errs() << "clang Invocation:\n";
192 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true);
193 llvm::errs() << "\n";
194 }
195
196 // Create a compiler instance to handle the actual work.
197 clang::CompilerInstance Compiler;
198 Compiler.setInvocation(Invocation);
199 Compiler.setFileManager(Files);
200 // FIXME: What about LangOpts?
201
Alexander Kornienko14a19242012-05-31 17:58:43 +0000202 // ToolAction can have lifetime requirements for Compiler or its members, and
203 // we need to ensure it's deleted earlier than Compiler. So we pass it to an
204 // OwningPtr declared after the Compiler variable.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000205 OwningPtr<FrontendAction> ScopedToolAction(ToolAction.take());
Alexander Kornienko14a19242012-05-31 17:58:43 +0000206
Manuel Klimekcb971c62012-04-04 12:07:46 +0000207 // Create the compilers actual diagnostics engine.
Sean Silvad47afb92013-01-20 01:58:28 +0000208 Compiler.createDiagnostics();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000209 if (!Compiler.hasDiagnostics())
210 return false;
211
212 Compiler.createSourceManager(*Files);
213 addFileMappingsTo(Compiler.getSourceManager());
214
Alexander Kornienko14a19242012-05-31 17:58:43 +0000215 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000216
217 Compiler.resetAndLeakFileManager();
Manuel Klimek98be8602012-07-31 13:56:54 +0000218 Files->clearStatCaches();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000219 return Success;
220}
221
222void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
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 // FIXME: figure out what '0' stands for.
230 const FileEntry *FromFile = Files->getVirtualFile(
231 It->getKey(), Input->getBufferSize(), 0);
Alexander Kornienko240193b2012-05-30 12:10:28 +0000232 Sources.overrideFileContents(FromFile, Input);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000233 }
234}
235
236ClangTool::ClangTool(const CompilationDatabase &Compilations,
237 ArrayRef<std::string> SourcePaths)
Simon Atanasyana01ddc72012-05-09 16:18:30 +0000238 : Files((FileSystemOptions())),
239 ArgsAdjuster(new ClangSyntaxOnlyAdjuster()) {
Manuel Klimekcb971c62012-04-04 12:07:46 +0000240 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000241 SmallString<1024> File(getAbsolutePath(SourcePaths[I]));
Manuel Klimekcb971c62012-04-04 12:07:46 +0000242
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000243 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimekcb971c62012-04-04 12:07:46 +0000244 Compilations.getCompileCommands(File.str());
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000245 if (!CompileCommandsForFile.empty()) {
246 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
247 CompileCommands.push_back(std::make_pair(File.str(),
248 CompileCommandsForFile[I]));
Manuel Klimekcb971c62012-04-04 12:07:46 +0000249 }
250 } else {
251 // FIXME: There are two use cases here: doing a fuzzy
252 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
253 // about the .cc files that were not found, and the use case where I
254 // specify all files I want to run over explicitly, where this should
255 // be an error. We'll want to add an option for this.
256 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
257 }
258 }
259}
260
261void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
262 MappedFileContents.push_back(std::make_pair(FilePath, Content));
263}
264
Simon Atanasyana01ddc72012-05-09 16:18:30 +0000265void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
266 ArgsAdjuster.reset(Adjuster);
267}
268
Manuel Klimekcb971c62012-04-04 12:07:46 +0000269int ClangTool::run(FrontendActionFactory *ActionFactory) {
Alexander Kornienko30c009b2012-06-04 19:02:59 +0000270 // Exists solely for the purpose of lookup of the resource path.
271 // This just needs to be some symbol in the binary.
272 static int StaticSymbol;
273 // The driver detects the builtin header path based on the path of the
274 // executable.
275 // FIXME: On linux, GetMainExecutable is independent of the value of the
276 // first argument, thus allowing ClangTool and runToolOnCode to just
277 // pass in made-up names here. Make sure this works on other platforms.
278 std::string MainExecutable =
279 llvm::sys::Path::GetMainExecutable("clang_tool", &StaticSymbol).str();
280
Manuel Klimekcb971c62012-04-04 12:07:46 +0000281 bool ProcessingFailed = false;
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000282 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
283 std::string File = CompileCommands[I].first;
284 // FIXME: chdir is thread hostile; on the other hand, creating the same
285 // behavior as chdir is complex: chdir resolves the path once, thus
286 // guaranteeing that all subsequent relative path operations work
287 // on the same path the original chdir resulted in. This makes a difference
Alexander Kornienko30c009b2012-06-04 19:02:59 +0000288 // for example on network filesystems, where symlinks might be switched
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000289 // during runtime of the tool. Fixing this depends on having a file system
290 // abstraction that allows openat() style interactions.
291 if (chdir(CompileCommands[I].second.Directory.c_str()))
292 llvm::report_fatal_error("Cannot chdir into \"" +
293 CompileCommands[I].second.Directory + "\n!");
Simon Atanasyana01ddc72012-05-09 16:18:30 +0000294 std::vector<std::string> CommandLine =
295 ArgsAdjuster->Adjust(CompileCommands[I].second.CommandLine);
Alexander Kornienko30c009b2012-06-04 19:02:59 +0000296 assert(!CommandLine.empty());
297 CommandLine[0] = MainExecutable;
Edwin Vanec45df062013-03-13 13:48:47 +0000298 llvm::outs() << "Processing: " << File << ".\n";
Manuel Klimekcb971c62012-04-04 12:07:46 +0000299 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
300 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
301 Invocation.mapVirtualFile(MappedFileContents[I].first,
302 MappedFileContents[I].second);
303 }
304 if (!Invocation.run()) {
Edwin Vanec45df062013-03-13 13:48:47 +0000305 llvm::outs() << "Error while processing " << File << ".\n";
Manuel Klimekcb971c62012-04-04 12:07:46 +0000306 ProcessingFailed = true;
307 }
308 }
309 return ProcessingFailed ? 1 : 0;
310}
311
312} // end namespace tooling
313} // end namespace clang