blob: 9b4d4e2e239a1343fc03da9a35bc12d72ba2e746 [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
15#include "clang/Tooling/Tooling.h"
16#include "clang/Tooling/CompilationDatabase.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000017#include "clang/Driver/Compilation.h"
18#include "clang/Driver/Driver.h"
19#include "clang/Driver/Tool.h"
20#include "clang/Frontend/CompilerInstance.h"
21#include "clang/Frontend/FrontendAction.h"
22#include "clang/Frontend/FrontendDiagnostic.h"
23#include "clang/Frontend/TextDiagnosticPrinter.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000024#include "llvm/ADT/STLExtras.h"
NAKAMURA Takumif0c87792012-04-04 13:59:36 +000025#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000026#include "llvm/Support/Host.h"
27#include "llvm/Support/raw_ostream.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000028
Manuel Klimek74cec542012-05-07 09:45:46 +000029// For chdir, see the comment in ClangTool::run for more information.
Manuel Klimekf33dcb02012-05-07 10:02:55 +000030#ifdef _WIN32
Manuel Klimek74cec542012-05-07 09:45:46 +000031# include <direct.h>
Manuel Klimekf33dcb02012-05-07 10:02:55 +000032#else
33# include <unistd.h>
Manuel Klimek74cec542012-05-07 09:45:46 +000034#endif
35
Manuel Klimek47c245a2012-04-04 12:07:46 +000036namespace clang {
37namespace tooling {
38
Manuel Klimek3778a432012-04-25 09:25:41 +000039// Exists solely for the purpose of lookup of the resource path.
40static int StaticSymbol;
41
Manuel Klimek47c245a2012-04-04 12:07:46 +000042FrontendActionFactory::~FrontendActionFactory() {}
43
44// FIXME: This file contains structural duplication with other parts of the
45// code that sets up a compiler to run tools on it, and we should refactor
46// it to be based on the same framework.
47
48/// \brief Builds a clang driver initialized for running clang tools.
49static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
50 const char *BinaryName) {
51 const std::string DefaultOutputName = "a.out";
Manuel Klimek3778a432012-04-25 09:25:41 +000052 // This just needs to be some symbol in the binary.
53 void *const SymbolAddr = &StaticSymbol;
54 // The driver detects the builtin header path based on the path of
55 // the executable.
56 // FIXME: On linux, GetMainExecutable is independent of the content
57 // of BinaryName, thus allowing ClangTool and runToolOnCode to just
58 // pass in made-up names here (in the case of ClangTool this being
59 // the original compiler invocation). Make sure this works on other
60 // platforms.
61 llvm::sys::Path MainExecutable =
62 llvm::sys::Path::GetMainExecutable(BinaryName, SymbolAddr);
Manuel Klimek47c245a2012-04-04 12:07:46 +000063 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Manuel Klimek3778a432012-04-25 09:25:41 +000064 MainExecutable.str(), llvm::sys::getDefaultTargetTriple(),
65 DefaultOutputName, false, *Diagnostics);
Manuel Klimek47c245a2012-04-04 12:07:46 +000066 CompilerDriver->setTitle("clang_based_tool");
67 return CompilerDriver;
68}
69
70/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
71///
72/// Returns NULL on error.
73static const clang::driver::ArgStringList *getCC1Arguments(
74 clang::DiagnosticsEngine *Diagnostics,
75 clang::driver::Compilation *Compilation) {
76 // We expect to get back exactly one Command job, if we didn't something
77 // failed. Extract that job from the Compilation.
78 const clang::driver::JobList &Jobs = Compilation->getJobs();
79 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
80 llvm::SmallString<256> error_msg;
81 llvm::raw_svector_ostream error_stream(error_msg);
82 Compilation->PrintJob(error_stream, Compilation->getJobs(), "; ", true);
83 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
84 << error_stream.str();
85 return NULL;
86 }
87
88 // The one job we find should be to invoke clang again.
89 const clang::driver::Command *Cmd =
90 cast<clang::driver::Command>(*Jobs.begin());
91 if (StringRef(Cmd->getCreator().getName()) != "clang") {
92 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
93 return NULL;
94 }
95
96 return &Cmd->getArguments();
97}
98
99/// \brief Returns a clang build invocation initialized from the CC1 flags.
100static clang::CompilerInvocation *newInvocation(
101 clang::DiagnosticsEngine *Diagnostics,
102 const clang::driver::ArgStringList &CC1Args) {
103 assert(!CC1Args.empty() && "Must at least contain the program name!");
104 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
105 clang::CompilerInvocation::CreateFromArgs(
106 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
107 *Diagnostics);
108 Invocation->getFrontendOpts().DisableFree = false;
109 return Invocation;
110}
111
112bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
113 const Twine &FileName) {
114 SmallString<16> FileNameStorage;
115 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
116 const char *const CommandLine[] = {
117 "clang-tool", "-fsyntax-only", FileNameRef.data()
118 };
119 FileManager Files((FileSystemOptions()));
120 ToolInvocation Invocation(
121 std::vector<std::string>(
122 CommandLine,
123 CommandLine + llvm::array_lengthof(CommandLine)),
124 ToolAction, &Files);
125
126 SmallString<1024> CodeStorage;
127 Invocation.mapVirtualFile(FileNameRef,
128 Code.toNullTerminatedStringRef(CodeStorage));
129 return Invocation.run();
130}
131
132/// \brief Returns the absolute path of 'File', by prepending it with
133/// 'BaseDirectory' if 'File' is not absolute.
134///
135/// Otherwise returns 'File'.
136/// If 'File' starts with "./", the returned path will not contain the "./".
137/// Otherwise, the returned path will contain the literal path-concatenation of
138/// 'BaseDirectory' and 'File'.
139///
140/// \param File Either an absolute or relative path.
141/// \param BaseDirectory An absolute path.
142static std::string getAbsolutePath(
143 StringRef File, StringRef BaseDirectory) {
144 assert(llvm::sys::path::is_absolute(BaseDirectory));
145 if (llvm::sys::path::is_absolute(File)) {
146 return File;
147 }
148 StringRef RelativePath(File);
149 if (RelativePath.startswith("./")) {
150 RelativePath = RelativePath.substr(strlen("./"));
151 }
152 llvm::SmallString<1024> AbsolutePath(BaseDirectory);
153 llvm::sys::path::append(AbsolutePath, RelativePath);
154 return AbsolutePath.str();
155}
156
157ToolInvocation::ToolInvocation(
158 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
159 FileManager *Files)
160 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) {
161}
162
163void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
164 MappedFileContents[FilePath] = Content;
165}
166
167bool ToolInvocation::run() {
168 std::vector<const char*> Argv;
169 for (int I = 0, E = CommandLine.size(); I != E; ++I)
170 Argv.push_back(CommandLine[I].c_str());
171 const char *const BinaryName = Argv[0];
172 DiagnosticOptions DefaultDiagnosticOptions;
173 TextDiagnosticPrinter DiagnosticPrinter(
174 llvm::errs(), DefaultDiagnosticOptions);
175 DiagnosticsEngine Diagnostics(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(
176 new DiagnosticIDs()), &DiagnosticPrinter, false);
177
178 const llvm::OwningPtr<clang::driver::Driver> Driver(
179 newDriver(&Diagnostics, BinaryName));
180 // Since the input might only be virtual, don't check whether it exists.
181 Driver->setCheckInputsExist(false);
182 const llvm::OwningPtr<clang::driver::Compilation> Compilation(
183 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
184 const clang::driver::ArgStringList *const CC1Args = getCC1Arguments(
185 &Diagnostics, Compilation.get());
186 if (CC1Args == NULL) {
187 return false;
188 }
189 llvm::OwningPtr<clang::CompilerInvocation> Invocation(
190 newInvocation(&Diagnostics, *CC1Args));
191 return runInvocation(BinaryName, Compilation.get(),
192 Invocation.take(), *CC1Args, ToolAction.take());
193}
194
Manuel Klimek47c245a2012-04-04 12:07:46 +0000195bool ToolInvocation::runInvocation(
196 const char *BinaryName,
197 clang::driver::Compilation *Compilation,
198 clang::CompilerInvocation *Invocation,
199 const clang::driver::ArgStringList &CC1Args,
200 clang::FrontendAction *ToolAction) {
201 llvm::OwningPtr<clang::FrontendAction> ScopedToolAction(ToolAction);
202 // Show the invocation, with -v.
203 if (Invocation->getHeaderSearchOpts().Verbose) {
204 llvm::errs() << "clang Invocation:\n";
205 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true);
206 llvm::errs() << "\n";
207 }
208
209 // Create a compiler instance to handle the actual work.
210 clang::CompilerInstance Compiler;
211 Compiler.setInvocation(Invocation);
212 Compiler.setFileManager(Files);
213 // FIXME: What about LangOpts?
214
215 // Create the compilers actual diagnostics engine.
216 Compiler.createDiagnostics(CC1Args.size(),
217 const_cast<char**>(CC1Args.data()));
218 if (!Compiler.hasDiagnostics())
219 return false;
220
221 Compiler.createSourceManager(*Files);
222 addFileMappingsTo(Compiler.getSourceManager());
223
224 // Infer the builtin include path if unspecified.
225 if (Compiler.getHeaderSearchOpts().UseBuiltinIncludes &&
226 Compiler.getHeaderSearchOpts().ResourceDir.empty()) {
227 // This just needs to be some symbol in the binary.
228 void *const SymbolAddr = &StaticSymbol;
229 Compiler.getHeaderSearchOpts().ResourceDir =
230 clang::CompilerInvocation::GetResourcesPath(BinaryName, SymbolAddr);
231 }
232
233 const bool Success = Compiler.ExecuteAction(*ToolAction);
234
235 Compiler.resetAndLeakFileManager();
236 return Success;
237}
238
239void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
240 for (llvm::StringMap<StringRef>::const_iterator
241 It = MappedFileContents.begin(), End = MappedFileContents.end();
242 It != End; ++It) {
243 // Inject the code as the given file name into the preprocessor options.
244 const llvm::MemoryBuffer *Input =
245 llvm::MemoryBuffer::getMemBuffer(It->getValue());
246 // FIXME: figure out what '0' stands for.
247 const FileEntry *FromFile = Files->getVirtualFile(
248 It->getKey(), Input->getBufferSize(), 0);
249 // FIXME: figure out memory management ('true').
250 Sources.overrideFileContents(FromFile, Input, true);
251 }
252}
253
254ClangTool::ClangTool(const CompilationDatabase &Compilations,
255 ArrayRef<std::string> SourcePaths)
256 : Files((FileSystemOptions())) {
NAKAMURA Takumif0c87792012-04-04 13:59:36 +0000257 llvm::SmallString<1024> BaseDirectory;
Manuel Klimek3521ae92012-04-09 18:08:23 +0000258 if (const char *PWD = ::getenv("PWD"))
259 BaseDirectory = PWD;
260 else
261 llvm::sys::fs::current_path(BaseDirectory);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000262 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
263 llvm::SmallString<1024> File(getAbsolutePath(
264 SourcePaths[I], BaseDirectory));
265
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000266 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimek47c245a2012-04-04 12:07:46 +0000267 Compilations.getCompileCommands(File.str());
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000268 if (!CompileCommandsForFile.empty()) {
269 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
270 CompileCommands.push_back(std::make_pair(File.str(),
271 CompileCommandsForFile[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000272 }
273 } else {
274 // FIXME: There are two use cases here: doing a fuzzy
275 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
276 // about the .cc files that were not found, and the use case where I
277 // specify all files I want to run over explicitly, where this should
278 // be an error. We'll want to add an option for this.
279 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
280 }
281 }
282}
283
284void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
285 MappedFileContents.push_back(std::make_pair(FilePath, Content));
286}
287
288int ClangTool::run(FrontendActionFactory *ActionFactory) {
289 bool ProcessingFailed = false;
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000290 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
291 std::string File = CompileCommands[I].first;
292 // FIXME: chdir is thread hostile; on the other hand, creating the same
293 // behavior as chdir is complex: chdir resolves the path once, thus
294 // guaranteeing that all subsequent relative path operations work
295 // on the same path the original chdir resulted in. This makes a difference
296 // for example on network filesystems, where symlinks might be switched
297 // during runtime of the tool. Fixing this depends on having a file system
298 // abstraction that allows openat() style interactions.
299 if (chdir(CompileCommands[I].second.Directory.c_str()))
300 llvm::report_fatal_error("Cannot chdir into \"" +
301 CompileCommands[I].second.Directory + "\n!");
302 std::vector<std::string> &CommandLine =
303 CompileCommands[I].second.CommandLine;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000304 llvm::outs() << "Processing: " << File << ".\n";
305 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
306 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
307 Invocation.mapVirtualFile(MappedFileContents[I].first,
308 MappedFileContents[I].second);
309 }
310 if (!Invocation.run()) {
311 llvm::outs() << "Error while processing " << File << ".\n";
312 ProcessingFailed = true;
313 }
314 }
315 return ProcessingFailed ? 1 : 0;
316}
317
318} // end namespace tooling
319} // end namespace clang