1 //===--- Tooling.cpp - Running clang standalone tools ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements functions to run clang tools standalone instead
11 // of running them as a plugin.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Tooling/Tooling.h"
16 #include "clang/Driver/Compilation.h"
17 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/Tool.h"
20 #include "clang/Driver/ToolChain.h"
21 #include "clang/Frontend/ASTUnit.h"
22 #include "clang/Frontend/CompilerInstance.h"
23 #include "clang/Frontend/FrontendDiagnostic.h"
24 #include "clang/Frontend/TextDiagnosticPrinter.h"
25 #include "clang/Lex/PreprocessorOptions.h"
26 #include "clang/Tooling/ArgumentsAdjusters.h"
27 #include "clang/Tooling/CompilationDatabase.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/Config/llvm-config.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/Option.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/raw_ostream.h"
39 #define DEBUG_TYPE "clang-tooling"
44 ToolAction::~ToolAction() {}
46 FrontendActionFactory::~FrontendActionFactory() {}
48 // FIXME: This file contains structural duplication with other parts of the
49 // code that sets up a compiler to run tools on it, and we should refactor
50 // it to be based on the same framework.
52 /// \brief Builds a clang driver initialized for running clang tools.
53 static clang::driver::Driver *newDriver(
54 clang::DiagnosticsEngine *Diagnostics, const char *BinaryName,
55 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
56 clang::driver::Driver *CompilerDriver =
57 new clang::driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
58 *Diagnostics, std::move(VFS));
59 CompilerDriver->setTitle("clang_based_tool");
60 return CompilerDriver;
63 /// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
65 /// Returns NULL on error.
66 static const llvm::opt::ArgStringList *getCC1Arguments(
67 clang::DiagnosticsEngine *Diagnostics,
68 clang::driver::Compilation *Compilation) {
69 // We expect to get back exactly one Command job, if we didn't something
70 // failed. Extract that job from the Compilation.
71 const clang::driver::JobList &Jobs = Compilation->getJobs();
72 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
73 SmallString<256> error_msg;
74 llvm::raw_svector_ostream error_stream(error_msg);
75 Jobs.Print(error_stream, "; ", true);
76 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
77 << error_stream.str();
81 // The one job we find should be to invoke clang again.
82 const clang::driver::Command &Cmd =
83 cast<clang::driver::Command>(*Jobs.begin());
84 if (StringRef(Cmd.getCreator().getName()) != "clang") {
85 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
89 return &Cmd.getArguments();
92 /// \brief Returns a clang build invocation initialized from the CC1 flags.
93 clang::CompilerInvocation *newInvocation(
94 clang::DiagnosticsEngine *Diagnostics,
95 const llvm::opt::ArgStringList &CC1Args) {
96 assert(!CC1Args.empty() && "Must at least contain the program name!");
97 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
98 clang::CompilerInvocation::CreateFromArgs(
99 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
101 Invocation->getFrontendOpts().DisableFree = false;
102 Invocation->getCodeGenOpts().DisableFree = false;
103 Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
107 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
108 const Twine &FileName,
109 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
110 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
111 FileName, "clang-tool",
112 std::move(PCHContainerOps));
115 static std::vector<std::string>
116 getSyntaxOnlyToolArgs(const Twine &ToolName,
117 const std::vector<std::string> &ExtraArgs,
118 StringRef FileName) {
119 std::vector<std::string> Args;
120 Args.push_back(ToolName.str());
121 Args.push_back("-fsyntax-only");
122 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
123 Args.push_back(FileName.str());
127 bool runToolOnCodeWithArgs(
128 clang::FrontendAction *ToolAction, const Twine &Code,
129 const std::vector<std::string> &Args, const Twine &FileName,
130 const Twine &ToolName,
131 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
132 const FileContentMappings &VirtualMappedFiles) {
134 SmallString<16> FileNameStorage;
135 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
136 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
137 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
138 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
139 new vfs::InMemoryFileSystem);
140 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
141 llvm::IntrusiveRefCntPtr<FileManager> Files(
142 new FileManager(FileSystemOptions(), OverlayFileSystem));
143 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
144 ToolAction, Files.get(),
145 std::move(PCHContainerOps));
147 SmallString<1024> CodeStorage;
148 InMemoryFileSystem->addFile(FileNameRef, 0,
149 llvm::MemoryBuffer::getMemBuffer(
150 Code.toNullTerminatedStringRef(CodeStorage)));
152 for (auto &FilenameWithContent : VirtualMappedFiles) {
153 InMemoryFileSystem->addFile(
154 FilenameWithContent.first, 0,
155 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
158 return Invocation.run();
161 std::string getAbsolutePath(StringRef File) {
162 StringRef RelativePath(File);
163 // FIXME: Should '.\\' be accepted on Win32?
164 if (RelativePath.startswith("./")) {
165 RelativePath = RelativePath.substr(strlen("./"));
168 SmallString<1024> AbsolutePath = RelativePath;
169 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
172 llvm::sys::path::native(AbsolutePath);
173 return AbsolutePath.str();
176 void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
177 StringRef InvokedAs) {
178 if (!CommandLine.empty() && !InvokedAs.empty()) {
179 bool AlreadyHasTarget = false;
180 bool AlreadyHasMode = false;
181 // Skip CommandLine[0].
182 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
184 StringRef TokenRef(*Token);
186 (TokenRef == "-target" || TokenRef.startswith("-target="));
187 AlreadyHasMode |= (TokenRef == "--driver-mode" ||
188 TokenRef.startswith("--driver-mode="));
191 clang::driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
192 if (!AlreadyHasMode && !TargetMode.second.empty()) {
193 CommandLine.insert(++CommandLine.begin(), TargetMode.second);
195 if (!AlreadyHasTarget && !TargetMode.first.empty()) {
196 CommandLine.insert(++CommandLine.begin(), {"-target", TargetMode.first});
203 class SingleFrontendActionFactory : public FrontendActionFactory {
204 FrontendAction *Action;
207 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
209 FrontendAction *create() override { return Action; }
214 ToolInvocation::ToolInvocation(
215 std::vector<std::string> CommandLine, ToolAction *Action,
216 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
217 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
218 Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
219 DiagConsumer(nullptr) {}
221 ToolInvocation::ToolInvocation(
222 std::vector<std::string> CommandLine, FrontendAction *FAction,
223 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
224 : CommandLine(std::move(CommandLine)),
225 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
226 Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
227 DiagConsumer(nullptr) {}
229 ToolInvocation::~ToolInvocation() {
234 void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
235 SmallString<1024> PathStorage;
236 llvm::sys::path::native(FilePath, PathStorage);
237 MappedFileContents[PathStorage] = Content;
240 bool ToolInvocation::run() {
241 std::vector<const char*> Argv;
242 for (const std::string &Str : CommandLine)
243 Argv.push_back(Str.c_str());
244 const char *const BinaryName = Argv[0];
245 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
246 unsigned MissingArgIndex, MissingArgCount;
247 std::unique_ptr<llvm::opt::OptTable> Opts(driver::createDriverOptTable());
248 llvm::opt::InputArgList ParsedArgs = Opts->ParseArgs(
249 ArrayRef<const char *>(Argv).slice(1), MissingArgIndex, MissingArgCount);
250 ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
251 TextDiagnosticPrinter DiagnosticPrinter(
252 llvm::errs(), &*DiagOpts);
253 DiagnosticsEngine Diagnostics(
254 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
255 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
257 const std::unique_ptr<clang::driver::Driver> Driver(
258 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
259 // Since the input might only be virtual, don't check whether it exists.
260 Driver->setCheckInputsExist(false);
261 const std::unique_ptr<clang::driver::Compilation> Compilation(
262 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
263 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
264 &Diagnostics, Compilation.get());
268 std::unique_ptr<clang::CompilerInvocation> Invocation(
269 newInvocation(&Diagnostics, *CC1Args));
270 // FIXME: remove this when all users have migrated!
271 for (const auto &It : MappedFileContents) {
272 // Inject the code as the given file name into the preprocessor options.
273 std::unique_ptr<llvm::MemoryBuffer> Input =
274 llvm::MemoryBuffer::getMemBuffer(It.getValue());
275 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
278 return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
279 std::move(PCHContainerOps));
282 bool ToolInvocation::runInvocation(
283 const char *BinaryName, clang::driver::Compilation *Compilation,
284 std::shared_ptr<clang::CompilerInvocation> Invocation,
285 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
286 // Show the invocation, with -v.
287 if (Invocation->getHeaderSearchOpts().Verbose) {
288 llvm::errs() << "clang Invocation:\n";
289 Compilation->getJobs().Print(llvm::errs(), "\n", true);
290 llvm::errs() << "\n";
293 return Action->runInvocation(std::move(Invocation), Files,
294 std::move(PCHContainerOps), DiagConsumer);
297 bool FrontendActionFactory::runInvocation(
298 std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
299 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
300 DiagnosticConsumer *DiagConsumer) {
301 // Create a compiler instance to handle the actual work.
302 clang::CompilerInstance Compiler(std::move(PCHContainerOps));
303 Compiler.setInvocation(std::move(Invocation));
304 Compiler.setFileManager(Files);
306 // The FrontendAction can have lifetime requirements for Compiler or its
307 // members, and we need to ensure it's deleted earlier than Compiler. So we
308 // pass it to an std::unique_ptr declared after the Compiler variable.
309 std::unique_ptr<FrontendAction> ScopedToolAction(create());
311 // Create the compiler's actual diagnostics engine.
312 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
313 if (!Compiler.hasDiagnostics())
316 Compiler.createSourceManager(*Files);
318 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
320 Files->clearStatCaches();
324 ClangTool::ClangTool(const CompilationDatabase &Compilations,
325 ArrayRef<std::string> SourcePaths,
326 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
327 : Compilations(Compilations), SourcePaths(SourcePaths),
328 PCHContainerOps(std::move(PCHContainerOps)),
329 OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
330 InMemoryFileSystem(new vfs::InMemoryFileSystem),
331 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
332 DiagConsumer(nullptr) {
333 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
334 appendArgumentsAdjuster(getClangStripOutputAdjuster());
335 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
338 ClangTool::~ClangTool() {}
340 void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
341 MappedFileContents.push_back(std::make_pair(FilePath, Content));
344 void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
347 combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
349 ArgsAdjuster = std::move(Adjuster);
352 void ClangTool::clearArgumentsAdjusters() {
353 ArgsAdjuster = nullptr;
356 static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
358 // Allow users to override the resource dir.
359 for (StringRef Arg : Args)
360 if (Arg.startswith("-resource-dir"))
363 // If there's no override in place add our resource dir.
364 Args.push_back("-resource-dir=" +
365 CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
368 int ClangTool::run(ToolAction *Action) {
369 // Exists solely for the purpose of lookup of the resource path.
370 // This just needs to be some symbol in the binary.
371 static int StaticSymbol;
373 llvm::SmallString<128> InitialDirectory;
374 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
375 llvm::report_fatal_error("Cannot detect current path: " +
376 Twine(EC.message()));
378 // First insert all absolute paths into the in-memory VFS. These are global
379 // for all compile commands.
380 if (SeenWorkingDirectories.insert("/").second)
381 for (const auto &MappedFile : MappedFileContents)
382 if (llvm::sys::path::is_absolute(MappedFile.first))
383 InMemoryFileSystem->addFile(
385 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
387 bool ProcessingFailed = false;
388 for (const auto &SourcePath : SourcePaths) {
389 std::string File(getAbsolutePath(SourcePath));
391 // Currently implementations of CompilationDatabase::getCompileCommands can
392 // change the state of the file system (e.g. prepare generated headers), so
393 // this method needs to run right before we invoke the tool, as the next
394 // file may require a different (incompatible) state of the file system.
396 // FIXME: Make the compilation database interface more explicit about the
397 // requirements to the order of invocation of its members.
398 std::vector<CompileCommand> CompileCommandsForFile =
399 Compilations.getCompileCommands(File);
400 if (CompileCommandsForFile.empty()) {
401 // FIXME: There are two use cases here: doing a fuzzy
402 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
403 // about the .cc files that were not found, and the use case where I
404 // specify all files I want to run over explicitly, where this should
405 // be an error. We'll want to add an option for this.
406 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
409 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
410 // FIXME: chdir is thread hostile; on the other hand, creating the same
411 // behavior as chdir is complex: chdir resolves the path once, thus
412 // guaranteeing that all subsequent relative path operations work
413 // on the same path the original chdir resulted in. This makes a
414 // difference for example on network filesystems, where symlinks might be
415 // switched during runtime of the tool. Fixing this depends on having a
416 // file system abstraction that allows openat() style interactions.
417 if (OverlayFileSystem->setCurrentWorkingDirectory(
418 CompileCommand.Directory))
419 llvm::report_fatal_error("Cannot chdir into \"" +
420 Twine(CompileCommand.Directory) + "\n!");
422 // Now fill the in-memory VFS with the relative file mappings so it will
423 // have the correct relative paths. We never remove mappings but that
425 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
426 for (const auto &MappedFile : MappedFileContents)
427 if (!llvm::sys::path::is_absolute(MappedFile.first))
428 InMemoryFileSystem->addFile(
430 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
432 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
434 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
435 assert(!CommandLine.empty());
437 // Add the resource dir based on the binary of this tool. argv[0] in the
438 // compilation database may refer to a different compiler and we want to
439 // pick up the very same standard library that compiler is using. The
440 // builtin headers in the resource dir need to match the exact clang
441 // version the tool is using.
442 // FIXME: On linux, GetMainExecutable is independent of the value of the
443 // first argument, thus allowing ClangTool and runToolOnCode to just
444 // pass in made-up names here. Make sure this works on other platforms.
445 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
447 // FIXME: We need a callback mechanism for the tool writer to output a
448 // customized message for each file.
449 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
450 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
452 Invocation.setDiagnosticConsumer(DiagConsumer);
454 if (!Invocation.run()) {
455 // FIXME: Diagnostics should be used instead.
456 llvm::errs() << "Error while processing " << File << ".\n";
457 ProcessingFailed = true;
459 // Return to the initial directory to correctly resolve next file by
461 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
462 llvm::report_fatal_error("Cannot chdir into \"" +
463 Twine(InitialDirectory) + "\n!");
466 return ProcessingFailed ? 1 : 0;
471 class ASTBuilderAction : public ToolAction {
472 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
475 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
477 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
479 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
480 DiagnosticConsumer *DiagConsumer) override {
481 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
482 Invocation, std::move(PCHContainerOps),
483 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
485 /*ShouldOwnClient=*/false),
490 ASTs.push_back(std::move(AST));
496 int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
497 ASTBuilderAction Action(ASTs);
501 std::unique_ptr<ASTUnit>
502 buildASTFromCode(const Twine &Code, const Twine &FileName,
503 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
504 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
505 "clang-tool", std::move(PCHContainerOps));
508 std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
509 const Twine &Code, const std::vector<std::string> &Args,
510 const Twine &FileName, const Twine &ToolName,
511 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
512 SmallString<16> FileNameStorage;
513 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
515 std::vector<std::unique_ptr<ASTUnit>> ASTs;
516 ASTBuilderAction Action(ASTs);
517 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
518 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
519 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
520 new vfs::InMemoryFileSystem);
521 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
522 llvm::IntrusiveRefCntPtr<FileManager> Files(
523 new FileManager(FileSystemOptions(), OverlayFileSystem));
524 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
525 &Action, Files.get(), std::move(PCHContainerOps));
527 SmallString<1024> CodeStorage;
528 InMemoryFileSystem->addFile(FileNameRef, 0,
529 llvm::MemoryBuffer::getMemBuffer(
530 Code.toNullTerminatedStringRef(CodeStorage)));
531 if (!Invocation.run())
534 assert(ASTs.size() == 1);
535 return std::move(ASTs[0]);
538 } // end namespace tooling
539 } // end namespace clang