1//===- Tooling.cpp - Running clang standalone tools -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements functions to run clang tools standalone instead
10// of running them as a plugin.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Tooling/Tooling.h"
15#include "clang/Basic/Diagnostic.h"
16#include "clang/Basic/DiagnosticFrontend.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/Driver/Compilation.h"
23#include "clang/Driver/Driver.h"
24#include "clang/Driver/Job.h"
25#include "clang/Driver/Tool.h"
26#include "clang/Driver/ToolChain.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
29#include "clang/Frontend/CompilerInvocation.h"
30#include "clang/Frontend/FrontendOptions.h"
31#include "clang/Frontend/TextDiagnosticPrinter.h"
32#include "clang/Lex/HeaderSearchOptions.h"
33#include "clang/Lex/PreprocessorOptions.h"
34#include "clang/Options/OptionUtils.h"
35#include "clang/Options/Options.h"
36#include "clang/Tooling/ArgumentsAdjusters.h"
37#include "clang/Tooling/CompilationDatabase.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/IntrusiveRefCntPtr.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/Option/ArgList.h"
43#include "llvm/Option/OptTable.h"
44#include "llvm/Option/Option.h"
45#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Path.h"
50#include "llvm/Support/VirtualFileSystem.h"
51#include "llvm/Support/raw_ostream.h"
52#include "llvm/TargetParser/Host.h"
53#include <cassert>
54#include <cstring>
55#include <memory>
56#include <string>
57#include <system_error>
58#include <utility>
59#include <vector>
60
61#define DEBUG_TYPE "clang-tooling"
62
63using namespace clang;
64using namespace tooling;
65
66ToolAction::~ToolAction() = default;
67
68FrontendActionFactory::~FrontendActionFactory() = default;
69
70// FIXME: This file contains structural duplication with other parts of the
71// code that sets up a compiler to run tools on it, and we should refactor
72// it to be based on the same framework.
73
74/// Builds a clang driver initialized for running clang tools.
75static driver::Driver *
76newDriver(DiagnosticsEngine *Diagnostics, const char *BinaryName,
77 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
78 driver::Driver *CompilerDriver =
79 new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
80 *Diagnostics, "clang LLVM compiler", std::move(VFS));
81 CompilerDriver->setTitle("clang_based_tool");
82 return CompilerDriver;
83}
84
85/// Decide whether extra compiler frontend commands can be ignored.
86static bool ignoreExtraCC1Commands(const driver::Compilation *Compilation) {
87 const driver::JobList &Jobs = Compilation->getJobs();
88 const driver::ActionList &Actions = Compilation->getActions();
89
90 bool OffloadCompilation = false;
91
92 // Jobs and Actions look very different depending on whether the Clang tool
93 // injected -fsyntax-only or not. Try to handle both cases here.
94
95 for (const auto &Job : Jobs)
96 if (StringRef(Job.getExecutable()) == "clang-offload-bundler")
97 OffloadCompilation = true;
98
99 if (Jobs.size() > 1) {
100 for (auto *A : Actions) {
101 // On MacOSX real actions may end up being wrapped in BindArchAction
102 if (isa<driver::BindArchAction>(Val: A))
103 A = *A->input_begin();
104 if (isa<driver::OffloadAction>(Val: A)) {
105 // Offload compilation has 2 top-level actions, one (at the front) is
106 // the original host compilation and the other is offload action
107 // composed of at least one device compilation. For such case, general
108 // tooling will consider host-compilation only. For tooling on device
109 // compilation, device compilation only option, such as
110 // `--cuda-device-only`, needs specifying.
111 if (Actions.size() > 1) {
112 assert(
113 isa<driver::CompileJobAction>(Actions.front()) ||
114 // On MacOSX real actions may end up being wrapped in
115 // BindArchAction.
116 (isa<driver::BindArchAction>(Actions.front()) &&
117 isa<driver::CompileJobAction>(*Actions.front()->input_begin())));
118 }
119 OffloadCompilation = true;
120 break;
121 }
122 }
123 }
124
125 return OffloadCompilation;
126}
127
128namespace clang {
129namespace tooling {
130
131const llvm::opt::ArgStringList *
132getCC1Arguments(DiagnosticsEngine *Diagnostics,
133 driver::Compilation *Compilation) {
134 const driver::JobList &Jobs = Compilation->getJobs();
135
136 auto IsCC1Command = [](const driver::Command &Cmd) {
137 return StringRef(Cmd.getCreator().getName()) == "clang";
138 };
139
140 auto IsSrcFile = [](const driver::InputInfo &II) {
141 return isSrcFile(Id: II.getType());
142 };
143
144 llvm::SmallVector<const driver::Command *, 1> CC1Jobs;
145 for (const driver::Command &Job : Jobs)
146 if (IsCC1Command(Job) && llvm::all_of(Range: Job.getInputInfos(), P: IsSrcFile))
147 CC1Jobs.push_back(Elt: &Job);
148
149 // If there are no jobs for source files, try checking again for a single job
150 // with any file type. This accepts a preprocessed file as input.
151 if (CC1Jobs.empty())
152 for (const driver::Command &Job : Jobs)
153 if (IsCC1Command(Job))
154 CC1Jobs.push_back(Elt: &Job);
155
156 if (CC1Jobs.empty() ||
157 (CC1Jobs.size() > 1 && !ignoreExtraCC1Commands(Compilation))) {
158 SmallString<256> error_msg;
159 llvm::raw_svector_ostream error_stream(error_msg);
160 Jobs.Print(OS&: error_stream, Terminator: "; ", Quote: true);
161 Diagnostics->Report(DiagID: diag::err_fe_expected_compiler_job)
162 << error_stream.str();
163 return nullptr;
164 }
165
166 return &CC1Jobs[0]->getArguments();
167}
168
169/// Returns a clang build invocation initialized from the CC1 flags.
170CompilerInvocation *newInvocation(DiagnosticsEngine *Diagnostics,
171 ArrayRef<const char *> CC1Args,
172 const char *const BinaryName) {
173 assert(!CC1Args.empty() && "Must at least contain the program name!");
174 CompilerInvocation *Invocation = new CompilerInvocation;
175 CompilerInvocation::CreateFromArgs(Res&: *Invocation, CommandLineArgs: CC1Args, Diags&: *Diagnostics,
176 Argv0: BinaryName);
177 Invocation->getFrontendOpts().DisableFree = false;
178 Invocation->getCodeGenOpts().DisableFree = false;
179 return Invocation;
180}
181
182bool runToolOnCode(std::unique_ptr<FrontendAction> ToolAction,
183 const Twine &Code, const Twine &FileName,
184 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
185 return runToolOnCodeWithArgs(ToolAction: std::move(ToolAction), Code,
186 Args: std::vector<std::string>(), FileName,
187 ToolName: "clang-tool", PCHContainerOps: std::move(PCHContainerOps));
188}
189
190} // namespace tooling
191} // namespace clang
192
193static std::vector<std::string>
194getSyntaxOnlyToolArgs(const Twine &ToolName,
195 const std::vector<std::string> &ExtraArgs,
196 StringRef FileName) {
197 std::vector<std::string> Args;
198 Args.push_back(x: ToolName.str());
199 Args.push_back(x: "-fsyntax-only");
200 llvm::append_range(C&: Args, R: ExtraArgs);
201 Args.push_back(x: FileName.str());
202 return Args;
203}
204
205namespace clang {
206namespace tooling {
207
208bool runToolOnCodeWithArgs(
209 std::unique_ptr<FrontendAction> ToolAction, const Twine &Code,
210 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
211 const std::vector<std::string> &Args, const Twine &FileName,
212 const Twine &ToolName,
213 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
214 SmallString<16> FileNameStorage;
215 StringRef FileNameRef = FileName.toNullTerminatedStringRef(Out&: FileNameStorage);
216
217 llvm::IntrusiveRefCntPtr<FileManager> Files =
218 llvm::makeIntrusiveRefCnt<FileManager>(A: FileSystemOptions(), A&: VFS);
219 ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();
220 ToolInvocation Invocation(
221 getSyntaxOnlyToolArgs(ToolName, ExtraArgs: Adjuster(Args, FileNameRef), FileName: FileNameRef),
222 std::move(ToolAction), Files.get(), std::move(PCHContainerOps));
223 return Invocation.run();
224}
225
226bool runToolOnCodeWithArgs(
227 std::unique_ptr<FrontendAction> ToolAction, const Twine &Code,
228 const std::vector<std::string> &Args, const Twine &FileName,
229 const Twine &ToolName,
230 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
231 const FileContentMappings &VirtualMappedFiles) {
232 auto OverlayFileSystem =
233 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
234 A: llvm::vfs::getRealFileSystem());
235 auto InMemoryFileSystem =
236 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
237 OverlayFileSystem->pushOverlay(FS: InMemoryFileSystem);
238
239 SmallString<1024> CodeStorage;
240 InMemoryFileSystem->addFile(Path: FileName, ModificationTime: 0,
241 Buffer: llvm::MemoryBuffer::getMemBuffer(
242 InputData: Code.toNullTerminatedStringRef(Out&: CodeStorage)));
243
244 for (auto &FilenameWithContent : VirtualMappedFiles) {
245 InMemoryFileSystem->addFile(
246 Path: FilenameWithContent.first, ModificationTime: 0,
247 Buffer: llvm::MemoryBuffer::getMemBuffer(InputData: FilenameWithContent.second));
248 }
249
250 return runToolOnCodeWithArgs(ToolAction: std::move(ToolAction), Code, VFS: OverlayFileSystem,
251 Args, FileName, ToolName);
252}
253
254llvm::Expected<std::string> getAbsolutePath(llvm::vfs::FileSystem &FS,
255 StringRef File) {
256 StringRef RelativePath(File);
257 // FIXME: Should '.\\' be accepted on Win32?
258 RelativePath.consume_front(Prefix: "./");
259
260 SmallString<1024> AbsolutePath = RelativePath;
261 if (auto EC = FS.makeAbsolute(Path&: AbsolutePath))
262 return llvm::errorCodeToError(EC);
263 llvm::sys::path::native(path&: AbsolutePath);
264 return std::string(AbsolutePath);
265}
266
267std::string getAbsolutePath(StringRef File) {
268 return llvm::cantFail(ValOrErr: getAbsolutePath(FS&: *llvm::vfs::getRealFileSystem(), File));
269}
270
271void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
272 StringRef InvokedAs) {
273 if (CommandLine.empty() || InvokedAs.empty())
274 return;
275 const auto &Table = getDriverOptTable();
276 // --target=X
277 StringRef TargetOPT = Table.getOption(Opt: options::OPT_target).getPrefixedName();
278 // -target X
279 StringRef TargetOPTLegacy =
280 Table.getOption(Opt: options::OPT_target_legacy_spelling).getPrefixedName();
281 // --driver-mode=X
282 StringRef DriverModeOPT =
283 Table.getOption(Opt: options::OPT_driver_mode).getPrefixedName();
284 auto TargetMode =
285 driver::ToolChain::getTargetAndModeFromProgramName(ProgName: InvokedAs);
286 // No need to search for target args if we don't have a target/mode to insert.
287 bool ShouldAddTarget = TargetMode.TargetIsValid;
288 bool ShouldAddMode = TargetMode.DriverMode != nullptr;
289 // Skip CommandLine[0].
290 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
291 ++Token) {
292 StringRef TokenRef(*Token);
293 ShouldAddTarget = ShouldAddTarget && !TokenRef.starts_with(Prefix: TargetOPT) &&
294 TokenRef != TargetOPTLegacy;
295 ShouldAddMode = ShouldAddMode && !TokenRef.starts_with(Prefix: DriverModeOPT);
296 }
297 if (ShouldAddMode) {
298 CommandLine.insert(position: ++CommandLine.begin(), x: TargetMode.DriverMode);
299 }
300 if (ShouldAddTarget) {
301 CommandLine.insert(position: ++CommandLine.begin(),
302 x: (TargetOPT + TargetMode.TargetPrefix).str());
303 }
304}
305
306void addExpandedResponseFiles(std::vector<std::string> &CommandLine,
307 llvm::StringRef WorkingDir,
308 llvm::cl::TokenizerCallback Tokenizer,
309 llvm::vfs::FileSystem &FS) {
310 bool SeenRSPFile = false;
311 llvm::SmallVector<const char *, 20> Argv;
312 Argv.reserve(N: CommandLine.size());
313 for (auto &Arg : CommandLine) {
314 Argv.push_back(Elt: Arg.c_str());
315 if (!Arg.empty())
316 SeenRSPFile |= Arg.front() == '@';
317 }
318 if (!SeenRSPFile)
319 return;
320 llvm::BumpPtrAllocator Alloc;
321 llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
322 llvm::Error Err =
323 ECtx.setVFS(&FS).setCurrentDir(WorkingDir).expandResponseFiles(Argv);
324 if (Err)
325 llvm::errs() << Err;
326 // Don't assign directly, Argv aliases CommandLine.
327 std::vector<std::string> ExpandedArgv(Argv.begin(), Argv.end());
328 CommandLine = std::move(ExpandedArgv);
329}
330
331} // namespace tooling
332} // namespace clang
333
334namespace {
335
336class SingleFrontendActionFactory : public FrontendActionFactory {
337 std::unique_ptr<FrontendAction> Action;
338
339public:
340 SingleFrontendActionFactory(std::unique_ptr<FrontendAction> Action)
341 : Action(std::move(Action)) {}
342
343 std::unique_ptr<FrontendAction> create() override {
344 return std::move(Action);
345 }
346};
347
348} // namespace
349
350ToolInvocation::ToolInvocation(
351 std::vector<std::string> CommandLine, ToolAction *Action,
352 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
353 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
354 Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {}
355
356ToolInvocation::ToolInvocation(
357 std::vector<std::string> CommandLine,
358 std::unique_ptr<FrontendAction> FAction, FileManager *Files,
359 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
360 : CommandLine(std::move(CommandLine)),
361 Action(new SingleFrontendActionFactory(std::move(FAction))),
362 OwnsAction(true), Files(Files),
363 PCHContainerOps(std::move(PCHContainerOps)) {}
364
365ToolInvocation::~ToolInvocation() {
366 if (OwnsAction)
367 delete Action;
368}
369
370bool ToolInvocation::run() {
371 llvm::opt::ArgStringList Argv;
372 for (const std::string &Str : CommandLine)
373 Argv.push_back(Elt: Str.c_str());
374 const char *const BinaryName = Argv[0];
375
376 // Parse diagnostic options from the driver command-line only if none were
377 // explicitly set.
378 std::unique_ptr<DiagnosticOptions> ParsedDiagOpts;
379 DiagnosticOptions *DiagOpts = this->DiagOpts;
380 if (!DiagOpts) {
381 ParsedDiagOpts = CreateAndPopulateDiagOpts(Argv);
382 DiagOpts = &*ParsedDiagOpts;
383 }
384
385 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), *DiagOpts);
386 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics =
387 CompilerInstance::createDiagnostics(
388 VFS&: Files->getVirtualFileSystem(), Opts&: *DiagOpts,
389 Client: DiagConsumer ? DiagConsumer : &DiagnosticPrinter, ShouldOwnClient: false);
390 // Although `Diagnostics` are used only for command-line parsing, the custom
391 // `DiagConsumer` might expect a `SourceManager` to be present.
392 SourceManager SrcMgr(*Diagnostics, *Files);
393 Diagnostics->setSourceManager(&SrcMgr);
394
395 // We already have a cc1, just create an invocation.
396 if (CommandLine.size() >= 2 && CommandLine[1] == "-cc1") {
397 ArrayRef<const char *> CC1Args = ArrayRef(Argv).drop_front();
398 std::unique_ptr<CompilerInvocation> Invocation(
399 newInvocation(Diagnostics: &*Diagnostics, CC1Args, BinaryName));
400 if (Diagnostics->hasErrorOccurred()) {
401 Diagnostics->getClient()->finish();
402 return false;
403 }
404 const bool Success = Action->runInvocation(
405 Invocation: std::move(Invocation), Files, PCHContainerOps: std::move(PCHContainerOps), DiagConsumer);
406 Diagnostics->getClient()->finish();
407 return Success;
408 }
409
410 const std::unique_ptr<driver::Driver> Driver(
411 newDriver(Diagnostics: &*Diagnostics, BinaryName, VFS: Files->getVirtualFileSystemPtr()));
412 // The "input file not found" diagnostics from the driver are useful.
413 // The driver is only aware of the VFS working directory, but some clients
414 // change this at the FileManager level instead.
415 // In this case the checks have false positives, so skip them.
416 if (!Files->getFileSystemOpts().WorkingDir.empty())
417 Driver->setCheckInputsExist(false);
418 const std::unique_ptr<driver::Compilation> Compilation(
419 Driver->BuildCompilation(Args: llvm::ArrayRef(Argv)));
420 if (!Compilation) {
421 Diagnostics->getClient()->finish();
422 return false;
423 }
424 const llvm::opt::ArgStringList *const CC1Args =
425 getCC1Arguments(Diagnostics: &*Diagnostics, Compilation: Compilation.get());
426 if (!CC1Args) {
427 Diagnostics->getClient()->finish();
428 return false;
429 }
430 std::unique_ptr<CompilerInvocation> Invocation(
431 newInvocation(Diagnostics: &*Diagnostics, CC1Args: *CC1Args, BinaryName));
432 const bool Success =
433 runInvocation(BinaryName, Compilation: Compilation.get(), Invocation: std::move(Invocation),
434 PCHContainerOps: std::move(PCHContainerOps));
435 Diagnostics->getClient()->finish();
436 return Success;
437}
438
439bool ToolInvocation::runInvocation(
440 const char *BinaryName, driver::Compilation *Compilation,
441 std::shared_ptr<CompilerInvocation> Invocation,
442 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
443 // Show the invocation, with -v.
444 if (Invocation->getHeaderSearchOpts().Verbose) {
445 llvm::errs() << "clang Invocation:\n";
446 Compilation->getJobs().Print(OS&: llvm::errs(), Terminator: "\n", Quote: true);
447 llvm::errs() << "\n";
448 }
449
450 return Action->runInvocation(Invocation: std::move(Invocation), Files,
451 PCHContainerOps: std::move(PCHContainerOps), DiagConsumer);
452}
453
454bool FrontendActionFactory::runInvocation(
455 std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
456 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
457 DiagnosticConsumer *DiagConsumer) {
458 // Create a compiler instance to handle the actual work.
459 CompilerInstance Compiler(std::move(Invocation), std::move(PCHContainerOps));
460 Compiler.setVirtualFileSystem(Files->getVirtualFileSystemPtr());
461 Compiler.setFileManager(Files);
462 Compiler.createDiagnostics(Client: DiagConsumer, /*ShouldOwnClient=*/false);
463 Compiler.createSourceManager();
464
465 // The FrontendAction can have lifetime requirements for Compiler or its
466 // members, and we need to ensure it's deleted earlier than Compiler. So we
467 // pass it to an std::unique_ptr declared after the Compiler variable.
468 std::unique_ptr<FrontendAction> ScopedToolAction(create());
469
470 const bool Success = Compiler.ExecuteAction(Act&: *ScopedToolAction);
471
472 Files->clearStatCache();
473 return Success;
474}
475
476ClangTool::ClangTool(const CompilationDatabase &Compilations,
477 ArrayRef<std::string> SourcePaths,
478 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
479 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
480 IntrusiveRefCntPtr<FileManager> Files)
481 : Compilations(Compilations), SourcePaths(SourcePaths),
482 PCHContainerOps(std::move(PCHContainerOps)),
483 OverlayFileSystem(llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
484 A: std::move(BaseFS))),
485 InMemoryFileSystem(
486 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>()),
487 Files(Files ? Files
488 : llvm::makeIntrusiveRefCnt<FileManager>(A: FileSystemOptions(),
489 A&: OverlayFileSystem)) {
490 OverlayFileSystem->pushOverlay(FS: InMemoryFileSystem);
491 appendArgumentsAdjuster(Adjuster: getClangStripOutputAdjuster());
492 appendArgumentsAdjuster(Adjuster: getClangSyntaxOnlyAdjuster());
493 appendArgumentsAdjuster(Adjuster: getClangStripDependencyFileAdjuster());
494 if (Files)
495 Files->setVirtualFileSystem(OverlayFileSystem);
496}
497
498ClangTool::~ClangTool() = default;
499
500void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
501 MappedFileContents.push_back(x: std::make_pair(x&: FilePath, y&: Content));
502}
503
504void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
505 ArgsAdjuster = combineAdjusters(First: std::move(ArgsAdjuster), Second: std::move(Adjuster));
506}
507
508void ClangTool::clearArgumentsAdjusters() { ArgsAdjuster = nullptr; }
509
510static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
511 void *MainAddr) {
512 // Allow users to override the resource dir.
513 for (StringRef Arg : Args)
514 if (Arg.starts_with(Prefix: "-resource-dir"))
515 return;
516
517 // If there's no override in place add our resource dir.
518 Args = getInsertArgumentAdjuster(
519 Extra: ("-resource-dir=" + GetResourcesPath(Argv0, MainAddr)).c_str())(Args, "");
520}
521
522int ClangTool::run(ToolAction *Action) {
523 // Exists solely for the purpose of lookup of the resource path.
524 // This just needs to be some symbol in the binary.
525 static int StaticSymbol;
526
527 // First insert all absolute paths into the in-memory VFS. These are global
528 // for all compile commands.
529 if (SeenWorkingDirectories.insert(key: "/").second)
530 for (const auto &MappedFile : MappedFileContents)
531 if (llvm::sys::path::is_absolute(path: MappedFile.first))
532 InMemoryFileSystem->addFile(
533 Path: MappedFile.first, ModificationTime: 0,
534 Buffer: llvm::MemoryBuffer::getMemBuffer(InputData: MappedFile.second));
535
536 bool ProcessingFailed = false;
537 bool FileSkipped = false;
538 // Compute all absolute paths before we run any actions, as those will change
539 // the working directory.
540 std::vector<std::string> AbsolutePaths;
541 AbsolutePaths.reserve(n: SourcePaths.size());
542 for (const auto &SourcePath : SourcePaths) {
543 auto AbsPath = getAbsolutePath(FS&: *OverlayFileSystem, File: SourcePath);
544 if (!AbsPath) {
545 llvm::errs() << "Skipping " << SourcePath
546 << ". Error while getting an absolute path: "
547 << llvm::toString(E: AbsPath.takeError()) << "\n";
548 continue;
549 }
550 AbsolutePaths.push_back(x: std::move(*AbsPath));
551 }
552
553 // Remember the working directory in case we need to restore it.
554 std::string InitialWorkingDir;
555 if (auto CWD = OverlayFileSystem->getCurrentWorkingDirectory()) {
556 InitialWorkingDir = std::move(*CWD);
557 } else {
558 llvm::errs() << "Could not get working directory: "
559 << CWD.getError().message() << "\n";
560 }
561
562 size_t NumOfTotalFiles = AbsolutePaths.size();
563 unsigned CurrentFileIndex = 0;
564 for (llvm::StringRef File : AbsolutePaths) {
565 ++CurrentFileIndex;
566 // Currently implementations of CompilationDatabase::getCompileCommands can
567 // change the state of the file system (e.g. prepare generated headers), so
568 // this method needs to run right before we invoke the tool, as the next
569 // file may require a different (incompatible) state of the file system.
570 //
571 // FIXME: Make the compilation database interface more explicit about the
572 // requirements to the order of invocation of its members.
573 std::vector<CompileCommand> CompileCommandsForFile =
574 Compilations.getCompileCommands(FilePath: File);
575 if (CompileCommandsForFile.empty()) {
576 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
577 FileSkipped = true;
578 continue;
579 }
580 unsigned CurrentCommandIndexForFile = 0;
581 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
582 // If the 'directory' field of the compilation database is empty, display
583 // an error and use the working directory instead.
584 StringRef Directory = CompileCommand.Directory;
585 if (Directory.empty()) {
586 llvm::errs() << "'directory' field of compilation database is empty; "
587 "using the current working directory instead.\n";
588 Directory = InitialWorkingDir;
589 }
590
591 // FIXME: chdir is thread hostile; on the other hand, creating the same
592 // behavior as chdir is complex: chdir resolves the path once, thus
593 // guaranteeing that all subsequent relative path operations work
594 // on the same path the original chdir resulted in. This makes a
595 // difference for example on network filesystems, where symlinks might be
596 // switched during runtime of the tool. Fixing this depends on having a
597 // file system abstraction that allows openat() style interactions.
598 if (OverlayFileSystem->setCurrentWorkingDirectory(Directory))
599 llvm::report_fatal_error(reason: "Cannot chdir into \"" + Twine(Directory) +
600 "\"!");
601
602 // Now fill the in-memory VFS with the relative file mappings so it will
603 // have the correct relative paths. We never remove mappings but that
604 // should be fine.
605 if (SeenWorkingDirectories.insert(key: Directory).second)
606 for (const auto &MappedFile : MappedFileContents)
607 if (!llvm::sys::path::is_absolute(path: MappedFile.first))
608 InMemoryFileSystem->addFile(
609 Path: MappedFile.first, ModificationTime: 0,
610 Buffer: llvm::MemoryBuffer::getMemBuffer(InputData: MappedFile.second));
611
612 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
613 if (ArgsAdjuster)
614 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
615 assert(!CommandLine.empty());
616
617 // Add the resource dir based on the binary of this tool. argv[0] in the
618 // compilation database may refer to a different compiler and we want to
619 // pick up the very same standard library that compiler is using. The
620 // builtin headers in the resource dir need to match the exact clang
621 // version the tool is using.
622 // FIXME: On linux, GetMainExecutable is independent of the value of the
623 // first argument, thus allowing ClangTool and runToolOnCode to just
624 // pass in made-up names here. Make sure this works on other platforms.
625 injectResourceDir(Args&: CommandLine, Argv0: "clang_tool", MainAddr: &StaticSymbol);
626
627 ++CurrentCommandIndexForFile;
628
629 // FIXME: We need a callback mechanism for the tool writer to output a
630 // customized message for each file.
631 if (NumOfTotalFiles > 1 || CompileCommandsForFile.size() > 1) {
632 llvm::errs() << "[" << std::to_string(val: CurrentFileIndex) << "/"
633 << std::to_string(val: NumOfTotalFiles) << "]";
634 if (CompileCommandsForFile.size() > 1) {
635 llvm::errs() << " (" << std::to_string(val: CurrentCommandIndexForFile)
636 << "/" << std::to_string(val: CompileCommandsForFile.size())
637 << ")";
638 }
639 llvm::errs() << " Processing file " << File << ".\n";
640 }
641 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
642 PCHContainerOps);
643 Invocation.setDiagnosticConsumer(DiagConsumer);
644
645 if (!Invocation.run()) {
646 // FIXME: Diagnostics should be used instead.
647 if (PrintErrorMessage)
648 llvm::errs() << "Error while processing " << File << ".\n";
649 ProcessingFailed = true;
650 }
651 }
652 }
653
654 if (!InitialWorkingDir.empty()) {
655 if (auto EC =
656 OverlayFileSystem->setCurrentWorkingDirectory(InitialWorkingDir))
657 llvm::errs() << "Error when trying to restore working dir: "
658 << EC.message() << "\n";
659 }
660 return ProcessingFailed ? 1 : (FileSkipped ? 2 : 0);
661}
662
663namespace {
664
665class ASTBuilderAction : public ToolAction {
666 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
667 CaptureDiagsKind CaptureKind;
668
669public:
670 ASTBuilderAction(
671 std::vector<std::unique_ptr<ASTUnit>> &ASTs,
672 CaptureDiagsKind CaptureDiagnosticsKind = CaptureDiagsKind::None)
673 : ASTs(ASTs), CaptureKind(CaptureDiagnosticsKind) {}
674
675 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
676 FileManager *Files,
677 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
678 DiagnosticConsumer *DiagConsumer) override {
679 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
680 CI: Invocation, PCHContainerOps: std::move(PCHContainerOps), DiagOpts: nullptr,
681 Diags: CompilerInstance::createDiagnostics(VFS&: Files->getVirtualFileSystem(),
682 Opts&: Invocation->getDiagnosticOpts(),
683 Client: DiagConsumer,
684 /*ShouldOwnClient=*/false),
685 FileMgr: Files, OnlyLocalDecls: false, CaptureDiagnostics: CaptureKind);
686 if (!AST)
687 return false;
688
689 ASTs.push_back(x: std::move(AST));
690 return true;
691 }
692};
693
694} // namespace
695
696int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
697 ASTBuilderAction Action(ASTs);
698 return run(Action: &Action);
699}
700
701void ClangTool::setPrintErrorMessage(bool PrintErrorMessage) {
702 this->PrintErrorMessage = PrintErrorMessage;
703}
704
705namespace clang {
706namespace tooling {
707
708std::unique_ptr<ASTUnit>
709buildASTFromCode(StringRef Code, StringRef FileName,
710 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
711 return buildASTFromCodeWithArgs(Code, Args: std::vector<std::string>(), FileName,
712 ToolName: "clang-tool", PCHContainerOps: std::move(PCHContainerOps));
713}
714
715std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
716 StringRef Code, const std::vector<std::string> &Args, StringRef FileName,
717 StringRef ToolName, std::shared_ptr<PCHContainerOperations> PCHContainerOps,
718 ArgumentsAdjuster Adjuster, const FileContentMappings &VirtualMappedFiles,
719 DiagnosticConsumer *DiagConsumer,
720 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
721 CaptureDiagsKind CaptureKind) {
722 std::vector<std::unique_ptr<ASTUnit>> ASTs;
723
724 ASTBuilderAction Action(ASTs, CaptureKind);
725
726 auto OverlayFileSystem =
727 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
728 A: std::move(BaseFS));
729 auto InMemoryFileSystem =
730 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
731 OverlayFileSystem->pushOverlay(FS: InMemoryFileSystem);
732 llvm::IntrusiveRefCntPtr<FileManager> Files =
733 llvm::makeIntrusiveRefCnt<FileManager>(A: FileSystemOptions(),
734 A&: OverlayFileSystem);
735
736 ToolInvocation Invocation(
737 getSyntaxOnlyToolArgs(ToolName, ExtraArgs: Adjuster(Args, FileName), FileName),
738 &Action, Files.get(), std::move(PCHContainerOps));
739 Invocation.setDiagnosticConsumer(DiagConsumer);
740
741 InMemoryFileSystem->addFile(Path: FileName, ModificationTime: 0,
742 Buffer: llvm::MemoryBuffer::getMemBufferCopy(InputData: Code));
743 for (auto &FilenameWithContent : VirtualMappedFiles) {
744 InMemoryFileSystem->addFile(
745 Path: FilenameWithContent.first, ModificationTime: 0,
746 Buffer: llvm::MemoryBuffer::getMemBuffer(InputData: FilenameWithContent.second));
747 }
748
749 if (!Invocation.run())
750 return nullptr;
751
752 assert(ASTs.size() == 1);
753 return std::move(ASTs[0]);
754}
755
756} // namespace tooling
757} // namespace clang
758