blob: a4a63e249f86f89647bd93d0324a866f135c995e [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) {
169 MappedFileContents[FilePath] = Content;
170}
171
172bool ToolInvocation::run() {
173 std::vector<const char*> Argv;
174 for (int I = 0, E = CommandLine.size(); I != E; ++I)
175 Argv.push_back(CommandLine[I].c_str());
176 const char *const BinaryName = Argv[0];
177 DiagnosticOptions DefaultDiagnosticOptions;
178 TextDiagnosticPrinter DiagnosticPrinter(
179 llvm::errs(), DefaultDiagnosticOptions);
180 DiagnosticsEngine Diagnostics(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(
181 new DiagnosticIDs()), &DiagnosticPrinter, false);
182
183 const llvm::OwningPtr<clang::driver::Driver> Driver(
184 newDriver(&Diagnostics, BinaryName));
185 // Since the input might only be virtual, don't check whether it exists.
186 Driver->setCheckInputsExist(false);
187 const llvm::OwningPtr<clang::driver::Compilation> Compilation(
188 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
189 const clang::driver::ArgStringList *const CC1Args = getCC1Arguments(
190 &Diagnostics, Compilation.get());
191 if (CC1Args == NULL) {
192 return false;
193 }
194 llvm::OwningPtr<clang::CompilerInvocation> Invocation(
195 newInvocation(&Diagnostics, *CC1Args));
196 return runInvocation(BinaryName, Compilation.get(),
197 Invocation.take(), *CC1Args, ToolAction.take());
198}
199
Manuel Klimek47c245a2012-04-04 12:07:46 +0000200bool ToolInvocation::runInvocation(
201 const char *BinaryName,
202 clang::driver::Compilation *Compilation,
203 clang::CompilerInvocation *Invocation,
204 const clang::driver::ArgStringList &CC1Args,
205 clang::FrontendAction *ToolAction) {
206 llvm::OwningPtr<clang::FrontendAction> ScopedToolAction(ToolAction);
207 // 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
220 // Create the compilers actual diagnostics engine.
221 Compiler.createDiagnostics(CC1Args.size(),
222 const_cast<char**>(CC1Args.data()));
223 if (!Compiler.hasDiagnostics())
224 return false;
225
226 Compiler.createSourceManager(*Files);
227 addFileMappingsTo(Compiler.getSourceManager());
228
229 // Infer the builtin include path if unspecified.
230 if (Compiler.getHeaderSearchOpts().UseBuiltinIncludes &&
231 Compiler.getHeaderSearchOpts().ResourceDir.empty()) {
232 // This just needs to be some symbol in the binary.
233 void *const SymbolAddr = &StaticSymbol;
234 Compiler.getHeaderSearchOpts().ResourceDir =
235 clang::CompilerInvocation::GetResourcesPath(BinaryName, SymbolAddr);
236 }
237
238 const bool Success = Compiler.ExecuteAction(*ToolAction);
239
240 Compiler.resetAndLeakFileManager();
241 return Success;
242}
243
244void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
245 for (llvm::StringMap<StringRef>::const_iterator
246 It = MappedFileContents.begin(), End = MappedFileContents.end();
247 It != End; ++It) {
248 // Inject the code as the given file name into the preprocessor options.
249 const llvm::MemoryBuffer *Input =
250 llvm::MemoryBuffer::getMemBuffer(It->getValue());
251 // FIXME: figure out what '0' stands for.
252 const FileEntry *FromFile = Files->getVirtualFile(
253 It->getKey(), Input->getBufferSize(), 0);
254 // FIXME: figure out memory management ('true').
255 Sources.overrideFileContents(FromFile, Input, true);
256 }
257}
258
259ClangTool::ClangTool(const CompilationDatabase &Compilations,
260 ArrayRef<std::string> SourcePaths)
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000261 : Files((FileSystemOptions())),
262 ArgsAdjuster(new ClangSyntaxOnlyAdjuster()) {
NAKAMURA Takumif0c87792012-04-04 13:59:36 +0000263 llvm::SmallString<1024> BaseDirectory;
Manuel Klimek3521ae92012-04-09 18:08:23 +0000264 if (const char *PWD = ::getenv("PWD"))
265 BaseDirectory = PWD;
266 else
267 llvm::sys::fs::current_path(BaseDirectory);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000268 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
269 llvm::SmallString<1024> File(getAbsolutePath(
270 SourcePaths[I], BaseDirectory));
271
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000272 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimek47c245a2012-04-04 12:07:46 +0000273 Compilations.getCompileCommands(File.str());
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000274 if (!CompileCommandsForFile.empty()) {
275 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
276 CompileCommands.push_back(std::make_pair(File.str(),
277 CompileCommandsForFile[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000278 }
279 } else {
280 // FIXME: There are two use cases here: doing a fuzzy
281 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
282 // about the .cc files that were not found, and the use case where I
283 // specify all files I want to run over explicitly, where this should
284 // be an error. We'll want to add an option for this.
285 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
286 }
287 }
288}
289
290void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
291 MappedFileContents.push_back(std::make_pair(FilePath, Content));
292}
293
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000294void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
295 ArgsAdjuster.reset(Adjuster);
296}
297
Manuel Klimek47c245a2012-04-04 12:07:46 +0000298int ClangTool::run(FrontendActionFactory *ActionFactory) {
299 bool ProcessingFailed = false;
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000300 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
301 std::string File = CompileCommands[I].first;
302 // FIXME: chdir is thread hostile; on the other hand, creating the same
303 // behavior as chdir is complex: chdir resolves the path once, thus
304 // guaranteeing that all subsequent relative path operations work
305 // on the same path the original chdir resulted in. This makes a difference
306 // for example on network filesystems, where symlinks might be switched
307 // during runtime of the tool. Fixing this depends on having a file system
308 // abstraction that allows openat() style interactions.
309 if (chdir(CompileCommands[I].second.Directory.c_str()))
310 llvm::report_fatal_error("Cannot chdir into \"" +
311 CompileCommands[I].second.Directory + "\n!");
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000312 std::vector<std::string> CommandLine =
313 ArgsAdjuster->Adjust(CompileCommands[I].second.CommandLine);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000314 llvm::outs() << "Processing: " << File << ".\n";
315 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
316 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
317 Invocation.mapVirtualFile(MappedFileContents[I].first,
318 MappedFileContents[I].second);
319 }
320 if (!Invocation.run()) {
321 llvm::outs() << "Error while processing " << File << ".\n";
322 ProcessingFailed = true;
323 }
324 }
325 return ProcessingFailed ? 1 : 0;
326}
327
328} // end namespace tooling
329} // end namespace clang