blob: 5d41172a919275a6731f40ef86c8ab8adff9c76c [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"
Manuel Klimek47c245a2012-04-04 12:07:46 +000022#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
39FrontendActionFactory::~FrontendActionFactory() {}
40
41// FIXME: This file contains structural duplication with other parts of the
42// code that sets up a compiler to run tools on it, and we should refactor
43// it to be based on the same framework.
44
45/// \brief Builds a clang driver initialized for running clang tools.
46static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
47 const char *BinaryName) {
48 const std::string DefaultOutputName = "a.out";
49 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Alexander Kornienko8388d242012-06-04 19:02:59 +000050 BinaryName, llvm::sys::getDefaultTargetTriple(),
Manuel Klimek3778a432012-04-25 09:25:41 +000051 DefaultOutputName, false, *Diagnostics);
Manuel Klimek47c245a2012-04-04 12:07:46 +000052 CompilerDriver->setTitle("clang_based_tool");
53 return CompilerDriver;
54}
55
56/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
57///
58/// Returns NULL on error.
59static const clang::driver::ArgStringList *getCC1Arguments(
60 clang::DiagnosticsEngine *Diagnostics,
61 clang::driver::Compilation *Compilation) {
62 // We expect to get back exactly one Command job, if we didn't something
63 // failed. Extract that job from the Compilation.
64 const clang::driver::JobList &Jobs = Compilation->getJobs();
65 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
66 llvm::SmallString<256> error_msg;
67 llvm::raw_svector_ostream error_stream(error_msg);
68 Compilation->PrintJob(error_stream, Compilation->getJobs(), "; ", true);
69 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
70 << error_stream.str();
71 return NULL;
72 }
73
74 // The one job we find should be to invoke clang again.
75 const clang::driver::Command *Cmd =
76 cast<clang::driver::Command>(*Jobs.begin());
77 if (StringRef(Cmd->getCreator().getName()) != "clang") {
78 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
79 return NULL;
80 }
81
82 return &Cmd->getArguments();
83}
84
85/// \brief Returns a clang build invocation initialized from the CC1 flags.
86static clang::CompilerInvocation *newInvocation(
87 clang::DiagnosticsEngine *Diagnostics,
88 const clang::driver::ArgStringList &CC1Args) {
89 assert(!CC1Args.empty() && "Must at least contain the program name!");
90 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
91 clang::CompilerInvocation::CreateFromArgs(
92 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
93 *Diagnostics);
94 Invocation->getFrontendOpts().DisableFree = false;
95 return Invocation;
96}
97
98bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
99 const Twine &FileName) {
100 SmallString<16> FileNameStorage;
101 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
102 const char *const CommandLine[] = {
103 "clang-tool", "-fsyntax-only", FileNameRef.data()
104 };
105 FileManager Files((FileSystemOptions()));
106 ToolInvocation Invocation(
107 std::vector<std::string>(
108 CommandLine,
109 CommandLine + llvm::array_lengthof(CommandLine)),
110 ToolAction, &Files);
111
112 SmallString<1024> CodeStorage;
113 Invocation.mapVirtualFile(FileNameRef,
114 Code.toNullTerminatedStringRef(CodeStorage));
115 return Invocation.run();
116}
117
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000118std::string getAbsolutePath(StringRef File) {
119 llvm::SmallString<1024> BaseDirectory;
120 if (const char *PWD = ::getenv("PWD"))
121 BaseDirectory = PWD;
122 else
123 llvm::sys::fs::current_path(BaseDirectory);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000124 SmallString<1024> PathStorage;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000125 if (llvm::sys::path::is_absolute(File)) {
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000126 llvm::sys::path::native(File, PathStorage);
127 return PathStorage.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000128 }
129 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000130 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000131 if (RelativePath.startswith("./")) {
132 RelativePath = RelativePath.substr(strlen("./"));
133 }
134 llvm::SmallString<1024> AbsolutePath(BaseDirectory);
135 llvm::sys::path::append(AbsolutePath, RelativePath);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000136 llvm::sys::path::native(Twine(AbsolutePath), PathStorage);
137 return PathStorage.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000138}
139
140ToolInvocation::ToolInvocation(
141 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
142 FileManager *Files)
143 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) {
144}
145
146void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000147 SmallString<1024> PathStorage;
148 llvm::sys::path::native(FilePath, PathStorage);
149 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000150}
151
152bool ToolInvocation::run() {
153 std::vector<const char*> Argv;
154 for (int I = 0, E = CommandLine.size(); I != E; ++I)
155 Argv.push_back(CommandLine[I].c_str());
156 const char *const BinaryName = Argv[0];
157 DiagnosticOptions DefaultDiagnosticOptions;
158 TextDiagnosticPrinter DiagnosticPrinter(
159 llvm::errs(), DefaultDiagnosticOptions);
160 DiagnosticsEngine Diagnostics(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(
161 new DiagnosticIDs()), &DiagnosticPrinter, false);
162
163 const llvm::OwningPtr<clang::driver::Driver> Driver(
164 newDriver(&Diagnostics, BinaryName));
165 // Since the input might only be virtual, don't check whether it exists.
166 Driver->setCheckInputsExist(false);
167 const llvm::OwningPtr<clang::driver::Compilation> Compilation(
168 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
169 const clang::driver::ArgStringList *const CC1Args = getCC1Arguments(
170 &Diagnostics, Compilation.get());
171 if (CC1Args == NULL) {
172 return false;
173 }
174 llvm::OwningPtr<clang::CompilerInvocation> Invocation(
175 newInvocation(&Diagnostics, *CC1Args));
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000176 return runInvocation(BinaryName, Compilation.get(), Invocation.take(),
177 *CC1Args);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000178}
179
Manuel Klimek47c245a2012-04-04 12:07:46 +0000180bool ToolInvocation::runInvocation(
181 const char *BinaryName,
182 clang::driver::Compilation *Compilation,
183 clang::CompilerInvocation *Invocation,
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000184 const clang::driver::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000185 // Show the invocation, with -v.
186 if (Invocation->getHeaderSearchOpts().Verbose) {
187 llvm::errs() << "clang Invocation:\n";
188 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true);
189 llvm::errs() << "\n";
190 }
191
192 // Create a compiler instance to handle the actual work.
193 clang::CompilerInstance Compiler;
194 Compiler.setInvocation(Invocation);
195 Compiler.setFileManager(Files);
196 // FIXME: What about LangOpts?
197
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000198 // ToolAction can have lifetime requirements for Compiler or its members, and
199 // we need to ensure it's deleted earlier than Compiler. So we pass it to an
200 // OwningPtr declared after the Compiler variable.
201 llvm::OwningPtr<FrontendAction> ScopedToolAction(ToolAction.take());
202
Manuel Klimek47c245a2012-04-04 12:07:46 +0000203 // Create the compilers actual diagnostics engine.
204 Compiler.createDiagnostics(CC1Args.size(),
205 const_cast<char**>(CC1Args.data()));
206 if (!Compiler.hasDiagnostics())
207 return false;
208
209 Compiler.createSourceManager(*Files);
210 addFileMappingsTo(Compiler.getSourceManager());
211
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000212 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000213
214 Compiler.resetAndLeakFileManager();
215 return Success;
216}
217
218void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
219 for (llvm::StringMap<StringRef>::const_iterator
220 It = MappedFileContents.begin(), End = MappedFileContents.end();
221 It != End; ++It) {
222 // Inject the code as the given file name into the preprocessor options.
223 const llvm::MemoryBuffer *Input =
224 llvm::MemoryBuffer::getMemBuffer(It->getValue());
225 // FIXME: figure out what '0' stands for.
226 const FileEntry *FromFile = Files->getVirtualFile(
227 It->getKey(), Input->getBufferSize(), 0);
Alexander Kornienko9e8d2282012-05-30 12:10:28 +0000228 Sources.overrideFileContents(FromFile, Input);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000229 }
230}
231
232ClangTool::ClangTool(const CompilationDatabase &Compilations,
233 ArrayRef<std::string> SourcePaths)
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000234 : Files((FileSystemOptions())),
235 ArgsAdjuster(new ClangSyntaxOnlyAdjuster()) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000236 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000237 llvm::SmallString<1024> File(getAbsolutePath(SourcePaths[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000238
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000239 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimek47c245a2012-04-04 12:07:46 +0000240 Compilations.getCompileCommands(File.str());
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000241 if (!CompileCommandsForFile.empty()) {
242 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
243 CompileCommands.push_back(std::make_pair(File.str(),
244 CompileCommandsForFile[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000245 }
246 } else {
247 // FIXME: There are two use cases here: doing a fuzzy
248 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
249 // about the .cc files that were not found, and the use case where I
250 // specify all files I want to run over explicitly, where this should
251 // be an error. We'll want to add an option for this.
252 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
253 }
254 }
255}
256
257void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
258 MappedFileContents.push_back(std::make_pair(FilePath, Content));
259}
260
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000261void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
262 ArgsAdjuster.reset(Adjuster);
263}
264
Manuel Klimek47c245a2012-04-04 12:07:46 +0000265int ClangTool::run(FrontendActionFactory *ActionFactory) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000266 // Exists solely for the purpose of lookup of the resource path.
267 // This just needs to be some symbol in the binary.
268 static int StaticSymbol;
269 // The driver detects the builtin header path based on the path of the
270 // executable.
271 // FIXME: On linux, GetMainExecutable is independent of the value of the
272 // first argument, thus allowing ClangTool and runToolOnCode to just
273 // pass in made-up names here. Make sure this works on other platforms.
274 std::string MainExecutable =
275 llvm::sys::Path::GetMainExecutable("clang_tool", &StaticSymbol).str();
276
Manuel Klimek47c245a2012-04-04 12:07:46 +0000277 bool ProcessingFailed = false;
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000278 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
279 std::string File = CompileCommands[I].first;
280 // FIXME: chdir is thread hostile; on the other hand, creating the same
281 // behavior as chdir is complex: chdir resolves the path once, thus
282 // guaranteeing that all subsequent relative path operations work
283 // on the same path the original chdir resulted in. This makes a difference
Alexander Kornienko8388d242012-06-04 19:02:59 +0000284 // for example on network filesystems, where symlinks might be switched
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000285 // during runtime of the tool. Fixing this depends on having a file system
286 // abstraction that allows openat() style interactions.
287 if (chdir(CompileCommands[I].second.Directory.c_str()))
288 llvm::report_fatal_error("Cannot chdir into \"" +
289 CompileCommands[I].second.Directory + "\n!");
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000290 std::vector<std::string> CommandLine =
291 ArgsAdjuster->Adjust(CompileCommands[I].second.CommandLine);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000292 assert(!CommandLine.empty());
293 CommandLine[0] = MainExecutable;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000294 llvm::outs() << "Processing: " << File << ".\n";
295 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
296 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
297 Invocation.mapVirtualFile(MappedFileContents[I].first,
298 MappedFileContents[I].second);
299 }
300 if (!Invocation.run()) {
301 llvm::outs() << "Error while processing " << File << ".\n";
302 ProcessingFailed = true;
303 }
304 }
305 return ProcessingFailed ? 1 : 0;
306}
307
308} // end namespace tooling
309} // end namespace clang