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;
106 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
107 const Twine &FileName,
108 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
109 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
110 FileName, "clang-tool",
111 std::move(PCHContainerOps));
114 static std::vector<std::string>
115 getSyntaxOnlyToolArgs(const Twine &ToolName,
116 const std::vector<std::string> &ExtraArgs,
117 StringRef FileName) {
118 std::vector<std::string> Args;
119 Args.push_back(ToolName.str());
120 Args.push_back("-fsyntax-only");
121 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
122 Args.push_back(FileName.str());
126 bool runToolOnCodeWithArgs(
127 clang::FrontendAction *ToolAction, const Twine &Code,
128 const std::vector<std::string> &Args, const Twine &FileName,
129 const Twine &ToolName,
130 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
131 const FileContentMappings &VirtualMappedFiles) {
133 SmallString<16> FileNameStorage;
134 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
135 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
136 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
137 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
138 new vfs::InMemoryFileSystem);
139 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
140 llvm::IntrusiveRefCntPtr<FileManager> Files(
141 new FileManager(FileSystemOptions(), OverlayFileSystem));
142 ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();
143 ToolInvocation Invocation(
144 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
145 ToolAction, Files.get(),
146 std::move(PCHContainerOps));
148 SmallString<1024> CodeStorage;
149 InMemoryFileSystem->addFile(FileNameRef, 0,
150 llvm::MemoryBuffer::getMemBuffer(
151 Code.toNullTerminatedStringRef(CodeStorage)));
153 for (auto &FilenameWithContent : VirtualMappedFiles) {
154 InMemoryFileSystem->addFile(
155 FilenameWithContent.first, 0,
156 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
159 return Invocation.run();
162 std::string getAbsolutePath(StringRef File) {
163 StringRef RelativePath(File);
164 // FIXME: Should '.\\' be accepted on Win32?
165 if (RelativePath.startswith("./")) {
166 RelativePath = RelativePath.substr(strlen("./"));
169 SmallString<1024> AbsolutePath = RelativePath;
170 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
173 llvm::sys::path::native(AbsolutePath);
174 return AbsolutePath.str();
177 void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
178 StringRef InvokedAs) {
179 if (!CommandLine.empty() && !InvokedAs.empty()) {
180 bool AlreadyHasTarget = false;
181 bool AlreadyHasMode = false;
182 // Skip CommandLine[0].
183 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
185 StringRef TokenRef(*Token);
187 (TokenRef == "-target" || TokenRef.startswith("-target="));
188 AlreadyHasMode |= (TokenRef == "--driver-mode" ||
189 TokenRef.startswith("--driver-mode="));
192 clang::driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
193 if (!AlreadyHasMode && !TargetMode.second.empty()) {
194 CommandLine.insert(++CommandLine.begin(), TargetMode.second);
196 if (!AlreadyHasTarget && !TargetMode.first.empty()) {
197 CommandLine.insert(++CommandLine.begin(), {"-target", TargetMode.first});
204 class SingleFrontendActionFactory : public FrontendActionFactory {
205 FrontendAction *Action;
208 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
210 FrontendAction *create() override { return Action; }
215 ToolInvocation::ToolInvocation(
216 std::vector<std::string> CommandLine, ToolAction *Action,
217 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
218 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
219 Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
220 DiagConsumer(nullptr) {}
222 ToolInvocation::ToolInvocation(
223 std::vector<std::string> CommandLine, FrontendAction *FAction,
224 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
225 : CommandLine(std::move(CommandLine)),
226 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
227 Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
228 DiagConsumer(nullptr) {}
230 ToolInvocation::~ToolInvocation() {
235 void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
236 SmallString<1024> PathStorage;
237 llvm::sys::path::native(FilePath, PathStorage);
238 MappedFileContents[PathStorage] = Content;
241 bool ToolInvocation::run() {
242 std::vector<const char*> Argv;
243 for (const std::string &Str : CommandLine)
244 Argv.push_back(Str.c_str());
245 const char *const BinaryName = Argv[0];
246 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
247 unsigned MissingArgIndex, MissingArgCount;
248 std::unique_ptr<llvm::opt::OptTable> Opts = driver::createDriverOptTable();
249 llvm::opt::InputArgList ParsedArgs = Opts->ParseArgs(
250 ArrayRef<const char *>(Argv).slice(1), MissingArgIndex, MissingArgCount);
251 ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
252 TextDiagnosticPrinter DiagnosticPrinter(
253 llvm::errs(), &*DiagOpts);
254 DiagnosticsEngine Diagnostics(
255 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
256 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
258 const std::unique_ptr<clang::driver::Driver> Driver(
259 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
260 // Since the input might only be virtual, don't check whether it exists.
261 Driver->setCheckInputsExist(false);
262 const std::unique_ptr<clang::driver::Compilation> Compilation(
263 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
266 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
267 &Diagnostics, Compilation.get());
271 std::unique_ptr<clang::CompilerInvocation> Invocation(
272 newInvocation(&Diagnostics, *CC1Args));
273 // FIXME: remove this when all users have migrated!
274 for (const auto &It : MappedFileContents) {
275 // Inject the code as the given file name into the preprocessor options.
276 std::unique_ptr<llvm::MemoryBuffer> Input =
277 llvm::MemoryBuffer::getMemBuffer(It.getValue());
278 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
281 return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
282 std::move(PCHContainerOps));
285 bool ToolInvocation::runInvocation(
286 const char *BinaryName, clang::driver::Compilation *Compilation,
287 std::shared_ptr<clang::CompilerInvocation> Invocation,
288 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
289 // Show the invocation, with -v.
290 if (Invocation->getHeaderSearchOpts().Verbose) {
291 llvm::errs() << "clang Invocation:\n";
292 Compilation->getJobs().Print(llvm::errs(), "\n", true);
293 llvm::errs() << "\n";
296 return Action->runInvocation(std::move(Invocation), Files,
297 std::move(PCHContainerOps), DiagConsumer);
300 bool FrontendActionFactory::runInvocation(
301 std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
302 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
303 DiagnosticConsumer *DiagConsumer) {
304 // Create a compiler instance to handle the actual work.
305 clang::CompilerInstance Compiler(std::move(PCHContainerOps));
306 Compiler.setInvocation(std::move(Invocation));
307 Compiler.setFileManager(Files);
309 // The FrontendAction can have lifetime requirements for Compiler or its
310 // members, and we need to ensure it's deleted earlier than Compiler. So we
311 // pass it to an std::unique_ptr declared after the Compiler variable.
312 std::unique_ptr<FrontendAction> ScopedToolAction(create());
314 // Create the compiler's actual diagnostics engine.
315 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
316 if (!Compiler.hasDiagnostics())
319 Compiler.createSourceManager(*Files);
321 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
323 Files->clearStatCaches();
327 ClangTool::ClangTool(const CompilationDatabase &Compilations,
328 ArrayRef<std::string> SourcePaths,
329 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
330 : Compilations(Compilations), SourcePaths(SourcePaths),
331 PCHContainerOps(std::move(PCHContainerOps)),
332 OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
333 InMemoryFileSystem(new vfs::InMemoryFileSystem),
334 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
335 DiagConsumer(nullptr) {
336 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
337 appendArgumentsAdjuster(getClangStripOutputAdjuster());
338 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
339 appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
342 ClangTool::~ClangTool() {}
344 void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
345 MappedFileContents.push_back(std::make_pair(FilePath, Content));
348 void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
351 combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
353 ArgsAdjuster = std::move(Adjuster);
356 void ClangTool::clearArgumentsAdjusters() {
357 ArgsAdjuster = nullptr;
360 static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
362 // Allow users to override the resource dir.
363 for (StringRef Arg : Args)
364 if (Arg.startswith("-resource-dir"))
367 // If there's no override in place add our resource dir.
368 Args.push_back("-resource-dir=" +
369 CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
372 int ClangTool::run(ToolAction *Action) {
373 // Exists solely for the purpose of lookup of the resource path.
374 // This just needs to be some symbol in the binary.
375 static int StaticSymbol;
377 llvm::SmallString<128> InitialDirectory;
378 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
379 llvm::report_fatal_error("Cannot detect current path: " +
380 Twine(EC.message()));
382 // First insert all absolute paths into the in-memory VFS. These are global
383 // for all compile commands.
384 if (SeenWorkingDirectories.insert("/").second)
385 for (const auto &MappedFile : MappedFileContents)
386 if (llvm::sys::path::is_absolute(MappedFile.first))
387 InMemoryFileSystem->addFile(
389 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
391 bool ProcessingFailed = false;
392 for (const auto &SourcePath : SourcePaths) {
393 std::string File(getAbsolutePath(SourcePath));
395 // Currently implementations of CompilationDatabase::getCompileCommands can
396 // change the state of the file system (e.g. prepare generated headers), so
397 // this method needs to run right before we invoke the tool, as the next
398 // file may require a different (incompatible) state of the file system.
400 // FIXME: Make the compilation database interface more explicit about the
401 // requirements to the order of invocation of its members.
402 std::vector<CompileCommand> CompileCommandsForFile =
403 Compilations.getCompileCommands(File);
404 if (CompileCommandsForFile.empty()) {
405 // FIXME: There are two use cases here: doing a fuzzy
406 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
407 // about the .cc files that were not found, and the use case where I
408 // specify all files I want to run over explicitly, where this should
409 // be an error. We'll want to add an option for this.
410 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
413 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
414 // FIXME: chdir is thread hostile; on the other hand, creating the same
415 // behavior as chdir is complex: chdir resolves the path once, thus
416 // guaranteeing that all subsequent relative path operations work
417 // on the same path the original chdir resulted in. This makes a
418 // difference for example on network filesystems, where symlinks might be
419 // switched during runtime of the tool. Fixing this depends on having a
420 // file system abstraction that allows openat() style interactions.
421 if (OverlayFileSystem->setCurrentWorkingDirectory(
422 CompileCommand.Directory))
423 llvm::report_fatal_error("Cannot chdir into \"" +
424 Twine(CompileCommand.Directory) + "\n!");
426 // Now fill the in-memory VFS with the relative file mappings so it will
427 // have the correct relative paths. We never remove mappings but that
429 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
430 for (const auto &MappedFile : MappedFileContents)
431 if (!llvm::sys::path::is_absolute(MappedFile.first))
432 InMemoryFileSystem->addFile(
434 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
436 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
438 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
439 assert(!CommandLine.empty());
441 // Add the resource dir based on the binary of this tool. argv[0] in the
442 // compilation database may refer to a different compiler and we want to
443 // pick up the very same standard library that compiler is using. The
444 // builtin headers in the resource dir need to match the exact clang
445 // version the tool is using.
446 // FIXME: On linux, GetMainExecutable is independent of the value of the
447 // first argument, thus allowing ClangTool and runToolOnCode to just
448 // pass in made-up names here. Make sure this works on other platforms.
449 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
451 // FIXME: We need a callback mechanism for the tool writer to output a
452 // customized message for each file.
453 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
454 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
456 Invocation.setDiagnosticConsumer(DiagConsumer);
458 if (!Invocation.run()) {
459 // FIXME: Diagnostics should be used instead.
460 llvm::errs() << "Error while processing " << File << ".\n";
461 ProcessingFailed = true;
463 // Return to the initial directory to correctly resolve next file by
465 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
466 llvm::report_fatal_error("Cannot chdir into \"" +
467 Twine(InitialDirectory) + "\n!");
470 return ProcessingFailed ? 1 : 0;
475 class ASTBuilderAction : public ToolAction {
476 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
479 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
481 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
483 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
484 DiagnosticConsumer *DiagConsumer) override {
485 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
486 Invocation, std::move(PCHContainerOps),
487 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
489 /*ShouldOwnClient=*/false),
494 ASTs.push_back(std::move(AST));
500 int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
501 ASTBuilderAction Action(ASTs);
505 std::unique_ptr<ASTUnit>
506 buildASTFromCode(const Twine &Code, const Twine &FileName,
507 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
508 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
509 "clang-tool", std::move(PCHContainerOps));
512 std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
513 const Twine &Code, const std::vector<std::string> &Args,
514 const Twine &FileName, const Twine &ToolName,
515 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
516 ArgumentsAdjuster Adjuster) {
517 SmallString<16> FileNameStorage;
518 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
520 std::vector<std::unique_ptr<ASTUnit>> ASTs;
521 ASTBuilderAction Action(ASTs);
522 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
523 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
524 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
525 new vfs::InMemoryFileSystem);
526 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
527 llvm::IntrusiveRefCntPtr<FileManager> Files(
528 new FileManager(FileSystemOptions(), OverlayFileSystem));
530 ToolInvocation Invocation(
531 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
532 &Action, Files.get(), std::move(PCHContainerOps));
534 SmallString<1024> CodeStorage;
535 InMemoryFileSystem->addFile(FileNameRef, 0,
536 llvm::MemoryBuffer::getMemBuffer(
537 Code.toNullTerminatedStringRef(CodeStorage)));
538 if (!Invocation.run())
541 assert(ASTs.size() == 1);
542 return std::move(ASTs[0]);
545 } // end namespace tooling
546 } // end namespace clang