blob: a449e105bf5a8027d62f0f6531945a57624748a1 [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
Simon Atanasyan32df72d2012-05-09 16:18:30 +000015#include "clang/Tooling/ArgumentsAdjusters.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000016#include "clang/Tooling/Tooling.h"
17#include "clang/Tooling/CompilationDatabase.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000018#include "clang/Driver/Compilation.h"
19#include "clang/Driver/Driver.h"
20#include "clang/Driver/Tool.h"
21#include "clang/Frontend/CompilerInstance.h"
22#include "clang/Frontend/FrontendAction.h"
23#include "clang/Frontend/FrontendDiagnostic.h"
24#include "clang/Frontend/TextDiagnosticPrinter.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000025#include "llvm/ADT/STLExtras.h"
NAKAMURA Takumif0c87792012-04-04 13:59:36 +000026#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000027#include "llvm/Support/Host.h"
28#include "llvm/Support/raw_ostream.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000029
Manuel Klimek74cec542012-05-07 09:45:46 +000030// For chdir, see the comment in ClangTool::run for more information.
Manuel Klimekf33dcb02012-05-07 10:02:55 +000031#ifdef _WIN32
Manuel Klimek74cec542012-05-07 09:45:46 +000032# include <direct.h>
Manuel Klimekf33dcb02012-05-07 10:02:55 +000033#else
34# include <unistd.h>
Manuel Klimek74cec542012-05-07 09:45:46 +000035#endif
36
Manuel Klimek47c245a2012-04-04 12:07:46 +000037namespace clang {
38namespace tooling {
39
40FrontendActionFactory::~FrontendActionFactory() {}
41
42// FIXME: This file contains structural duplication with other parts of the
43// code that sets up a compiler to run tools on it, and we should refactor
44// it to be based on the same framework.
45
46/// \brief Builds a clang driver initialized for running clang tools.
47static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
48 const char *BinaryName) {
49 const std::string DefaultOutputName = "a.out";
50 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Alexander Kornienko8388d242012-06-04 19:02:59 +000051 BinaryName, llvm::sys::getDefaultTargetTriple(),
Manuel Klimek3778a432012-04-25 09:25:41 +000052 DefaultOutputName, false, *Diagnostics);
Manuel Klimek47c245a2012-04-04 12:07:46 +000053 CompilerDriver->setTitle("clang_based_tool");
54 return CompilerDriver;
55}
56
57/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
58///
59/// Returns NULL on error.
60static const clang::driver::ArgStringList *getCC1Arguments(
61 clang::DiagnosticsEngine *Diagnostics,
62 clang::driver::Compilation *Compilation) {
63 // We expect to get back exactly one Command job, if we didn't something
64 // failed. Extract that job from the Compilation.
65 const clang::driver::JobList &Jobs = Compilation->getJobs();
66 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
67 llvm::SmallString<256> error_msg;
68 llvm::raw_svector_ostream error_stream(error_msg);
69 Compilation->PrintJob(error_stream, Compilation->getJobs(), "; ", true);
70 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
71 << error_stream.str();
72 return NULL;
73 }
74
75 // The one job we find should be to invoke clang again.
76 const clang::driver::Command *Cmd =
77 cast<clang::driver::Command>(*Jobs.begin());
78 if (StringRef(Cmd->getCreator().getName()) != "clang") {
79 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
80 return NULL;
81 }
82
83 return &Cmd->getArguments();
84}
85
86/// \brief Returns a clang build invocation initialized from the CC1 flags.
87static clang::CompilerInvocation *newInvocation(
88 clang::DiagnosticsEngine *Diagnostics,
89 const clang::driver::ArgStringList &CC1Args) {
90 assert(!CC1Args.empty() && "Must at least contain the program name!");
91 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
92 clang::CompilerInvocation::CreateFromArgs(
93 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
94 *Diagnostics);
95 Invocation->getFrontendOpts().DisableFree = false;
96 return Invocation;
97}
98
99bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
100 const Twine &FileName) {
101 SmallString<16> FileNameStorage;
102 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
103 const char *const CommandLine[] = {
104 "clang-tool", "-fsyntax-only", FileNameRef.data()
105 };
106 FileManager Files((FileSystemOptions()));
107 ToolInvocation Invocation(
108 std::vector<std::string>(
109 CommandLine,
110 CommandLine + llvm::array_lengthof(CommandLine)),
111 ToolAction, &Files);
112
113 SmallString<1024> CodeStorage;
114 Invocation.mapVirtualFile(FileNameRef,
115 Code.toNullTerminatedStringRef(CodeStorage));
116 return Invocation.run();
117}
118
119/// \brief Returns the absolute path of 'File', by prepending it with
120/// 'BaseDirectory' if 'File' is not absolute.
121///
122/// Otherwise returns 'File'.
123/// If 'File' starts with "./", the returned path will not contain the "./".
124/// Otherwise, the returned path will contain the literal path-concatenation of
125/// 'BaseDirectory' and 'File'.
126///
127/// \param File Either an absolute or relative path.
128/// \param BaseDirectory An absolute path.
129static std::string getAbsolutePath(
130 StringRef File, StringRef BaseDirectory) {
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000131 SmallString<1024> PathStorage;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000132 assert(llvm::sys::path::is_absolute(BaseDirectory));
133 if (llvm::sys::path::is_absolute(File)) {
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000134 llvm::sys::path::native(File, PathStorage);
135 return PathStorage.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000136 }
137 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000138 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000139 if (RelativePath.startswith("./")) {
140 RelativePath = RelativePath.substr(strlen("./"));
141 }
142 llvm::SmallString<1024> AbsolutePath(BaseDirectory);
143 llvm::sys::path::append(AbsolutePath, RelativePath);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000144 llvm::sys::path::native(Twine(AbsolutePath), PathStorage);
145 return PathStorage.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000146}
147
148ToolInvocation::ToolInvocation(
149 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
150 FileManager *Files)
151 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) {
152}
153
154void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000155 SmallString<1024> PathStorage;
156 llvm::sys::path::native(FilePath, PathStorage);
157 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000158}
159
160bool ToolInvocation::run() {
161 std::vector<const char*> Argv;
162 for (int I = 0, E = CommandLine.size(); I != E; ++I)
163 Argv.push_back(CommandLine[I].c_str());
164 const char *const BinaryName = Argv[0];
165 DiagnosticOptions DefaultDiagnosticOptions;
166 TextDiagnosticPrinter DiagnosticPrinter(
167 llvm::errs(), DefaultDiagnosticOptions);
168 DiagnosticsEngine Diagnostics(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(
169 new DiagnosticIDs()), &DiagnosticPrinter, false);
170
171 const llvm::OwningPtr<clang::driver::Driver> Driver(
172 newDriver(&Diagnostics, BinaryName));
173 // Since the input might only be virtual, don't check whether it exists.
174 Driver->setCheckInputsExist(false);
175 const llvm::OwningPtr<clang::driver::Compilation> Compilation(
176 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
177 const clang::driver::ArgStringList *const CC1Args = getCC1Arguments(
178 &Diagnostics, Compilation.get());
179 if (CC1Args == NULL) {
180 return false;
181 }
182 llvm::OwningPtr<clang::CompilerInvocation> Invocation(
183 newInvocation(&Diagnostics, *CC1Args));
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000184 return runInvocation(BinaryName, Compilation.get(), Invocation.take(),
185 *CC1Args);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000186}
187
Manuel Klimek47c245a2012-04-04 12:07:46 +0000188bool ToolInvocation::runInvocation(
189 const char *BinaryName,
190 clang::driver::Compilation *Compilation,
191 clang::CompilerInvocation *Invocation,
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000192 const clang::driver::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000193 // Show the invocation, with -v.
194 if (Invocation->getHeaderSearchOpts().Verbose) {
195 llvm::errs() << "clang Invocation:\n";
196 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true);
197 llvm::errs() << "\n";
198 }
199
200 // Create a compiler instance to handle the actual work.
201 clang::CompilerInstance Compiler;
202 Compiler.setInvocation(Invocation);
203 Compiler.setFileManager(Files);
204 // FIXME: What about LangOpts?
205
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000206 // ToolAction can have lifetime requirements for Compiler or its members, and
207 // we need to ensure it's deleted earlier than Compiler. So we pass it to an
208 // OwningPtr declared after the Compiler variable.
209 llvm::OwningPtr<FrontendAction> ScopedToolAction(ToolAction.take());
210
Manuel Klimek47c245a2012-04-04 12:07:46 +0000211 // Create the compilers actual diagnostics engine.
212 Compiler.createDiagnostics(CC1Args.size(),
213 const_cast<char**>(CC1Args.data()));
214 if (!Compiler.hasDiagnostics())
215 return false;
216
217 Compiler.createSourceManager(*Files);
218 addFileMappingsTo(Compiler.getSourceManager());
219
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000220 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000221
222 Compiler.resetAndLeakFileManager();
223 return Success;
224}
225
226void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
227 for (llvm::StringMap<StringRef>::const_iterator
228 It = MappedFileContents.begin(), End = MappedFileContents.end();
229 It != End; ++It) {
230 // Inject the code as the given file name into the preprocessor options.
231 const llvm::MemoryBuffer *Input =
232 llvm::MemoryBuffer::getMemBuffer(It->getValue());
233 // FIXME: figure out what '0' stands for.
234 const FileEntry *FromFile = Files->getVirtualFile(
235 It->getKey(), Input->getBufferSize(), 0);
Alexander Kornienko9e8d2282012-05-30 12:10:28 +0000236 Sources.overrideFileContents(FromFile, Input);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000237 }
238}
239
240ClangTool::ClangTool(const CompilationDatabase &Compilations,
241 ArrayRef<std::string> SourcePaths)
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000242 : Files((FileSystemOptions())),
243 ArgsAdjuster(new ClangSyntaxOnlyAdjuster()) {
NAKAMURA Takumif0c87792012-04-04 13:59:36 +0000244 llvm::SmallString<1024> BaseDirectory;
Manuel Klimek3521ae92012-04-09 18:08:23 +0000245 if (const char *PWD = ::getenv("PWD"))
246 BaseDirectory = PWD;
247 else
248 llvm::sys::fs::current_path(BaseDirectory);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000249 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
250 llvm::SmallString<1024> File(getAbsolutePath(
251 SourcePaths[I], BaseDirectory));
252
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000253 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimek47c245a2012-04-04 12:07:46 +0000254 Compilations.getCompileCommands(File.str());
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000255 if (!CompileCommandsForFile.empty()) {
256 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
257 CompileCommands.push_back(std::make_pair(File.str(),
258 CompileCommandsForFile[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000259 }
260 } else {
261 // FIXME: There are two use cases here: doing a fuzzy
262 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
263 // about the .cc files that were not found, and the use case where I
264 // specify all files I want to run over explicitly, where this should
265 // be an error. We'll want to add an option for this.
266 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
267 }
268 }
269}
270
271void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
272 MappedFileContents.push_back(std::make_pair(FilePath, Content));
273}
274
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000275void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
276 ArgsAdjuster.reset(Adjuster);
277}
278
Manuel Klimek47c245a2012-04-04 12:07:46 +0000279int ClangTool::run(FrontendActionFactory *ActionFactory) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000280 // Exists solely for the purpose of lookup of the resource path.
281 // This just needs to be some symbol in the binary.
282 static int StaticSymbol;
283 // The driver detects the builtin header path based on the path of the
284 // executable.
285 // FIXME: On linux, GetMainExecutable is independent of the value of the
286 // first argument, thus allowing ClangTool and runToolOnCode to just
287 // pass in made-up names here. Make sure this works on other platforms.
288 std::string MainExecutable =
289 llvm::sys::Path::GetMainExecutable("clang_tool", &StaticSymbol).str();
290
Manuel Klimek47c245a2012-04-04 12:07:46 +0000291 bool ProcessingFailed = false;
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000292 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
293 std::string File = CompileCommands[I].first;
294 // FIXME: chdir is thread hostile; on the other hand, creating the same
295 // behavior as chdir is complex: chdir resolves the path once, thus
296 // guaranteeing that all subsequent relative path operations work
297 // on the same path the original chdir resulted in. This makes a difference
Alexander Kornienko8388d242012-06-04 19:02:59 +0000298 // for example on network filesystems, where symlinks might be switched
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000299 // during runtime of the tool. Fixing this depends on having a file system
300 // abstraction that allows openat() style interactions.
301 if (chdir(CompileCommands[I].second.Directory.c_str()))
302 llvm::report_fatal_error("Cannot chdir into \"" +
303 CompileCommands[I].second.Directory + "\n!");
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000304 std::vector<std::string> CommandLine =
305 ArgsAdjuster->Adjust(CompileCommands[I].second.CommandLine);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000306 assert(!CommandLine.empty());
307 CommandLine[0] = MainExecutable;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000308 llvm::outs() << "Processing: " << File << ".\n";
309 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
310 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
311 Invocation.mapVirtualFile(MappedFileContents[I].first,
312 MappedFileContents[I].second);
313 }
314 if (!Invocation.run()) {
315 llvm::outs() << "Error while processing " << File << ".\n";
316 ProcessingFailed = true;
317 }
318 }
319 return ProcessingFailed ? 1 : 0;
320}
321
322} // end namespace tooling
323} // end namespace clang