blob: 0c9fa43606544227caa04aecee2ade8fc65f92da [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
Manuel Klimek3778a432012-04-25 09:25:41 +000040// Exists solely for the purpose of lookup of the resource path.
41static int StaticSymbol;
42
Manuel Klimek47c245a2012-04-04 12:07:46 +000043FrontendActionFactory::~FrontendActionFactory() {}
44
45// FIXME: This file contains structural duplication with other parts of the
46// code that sets up a compiler to run tools on it, and we should refactor
47// it to be based on the same framework.
48
49/// \brief Builds a clang driver initialized for running clang tools.
50static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
51 const char *BinaryName) {
52 const std::string DefaultOutputName = "a.out";
Manuel Klimek3778a432012-04-25 09:25:41 +000053 // This just needs to be some symbol in the binary.
54 void *const SymbolAddr = &StaticSymbol;
55 // The driver detects the builtin header path based on the path of
56 // the executable.
57 // FIXME: On linux, GetMainExecutable is independent of the content
58 // of BinaryName, thus allowing ClangTool and runToolOnCode to just
59 // pass in made-up names here (in the case of ClangTool this being
60 // the original compiler invocation). Make sure this works on other
61 // platforms.
62 llvm::sys::Path MainExecutable =
63 llvm::sys::Path::GetMainExecutable(BinaryName, SymbolAddr);
Manuel Klimek47c245a2012-04-04 12:07:46 +000064 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Manuel Klimek3778a432012-04-25 09:25:41 +000065 MainExecutable.str(), llvm::sys::getDefaultTargetTriple(),
66 DefaultOutputName, false, *Diagnostics);
Manuel Klimek47c245a2012-04-04 12:07:46 +000067 CompilerDriver->setTitle("clang_based_tool");
68 return CompilerDriver;
69}
70
71/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
72///
73/// Returns NULL on error.
74static const clang::driver::ArgStringList *getCC1Arguments(
75 clang::DiagnosticsEngine *Diagnostics,
76 clang::driver::Compilation *Compilation) {
77 // We expect to get back exactly one Command job, if we didn't something
78 // failed. Extract that job from the Compilation.
79 const clang::driver::JobList &Jobs = Compilation->getJobs();
80 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
81 llvm::SmallString<256> error_msg;
82 llvm::raw_svector_ostream error_stream(error_msg);
83 Compilation->PrintJob(error_stream, Compilation->getJobs(), "; ", true);
84 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
85 << error_stream.str();
86 return NULL;
87 }
88
89 // The one job we find should be to invoke clang again.
90 const clang::driver::Command *Cmd =
91 cast<clang::driver::Command>(*Jobs.begin());
92 if (StringRef(Cmd->getCreator().getName()) != "clang") {
93 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
94 return NULL;
95 }
96
97 return &Cmd->getArguments();
98}
99
100/// \brief Returns a clang build invocation initialized from the CC1 flags.
101static clang::CompilerInvocation *newInvocation(
102 clang::DiagnosticsEngine *Diagnostics,
103 const clang::driver::ArgStringList &CC1Args) {
104 assert(!CC1Args.empty() && "Must at least contain the program name!");
105 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
106 clang::CompilerInvocation::CreateFromArgs(
107 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
108 *Diagnostics);
109 Invocation->getFrontendOpts().DisableFree = false;
110 return Invocation;
111}
112
113bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
114 const Twine &FileName) {
115 SmallString<16> FileNameStorage;
116 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
117 const char *const CommandLine[] = {
118 "clang-tool", "-fsyntax-only", FileNameRef.data()
119 };
120 FileManager Files((FileSystemOptions()));
121 ToolInvocation Invocation(
122 std::vector<std::string>(
123 CommandLine,
124 CommandLine + llvm::array_lengthof(CommandLine)),
125 ToolAction, &Files);
126
127 SmallString<1024> CodeStorage;
128 Invocation.mapVirtualFile(FileNameRef,
129 Code.toNullTerminatedStringRef(CodeStorage));
130 return Invocation.run();
131}
132
133/// \brief Returns the absolute path of 'File', by prepending it with
134/// 'BaseDirectory' if 'File' is not absolute.
135///
136/// Otherwise returns 'File'.
137/// If 'File' starts with "./", the returned path will not contain the "./".
138/// Otherwise, the returned path will contain the literal path-concatenation of
139/// 'BaseDirectory' and 'File'.
140///
141/// \param File Either an absolute or relative path.
142/// \param BaseDirectory An absolute path.
143static std::string getAbsolutePath(
144 StringRef File, StringRef BaseDirectory) {
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000145 SmallString<1024> PathStorage;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000146 assert(llvm::sys::path::is_absolute(BaseDirectory));
147 if (llvm::sys::path::is_absolute(File)) {
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000148 llvm::sys::path::native(File, PathStorage);
149 return PathStorage.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000150 }
151 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000152 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000153 if (RelativePath.startswith("./")) {
154 RelativePath = RelativePath.substr(strlen("./"));
155 }
156 llvm::SmallString<1024> AbsolutePath(BaseDirectory);
157 llvm::sys::path::append(AbsolutePath, RelativePath);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000158 llvm::sys::path::native(Twine(AbsolutePath), PathStorage);
159 return PathStorage.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000160}
161
162ToolInvocation::ToolInvocation(
163 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
164 FileManager *Files)
165 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) {
166}
167
168void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000169 SmallString<1024> PathStorage;
170 llvm::sys::path::native(FilePath, PathStorage);
171 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000172}
173
174bool ToolInvocation::run() {
175 std::vector<const char*> Argv;
176 for (int I = 0, E = CommandLine.size(); I != E; ++I)
177 Argv.push_back(CommandLine[I].c_str());
178 const char *const BinaryName = Argv[0];
179 DiagnosticOptions DefaultDiagnosticOptions;
180 TextDiagnosticPrinter DiagnosticPrinter(
181 llvm::errs(), DefaultDiagnosticOptions);
182 DiagnosticsEngine Diagnostics(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(
183 new DiagnosticIDs()), &DiagnosticPrinter, false);
184
185 const llvm::OwningPtr<clang::driver::Driver> Driver(
186 newDriver(&Diagnostics, BinaryName));
187 // Since the input might only be virtual, don't check whether it exists.
188 Driver->setCheckInputsExist(false);
189 const llvm::OwningPtr<clang::driver::Compilation> Compilation(
190 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
191 const clang::driver::ArgStringList *const CC1Args = getCC1Arguments(
192 &Diagnostics, Compilation.get());
193 if (CC1Args == NULL) {
194 return false;
195 }
196 llvm::OwningPtr<clang::CompilerInvocation> Invocation(
197 newInvocation(&Diagnostics, *CC1Args));
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000198 return runInvocation(BinaryName, Compilation.get(), Invocation.take(),
199 *CC1Args);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000200}
201
Manuel Klimek47c245a2012-04-04 12:07:46 +0000202bool ToolInvocation::runInvocation(
203 const char *BinaryName,
204 clang::driver::Compilation *Compilation,
205 clang::CompilerInvocation *Invocation,
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000206 const clang::driver::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000207 // Show the invocation, with -v.
208 if (Invocation->getHeaderSearchOpts().Verbose) {
209 llvm::errs() << "clang Invocation:\n";
210 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true);
211 llvm::errs() << "\n";
212 }
213
214 // Create a compiler instance to handle the actual work.
215 clang::CompilerInstance Compiler;
216 Compiler.setInvocation(Invocation);
217 Compiler.setFileManager(Files);
218 // FIXME: What about LangOpts?
219
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000220 // ToolAction can have lifetime requirements for Compiler or its members, and
221 // we need to ensure it's deleted earlier than Compiler. So we pass it to an
222 // OwningPtr declared after the Compiler variable.
223 llvm::OwningPtr<FrontendAction> ScopedToolAction(ToolAction.take());
224
Manuel Klimek47c245a2012-04-04 12:07:46 +0000225 // Create the compilers actual diagnostics engine.
226 Compiler.createDiagnostics(CC1Args.size(),
227 const_cast<char**>(CC1Args.data()));
228 if (!Compiler.hasDiagnostics())
229 return false;
230
231 Compiler.createSourceManager(*Files);
232 addFileMappingsTo(Compiler.getSourceManager());
233
234 // Infer the builtin include path if unspecified.
235 if (Compiler.getHeaderSearchOpts().UseBuiltinIncludes &&
236 Compiler.getHeaderSearchOpts().ResourceDir.empty()) {
237 // This just needs to be some symbol in the binary.
238 void *const SymbolAddr = &StaticSymbol;
239 Compiler.getHeaderSearchOpts().ResourceDir =
240 clang::CompilerInvocation::GetResourcesPath(BinaryName, SymbolAddr);
241 }
242
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000243 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000244
245 Compiler.resetAndLeakFileManager();
246 return Success;
247}
248
249void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
250 for (llvm::StringMap<StringRef>::const_iterator
251 It = MappedFileContents.begin(), End = MappedFileContents.end();
252 It != End; ++It) {
253 // Inject the code as the given file name into the preprocessor options.
254 const llvm::MemoryBuffer *Input =
255 llvm::MemoryBuffer::getMemBuffer(It->getValue());
256 // FIXME: figure out what '0' stands for.
257 const FileEntry *FromFile = Files->getVirtualFile(
258 It->getKey(), Input->getBufferSize(), 0);
Alexander Kornienko9e8d2282012-05-30 12:10:28 +0000259 Sources.overrideFileContents(FromFile, Input);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000260 }
261}
262
263ClangTool::ClangTool(const CompilationDatabase &Compilations,
264 ArrayRef<std::string> SourcePaths)
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000265 : Files((FileSystemOptions())),
266 ArgsAdjuster(new ClangSyntaxOnlyAdjuster()) {
NAKAMURA Takumif0c87792012-04-04 13:59:36 +0000267 llvm::SmallString<1024> BaseDirectory;
Manuel Klimek3521ae92012-04-09 18:08:23 +0000268 if (const char *PWD = ::getenv("PWD"))
269 BaseDirectory = PWD;
270 else
271 llvm::sys::fs::current_path(BaseDirectory);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000272 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
273 llvm::SmallString<1024> File(getAbsolutePath(
274 SourcePaths[I], BaseDirectory));
275
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000276 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimek47c245a2012-04-04 12:07:46 +0000277 Compilations.getCompileCommands(File.str());
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000278 if (!CompileCommandsForFile.empty()) {
279 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
280 CompileCommands.push_back(std::make_pair(File.str(),
281 CompileCommandsForFile[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000282 }
283 } else {
284 // FIXME: There are two use cases here: doing a fuzzy
285 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
286 // about the .cc files that were not found, and the use case where I
287 // specify all files I want to run over explicitly, where this should
288 // be an error. We'll want to add an option for this.
289 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
290 }
291 }
292}
293
294void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
295 MappedFileContents.push_back(std::make_pair(FilePath, Content));
296}
297
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000298void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
299 ArgsAdjuster.reset(Adjuster);
300}
301
Manuel Klimek47c245a2012-04-04 12:07:46 +0000302int ClangTool::run(FrontendActionFactory *ActionFactory) {
303 bool ProcessingFailed = false;
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000304 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
305 std::string File = CompileCommands[I].first;
306 // FIXME: chdir is thread hostile; on the other hand, creating the same
307 // behavior as chdir is complex: chdir resolves the path once, thus
308 // guaranteeing that all subsequent relative path operations work
309 // on the same path the original chdir resulted in. This makes a difference
310 // for example on network filesystems, where symlinks might be switched
311 // during runtime of the tool. Fixing this depends on having a file system
312 // abstraction that allows openat() style interactions.
313 if (chdir(CompileCommands[I].second.Directory.c_str()))
314 llvm::report_fatal_error("Cannot chdir into \"" +
315 CompileCommands[I].second.Directory + "\n!");
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000316 std::vector<std::string> CommandLine =
317 ArgsAdjuster->Adjust(CompileCommands[I].second.CommandLine);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000318 llvm::outs() << "Processing: " << File << ".\n";
319 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
320 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
321 Invocation.mapVirtualFile(MappedFileContents[I].first,
322 MappedFileContents[I].second);
323 }
324 if (!Invocation.run()) {
325 llvm::outs() << "Error while processing " << File << ".\n";
326 ProcessingFailed = true;
327 }
328 }
329 return ProcessingFailed ? 1 : 0;
330}
331
332} // end namespace tooling
333} // end namespace clang