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)));
265 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
266 &Diagnostics, Compilation.get());
270 std::unique_ptr<clang::CompilerInvocation> Invocation(
271 newInvocation(&Diagnostics, *CC1Args));
272 // FIXME: remove this when all users have migrated!
273 for (const auto &It : MappedFileContents) {
274 // Inject the code as the given file name into the preprocessor options.
275 std::unique_ptr<llvm::MemoryBuffer> Input =
276 llvm::MemoryBuffer::getMemBuffer(It.getValue());
277 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
280 return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
281 std::move(PCHContainerOps));
284 bool ToolInvocation::runInvocation(
285 const char *BinaryName, clang::driver::Compilation *Compilation,
286 std::shared_ptr<clang::CompilerInvocation> Invocation,
287 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
288 // Show the invocation, with -v.
289 if (Invocation->getHeaderSearchOpts().Verbose) {
290 llvm::errs() << "clang Invocation:\n";
291 Compilation->getJobs().Print(llvm::errs(), "\n", true);
292 llvm::errs() << "\n";
295 return Action->runInvocation(std::move(Invocation), Files,
296 std::move(PCHContainerOps), DiagConsumer);
299 bool FrontendActionFactory::runInvocation(
300 std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
301 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
302 DiagnosticConsumer *DiagConsumer) {
303 // Create a compiler instance to handle the actual work.
304 clang::CompilerInstance Compiler(std::move(PCHContainerOps));
305 Compiler.setInvocation(std::move(Invocation));
306 Compiler.setFileManager(Files);
308 // The FrontendAction can have lifetime requirements for Compiler or its
309 // members, and we need to ensure it's deleted earlier than Compiler. So we
310 // pass it to an std::unique_ptr declared after the Compiler variable.
311 std::unique_ptr<FrontendAction> ScopedToolAction(create());
313 // Create the compiler's actual diagnostics engine.
314 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
315 if (!Compiler.hasDiagnostics())
318 Compiler.createSourceManager(*Files);
320 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
322 Files->clearStatCaches();
326 ClangTool::ClangTool(const CompilationDatabase &Compilations,
327 ArrayRef<std::string> SourcePaths,
328 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
329 : Compilations(Compilations), SourcePaths(SourcePaths),
330 PCHContainerOps(std::move(PCHContainerOps)),
331 OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
332 InMemoryFileSystem(new vfs::InMemoryFileSystem),
333 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
334 DiagConsumer(nullptr) {
335 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
336 appendArgumentsAdjuster(getClangStripOutputAdjuster());
337 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
340 ClangTool::~ClangTool() {}
342 void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
343 MappedFileContents.push_back(std::make_pair(FilePath, Content));
346 void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
349 combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
351 ArgsAdjuster = std::move(Adjuster);
354 void ClangTool::clearArgumentsAdjusters() {
355 ArgsAdjuster = nullptr;
358 static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
360 // Allow users to override the resource dir.
361 for (StringRef Arg : Args)
362 if (Arg.startswith("-resource-dir"))
365 // If there's no override in place add our resource dir.
366 Args.push_back("-resource-dir=" +
367 CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
370 int ClangTool::run(ToolAction *Action) {
371 // Exists solely for the purpose of lookup of the resource path.
372 // This just needs to be some symbol in the binary.
373 static int StaticSymbol;
375 llvm::SmallString<128> InitialDirectory;
376 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
377 llvm::report_fatal_error("Cannot detect current path: " +
378 Twine(EC.message()));
380 // First insert all absolute paths into the in-memory VFS. These are global
381 // for all compile commands.
382 if (SeenWorkingDirectories.insert("/").second)
383 for (const auto &MappedFile : MappedFileContents)
384 if (llvm::sys::path::is_absolute(MappedFile.first))
385 InMemoryFileSystem->addFile(
387 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
389 bool ProcessingFailed = false;
390 for (const auto &SourcePath : SourcePaths) {
391 std::string File(getAbsolutePath(SourcePath));
393 // Currently implementations of CompilationDatabase::getCompileCommands can
394 // change the state of the file system (e.g. prepare generated headers), so
395 // this method needs to run right before we invoke the tool, as the next
396 // file may require a different (incompatible) state of the file system.
398 // FIXME: Make the compilation database interface more explicit about the
399 // requirements to the order of invocation of its members.
400 std::vector<CompileCommand> CompileCommandsForFile =
401 Compilations.getCompileCommands(File);
402 if (CompileCommandsForFile.empty()) {
403 // FIXME: There are two use cases here: doing a fuzzy
404 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
405 // about the .cc files that were not found, and the use case where I
406 // specify all files I want to run over explicitly, where this should
407 // be an error. We'll want to add an option for this.
408 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
411 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
412 // FIXME: chdir is thread hostile; on the other hand, creating the same
413 // behavior as chdir is complex: chdir resolves the path once, thus
414 // guaranteeing that all subsequent relative path operations work
415 // on the same path the original chdir resulted in. This makes a
416 // difference for example on network filesystems, where symlinks might be
417 // switched during runtime of the tool. Fixing this depends on having a
418 // file system abstraction that allows openat() style interactions.
419 if (OverlayFileSystem->setCurrentWorkingDirectory(
420 CompileCommand.Directory))
421 llvm::report_fatal_error("Cannot chdir into \"" +
422 Twine(CompileCommand.Directory) + "\n!");
424 // Now fill the in-memory VFS with the relative file mappings so it will
425 // have the correct relative paths. We never remove mappings but that
427 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
428 for (const auto &MappedFile : MappedFileContents)
429 if (!llvm::sys::path::is_absolute(MappedFile.first))
430 InMemoryFileSystem->addFile(
432 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
434 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
436 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
437 assert(!CommandLine.empty());
439 // Add the resource dir based on the binary of this tool. argv[0] in the
440 // compilation database may refer to a different compiler and we want to
441 // pick up the very same standard library that compiler is using. The
442 // builtin headers in the resource dir need to match the exact clang
443 // version the tool is using.
444 // FIXME: On linux, GetMainExecutable is independent of the value of the
445 // first argument, thus allowing ClangTool and runToolOnCode to just
446 // pass in made-up names here. Make sure this works on other platforms.
447 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
449 // FIXME: We need a callback mechanism for the tool writer to output a
450 // customized message for each file.
451 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
452 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
454 Invocation.setDiagnosticConsumer(DiagConsumer);
456 if (!Invocation.run()) {
457 // FIXME: Diagnostics should be used instead.
458 llvm::errs() << "Error while processing " << File << ".\n";
459 ProcessingFailed = true;
461 // Return to the initial directory to correctly resolve next file by
463 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
464 llvm::report_fatal_error("Cannot chdir into \"" +
465 Twine(InitialDirectory) + "\n!");
468 return ProcessingFailed ? 1 : 0;
473 class ASTBuilderAction : public ToolAction {
474 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
477 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
479 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
481 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
482 DiagnosticConsumer *DiagConsumer) override {
483 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
484 Invocation, std::move(PCHContainerOps),
485 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
487 /*ShouldOwnClient=*/false),
492 ASTs.push_back(std::move(AST));
498 int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
499 ASTBuilderAction Action(ASTs);
503 std::unique_ptr<ASTUnit>
504 buildASTFromCode(const Twine &Code, const Twine &FileName,
505 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
506 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
507 "clang-tool", std::move(PCHContainerOps));
510 std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
511 const Twine &Code, const std::vector<std::string> &Args,
512 const Twine &FileName, const Twine &ToolName,
513 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
514 SmallString<16> FileNameStorage;
515 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
517 std::vector<std::unique_ptr<ASTUnit>> ASTs;
518 ASTBuilderAction Action(ASTs);
519 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
520 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
521 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
522 new vfs::InMemoryFileSystem);
523 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
524 llvm::IntrusiveRefCntPtr<FileManager> Files(
525 new FileManager(FileSystemOptions(), OverlayFileSystem));
526 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
527 &Action, Files.get(), std::move(PCHContainerOps));
529 SmallString<1024> CodeStorage;
530 InMemoryFileSystem->addFile(FileNameRef, 0,
531 llvm::MemoryBuffer::getMemBuffer(
532 Code.toNullTerminatedStringRef(CodeStorage)));
533 if (!Invocation.run())
536 assert(ASTs.size() == 1);
537 return std::move(ASTs[0]);
540 } // end namespace tooling
541 } // end namespace clang