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/Basic/Diagnostic.h"
17 #include "clang/Basic/DiagnosticIDs.h"
18 #include "clang/Basic/DiagnosticOptions.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/FileSystemOptions.h"
21 #include "clang/Basic/LLVM.h"
22 #include "clang/Basic/VirtualFileSystem.h"
23 #include "clang/Driver/Compilation.h"
24 #include "clang/Driver/Driver.h"
25 #include "clang/Driver/Job.h"
26 #include "clang/Driver/Options.h"
27 #include "clang/Driver/Tool.h"
28 #include "clang/Driver/ToolChain.h"
29 #include "clang/Frontend/ASTUnit.h"
30 #include "clang/Frontend/CompilerInstance.h"
31 #include "clang/Frontend/CompilerInvocation.h"
32 #include "clang/Frontend/FrontendDiagnostic.h"
33 #include "clang/Frontend/FrontendOptions.h"
34 #include "clang/Frontend/TextDiagnosticPrinter.h"
35 #include "clang/Lex/HeaderSearchOptions.h"
36 #include "clang/Lex/PreprocessorOptions.h"
37 #include "clang/Tooling/ArgumentsAdjusters.h"
38 #include "clang/Tooling/CompilationDatabase.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/ADT/IntrusiveRefCntPtr.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringRef.h"
43 #include "llvm/ADT/Twine.h"
44 #include "llvm/Option/ArgList.h"
45 #include "llvm/Option/OptTable.h"
46 #include "llvm/Option/Option.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/FileSystem.h"
51 #include "llvm/Support/Host.h"
52 #include "llvm/Support/MemoryBuffer.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/raw_ostream.h"
59 #include <system_error>
63 #define DEBUG_TYPE "clang-tooling"
65 using namespace clang;
66 using namespace tooling;
68 ToolAction::~ToolAction() = default;
70 FrontendActionFactory::~FrontendActionFactory() = default;
72 // FIXME: This file contains structural duplication with other parts of the
73 // code that sets up a compiler to run tools on it, and we should refactor
74 // it to be based on the same framework.
76 /// Builds a clang driver initialized for running clang tools.
77 static driver::Driver *newDriver(
78 DiagnosticsEngine *Diagnostics, const char *BinaryName,
79 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
80 driver::Driver *CompilerDriver =
81 new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
82 *Diagnostics, std::move(VFS));
83 CompilerDriver->setTitle("clang_based_tool");
84 return CompilerDriver;
87 /// Retrieves the clang CC1 specific flags out of the compilation's jobs.
89 /// Returns nullptr on error.
90 static const llvm::opt::ArgStringList *getCC1Arguments(
91 DiagnosticsEngine *Diagnostics, driver::Compilation *Compilation) {
92 // We expect to get back exactly one Command job, if we didn't something
93 // failed. Extract that job from the Compilation.
94 const driver::JobList &Jobs = Compilation->getJobs();
95 if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
96 SmallString<256> error_msg;
97 llvm::raw_svector_ostream error_stream(error_msg);
98 Jobs.Print(error_stream, "; ", true);
99 Diagnostics->Report(diag::err_fe_expected_compiler_job)
100 << error_stream.str();
104 // The one job we find should be to invoke clang again.
105 const auto &Cmd = cast<driver::Command>(*Jobs.begin());
106 if (StringRef(Cmd.getCreator().getName()) != "clang") {
107 Diagnostics->Report(diag::err_fe_expected_clang_command);
111 return &Cmd.getArguments();
117 /// Returns a clang build invocation initialized from the CC1 flags.
118 CompilerInvocation *newInvocation(
119 DiagnosticsEngine *Diagnostics, const llvm::opt::ArgStringList &CC1Args) {
120 assert(!CC1Args.empty() && "Must at least contain the program name!");
121 CompilerInvocation *Invocation = new CompilerInvocation;
122 CompilerInvocation::CreateFromArgs(
123 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
125 Invocation->getFrontendOpts().DisableFree = false;
126 Invocation->getCodeGenOpts().DisableFree = false;
130 bool runToolOnCode(FrontendAction *ToolAction, const Twine &Code,
131 const Twine &FileName,
132 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
133 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
134 FileName, "clang-tool",
135 std::move(PCHContainerOps));
138 } // namespace tooling
141 static std::vector<std::string>
142 getSyntaxOnlyToolArgs(const Twine &ToolName,
143 const std::vector<std::string> &ExtraArgs,
144 StringRef FileName) {
145 std::vector<std::string> Args;
146 Args.push_back(ToolName.str());
147 Args.push_back("-fsyntax-only");
148 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
149 Args.push_back(FileName.str());
156 bool runToolOnCodeWithArgs(
157 FrontendAction *ToolAction, const Twine &Code,
158 llvm::IntrusiveRefCntPtr<vfs::FileSystem> VFS,
159 const std::vector<std::string> &Args, const Twine &FileName,
160 const Twine &ToolName,
161 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
162 SmallString<16> FileNameStorage;
163 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
165 llvm::IntrusiveRefCntPtr<FileManager> Files(
166 new FileManager(FileSystemOptions(), VFS));
167 ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();
168 ToolInvocation Invocation(
169 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
170 ToolAction, Files.get(),
171 std::move(PCHContainerOps));
172 return Invocation.run();
175 bool runToolOnCodeWithArgs(
176 FrontendAction *ToolAction, const Twine &Code,
177 const std::vector<std::string> &Args, const Twine &FileName,
178 const Twine &ToolName,
179 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
180 const FileContentMappings &VirtualMappedFiles) {
181 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
182 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
183 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
184 new vfs::InMemoryFileSystem);
185 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
187 SmallString<1024> CodeStorage;
188 InMemoryFileSystem->addFile(FileName, 0,
189 llvm::MemoryBuffer::getMemBuffer(
190 Code.toNullTerminatedStringRef(CodeStorage)));
192 for (auto &FilenameWithContent : VirtualMappedFiles) {
193 InMemoryFileSystem->addFile(
194 FilenameWithContent.first, 0,
195 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
198 return runToolOnCodeWithArgs(ToolAction, Code, OverlayFileSystem, Args,
202 std::string getAbsolutePath(StringRef File) {
203 StringRef RelativePath(File);
204 // FIXME: Should '.\\' be accepted on Win32?
205 if (RelativePath.startswith("./")) {
206 RelativePath = RelativePath.substr(strlen("./"));
209 SmallString<1024> AbsolutePath = RelativePath;
210 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
213 llvm::sys::path::native(AbsolutePath);
214 return AbsolutePath.str();
217 void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
218 StringRef InvokedAs) {
219 if (!CommandLine.empty() && !InvokedAs.empty()) {
220 bool AlreadyHasTarget = false;
221 bool AlreadyHasMode = false;
222 // Skip CommandLine[0].
223 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
225 StringRef TokenRef(*Token);
227 (TokenRef == "-target" || TokenRef.startswith("-target="));
228 AlreadyHasMode |= (TokenRef == "--driver-mode" ||
229 TokenRef.startswith("--driver-mode="));
232 driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
233 if (!AlreadyHasMode && TargetMode.DriverMode) {
234 CommandLine.insert(++CommandLine.begin(), TargetMode.DriverMode);
236 if (!AlreadyHasTarget && TargetMode.TargetIsValid) {
237 CommandLine.insert(++CommandLine.begin(), {"-target",
238 TargetMode.TargetPrefix});
243 } // namespace tooling
248 class SingleFrontendActionFactory : public FrontendActionFactory {
249 FrontendAction *Action;
252 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
254 FrontendAction *create() override { return Action; }
259 ToolInvocation::ToolInvocation(
260 std::vector<std::string> CommandLine, ToolAction *Action,
261 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
262 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
263 Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {}
265 ToolInvocation::ToolInvocation(
266 std::vector<std::string> CommandLine, FrontendAction *FAction,
267 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
268 : CommandLine(std::move(CommandLine)),
269 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
270 Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {}
272 ToolInvocation::~ToolInvocation() {
277 void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
278 SmallString<1024> PathStorage;
279 llvm::sys::path::native(FilePath, PathStorage);
280 MappedFileContents[PathStorage] = Content;
283 bool ToolInvocation::run() {
284 std::vector<const char*> Argv;
285 for (const std::string &Str : CommandLine)
286 Argv.push_back(Str.c_str());
287 const char *const BinaryName = Argv[0];
288 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
289 unsigned MissingArgIndex, MissingArgCount;
290 std::unique_ptr<llvm::opt::OptTable> Opts = driver::createDriverOptTable();
291 llvm::opt::InputArgList ParsedArgs = Opts->ParseArgs(
292 ArrayRef<const char *>(Argv).slice(1), MissingArgIndex, MissingArgCount);
293 ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
294 TextDiagnosticPrinter DiagnosticPrinter(
295 llvm::errs(), &*DiagOpts);
296 DiagnosticsEngine Diagnostics(
297 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
298 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
300 const std::unique_ptr<driver::Driver> Driver(
301 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
302 // Since the input might only be virtual, don't check whether it exists.
303 Driver->setCheckInputsExist(false);
304 const std::unique_ptr<driver::Compilation> Compilation(
305 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
308 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
309 &Diagnostics, Compilation.get());
312 std::unique_ptr<CompilerInvocation> Invocation(
313 newInvocation(&Diagnostics, *CC1Args));
314 // FIXME: remove this when all users have migrated!
315 for (const auto &It : MappedFileContents) {
316 // Inject the code as the given file name into the preprocessor options.
317 std::unique_ptr<llvm::MemoryBuffer> Input =
318 llvm::MemoryBuffer::getMemBuffer(It.getValue());
319 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
322 return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
323 std::move(PCHContainerOps));
326 bool ToolInvocation::runInvocation(
327 const char *BinaryName, driver::Compilation *Compilation,
328 std::shared_ptr<CompilerInvocation> Invocation,
329 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
330 // Show the invocation, with -v.
331 if (Invocation->getHeaderSearchOpts().Verbose) {
332 llvm::errs() << "clang Invocation:\n";
333 Compilation->getJobs().Print(llvm::errs(), "\n", true);
334 llvm::errs() << "\n";
337 return Action->runInvocation(std::move(Invocation), Files,
338 std::move(PCHContainerOps), DiagConsumer);
341 bool FrontendActionFactory::runInvocation(
342 std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
343 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
344 DiagnosticConsumer *DiagConsumer) {
345 // Create a compiler instance to handle the actual work.
346 CompilerInstance Compiler(std::move(PCHContainerOps));
347 Compiler.setInvocation(std::move(Invocation));
348 Compiler.setFileManager(Files);
350 // The FrontendAction can have lifetime requirements for Compiler or its
351 // members, and we need to ensure it's deleted earlier than Compiler. So we
352 // pass it to an std::unique_ptr declared after the Compiler variable.
353 std::unique_ptr<FrontendAction> ScopedToolAction(create());
355 // Create the compiler's actual diagnostics engine.
356 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
357 if (!Compiler.hasDiagnostics())
360 Compiler.createSourceManager(*Files);
362 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
364 Files->clearStatCaches();
368 ClangTool::ClangTool(const CompilationDatabase &Compilations,
369 ArrayRef<std::string> SourcePaths,
370 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
371 IntrusiveRefCntPtr<vfs::FileSystem> BaseFS)
372 : Compilations(Compilations), SourcePaths(SourcePaths),
373 PCHContainerOps(std::move(PCHContainerOps)),
374 OverlayFileSystem(new vfs::OverlayFileSystem(std::move(BaseFS))),
375 InMemoryFileSystem(new vfs::InMemoryFileSystem),
376 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)) {
377 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
378 appendArgumentsAdjuster(getClangStripOutputAdjuster());
379 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
380 appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
383 ClangTool::~ClangTool() = default;
385 void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
386 MappedFileContents.push_back(std::make_pair(FilePath, Content));
389 void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
390 ArgsAdjuster = combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
393 void ClangTool::clearArgumentsAdjusters() {
394 ArgsAdjuster = nullptr;
397 static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
399 // Allow users to override the resource dir.
400 for (StringRef Arg : Args)
401 if (Arg.startswith("-resource-dir"))
404 // If there's no override in place add our resource dir.
405 Args.push_back("-resource-dir=" +
406 CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
409 int ClangTool::run(ToolAction *Action) {
410 // Exists solely for the purpose of lookup of the resource path.
411 // This just needs to be some symbol in the binary.
412 static int StaticSymbol;
414 std::string InitialDirectory;
415 if (llvm::ErrorOr<std::string> CWD =
416 OverlayFileSystem->getCurrentWorkingDirectory()) {
417 InitialDirectory = std::move(*CWD);
419 llvm::report_fatal_error("Cannot detect current path: " +
420 Twine(CWD.getError().message()));
423 // First insert all absolute paths into the in-memory VFS. These are global
424 // for all compile commands.
425 if (SeenWorkingDirectories.insert("/").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 bool ProcessingFailed = false;
433 bool FileSkipped = false;
434 for (const auto &SourcePath : SourcePaths) {
435 std::string File(getAbsolutePath(SourcePath));
437 // Currently implementations of CompilationDatabase::getCompileCommands can
438 // change the state of the file system (e.g. prepare generated headers), so
439 // this method needs to run right before we invoke the tool, as the next
440 // file may require a different (incompatible) state of the file system.
442 // FIXME: Make the compilation database interface more explicit about the
443 // requirements to the order of invocation of its members.
444 std::vector<CompileCommand> CompileCommandsForFile =
445 Compilations.getCompileCommands(File);
446 if (CompileCommandsForFile.empty()) {
447 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
451 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
452 // FIXME: chdir is thread hostile; on the other hand, creating the same
453 // behavior as chdir is complex: chdir resolves the path once, thus
454 // guaranteeing that all subsequent relative path operations work
455 // on the same path the original chdir resulted in. This makes a
456 // difference for example on network filesystems, where symlinks might be
457 // switched during runtime of the tool. Fixing this depends on having a
458 // file system abstraction that allows openat() style interactions.
459 if (OverlayFileSystem->setCurrentWorkingDirectory(
460 CompileCommand.Directory))
461 llvm::report_fatal_error("Cannot chdir into \"" +
462 Twine(CompileCommand.Directory) + "\n!");
464 // Now fill the in-memory VFS with the relative file mappings so it will
465 // have the correct relative paths. We never remove mappings but that
467 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
468 for (const auto &MappedFile : MappedFileContents)
469 if (!llvm::sys::path::is_absolute(MappedFile.first))
470 InMemoryFileSystem->addFile(
472 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
474 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
476 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
477 assert(!CommandLine.empty());
479 // Add the resource dir based on the binary of this tool. argv[0] in the
480 // compilation database may refer to a different compiler and we want to
481 // pick up the very same standard library that compiler is using. The
482 // builtin headers in the resource dir need to match the exact clang
483 // version the tool is using.
484 // FIXME: On linux, GetMainExecutable is independent of the value of the
485 // first argument, thus allowing ClangTool and runToolOnCode to just
486 // pass in made-up names here. Make sure this works on other platforms.
487 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
489 // FIXME: We need a callback mechanism for the tool writer to output a
490 // customized message for each file.
491 LLVM_DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
492 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
494 Invocation.setDiagnosticConsumer(DiagConsumer);
496 if (!Invocation.run()) {
497 // FIXME: Diagnostics should be used instead.
498 llvm::errs() << "Error while processing " << File << ".\n";
499 ProcessingFailed = true;
501 // Return to the initial directory to correctly resolve next file by
503 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
504 llvm::report_fatal_error("Cannot chdir into \"" +
505 Twine(InitialDirectory) + "\n!");
508 return ProcessingFailed ? 1 : (FileSkipped ? 2 : 0);
513 class ASTBuilderAction : public ToolAction {
514 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
517 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
519 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
521 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
522 DiagnosticConsumer *DiagConsumer) override {
523 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
524 Invocation, std::move(PCHContainerOps),
525 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
527 /*ShouldOwnClient=*/false),
532 ASTs.push_back(std::move(AST));
539 int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
540 ASTBuilderAction Action(ASTs);
547 std::unique_ptr<ASTUnit>
548 buildASTFromCode(const Twine &Code, const Twine &FileName,
549 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
550 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
551 "clang-tool", std::move(PCHContainerOps));
554 std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
555 const Twine &Code, const std::vector<std::string> &Args,
556 const Twine &FileName, const Twine &ToolName,
557 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
558 ArgumentsAdjuster Adjuster) {
559 SmallString<16> FileNameStorage;
560 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
562 std::vector<std::unique_ptr<ASTUnit>> ASTs;
563 ASTBuilderAction Action(ASTs);
564 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
565 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
566 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
567 new vfs::InMemoryFileSystem);
568 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
569 llvm::IntrusiveRefCntPtr<FileManager> Files(
570 new FileManager(FileSystemOptions(), OverlayFileSystem));
572 ToolInvocation Invocation(
573 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
574 &Action, Files.get(), std::move(PCHContainerOps));
576 SmallString<1024> CodeStorage;
577 InMemoryFileSystem->addFile(FileNameRef, 0,
578 llvm::MemoryBuffer::getMemBuffer(
579 Code.toNullTerminatedStringRef(CodeStorage)));
580 if (!Invocation.run())
583 assert(ASTs.size() == 1);
584 return std::move(ASTs[0]);
587 } // namespace tooling