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