Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Tooling/Tooling.cpp
Line
Count
Source (jump to first uncovered line)
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/DiagnosticIDs.h"
17
#include "clang/Basic/DiagnosticOptions.h"
18
#include "clang/Basic/FileManager.h"
19
#include "clang/Basic/FileSystemOptions.h"
20
#include "clang/Basic/LLVM.h"
21
#include "clang/Driver/Compilation.h"
22
#include "clang/Driver/Driver.h"
23
#include "clang/Driver/Job.h"
24
#include "clang/Driver/Options.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/FrontendDiagnostic.h"
31
#include "clang/Frontend/FrontendOptions.h"
32
#include "clang/Frontend/TextDiagnosticPrinter.h"
33
#include "clang/Lex/HeaderSearchOptions.h"
34
#include "clang/Lex/PreprocessorOptions.h"
35
#include "clang/Tooling/ArgumentsAdjusters.h"
36
#include "clang/Tooling/CompilationDatabase.h"
37
#include "llvm/ADT/ArrayRef.h"
38
#include "llvm/ADT/IntrusiveRefCntPtr.h"
39
#include "llvm/ADT/SmallString.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/Casting.h"
46
#include "llvm/Support/Debug.h"
47
#include "llvm/Support/ErrorHandling.h"
48
#include "llvm/Support/FileSystem.h"
49
#include "llvm/Support/Host.h"
50
#include "llvm/Support/MemoryBuffer.h"
51
#include "llvm/Support/Path.h"
52
#include "llvm/Support/VirtualFileSystem.h"
53
#include "llvm/Support/raw_ostream.h"
54
#include <cassert>
55
#include <cstring>
56
#include <memory>
57
#include <string>
58
#include <system_error>
59
#include <utility>
60
#include <vector>
61
62
#define DEBUG_TYPE "clang-tooling"
63
64
using namespace clang;
65
using namespace tooling;
66
67
11.9k
ToolAction::~ToolAction() = default;
68
69
6.68k
FrontendActionFactory::~FrontendActionFactory() = default;
70
71
// FIXME: This file contains structural duplication with other parts of the
72
// code that sets up a compiler to run tools on it, and we should refactor
73
// it to be based on the same framework.
74
75
/// Builds a clang driver initialized for running clang tools.
76
static driver::Driver *
77
newDriver(DiagnosticsEngine *Diagnostics, const char *BinaryName,
78
8.97k
          IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
79
8.97k
  driver::Driver *CompilerDriver =
80
8.97k
      new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
81
8.97k
                         *Diagnostics, std::move(VFS));
82
8.97k
  CompilerDriver->setTitle("clang_based_tool");
83
8.97k
  return CompilerDriver;
84
8.97k
}
85
86
/// Retrieves the clang CC1 specific flags out of the compilation's jobs.
87
///
88
/// Returns nullptr on error.
89
static const llvm::opt::ArgStringList *getCC1Arguments(
90
8.97k
    DiagnosticsEngine *Diagnostics, driver::Compilation *Compilation) {
91
8.97k
  // We expect to get back exactly one Command job, if we didn't something
92
8.97k
  // failed. Extract that job from the Compilation.
93
8.97k
  const driver::JobList &Jobs = Compilation->getJobs();
94
8.97k
  const driver::ActionList &Actions = Compilation->getActions();
95
8.97k
  bool OffloadCompilation = false;
96
8.97k
  if (Jobs.size() > 1) {
97
3
    for (auto A : Actions){
98
3
      // On MacOSX real actions may end up being wrapped in BindArchAction
99
3
      if (isa<driver::BindArchAction>(A))
100
3
        A = *A->input_begin();
101
3
      if (isa<driver::OffloadAction>(A)) {
102
1
        // Offload compilation has 2 top-level actions, one (at the front) is
103
1
        // the original host compilation and the other is offload action
104
1
        // composed of at least one device compilation. For such case, general
105
1
        // tooling will consider host-compilation only. For tooling on device
106
1
        // compilation, device compilation only option, such as
107
1
        // `--cuda-device-only`, needs specifying.
108
1
        assert(Actions.size() > 1);
109
1
        assert(
110
1
            isa<driver::CompileJobAction>(Actions.front()) ||
111
1
            // On MacOSX real actions may end up being wrapped in
112
1
            // BindArchAction.
113
1
            (isa<driver::BindArchAction>(Actions.front()) &&
114
1
             isa<driver::CompileJobAction>(*Actions.front()->input_begin())));
115
1
        OffloadCompilation = true;
116
1
        break;
117
1
      }
118
8.97k
    }
119
2
  }
120
8.97k
  if (Jobs.size() == 0 || 
!isa<driver::Command>(*Jobs.begin())8.97k
||
121
8.97k
      
(8.97k
Jobs.size() > 18.97k
&&
!OffloadCompilation2
)) {
122
2
    SmallString<256> error_msg;
123
2
    llvm::raw_svector_ostream error_stream(error_msg);
124
2
    Jobs.Print(error_stream, "; ", true);
125
2
    Diagnostics->Report(diag::err_fe_expected_compiler_job)
126
2
        << error_stream.str();
127
2
    return nullptr;
128
2
  }
129
8.97k
130
8.97k
  // The one job we find should be to invoke clang again.
131
8.97k
  const auto &Cmd = cast<driver::Command>(*Jobs.begin());
132
8.97k
  if (StringRef(Cmd.getCreator().getName()) != "clang") {
133
0
    Diagnostics->Report(diag::err_fe_expected_clang_command);
134
0
    return nullptr;
135
0
  }
136
8.97k
137
8.97k
  return &Cmd.getArguments();
138
8.97k
}
139
140
namespace clang {
141
namespace tooling {
142
143
/// Returns a clang build invocation initialized from the CC1 flags.
144
CompilerInvocation *newInvocation(
145
8.97k
    DiagnosticsEngine *Diagnostics, const llvm::opt::ArgStringList &CC1Args) {
146
8.97k
  assert(!CC1Args.empty() && "Must at least contain the program name!");
147
8.97k
  CompilerInvocation *Invocation = new CompilerInvocation;
148
8.97k
  CompilerInvocation::CreateFromArgs(*Invocation, CC1Args, *Diagnostics);
149
8.97k
  Invocation->getFrontendOpts().DisableFree = false;
150
8.97k
  Invocation->getCodeGenOpts().DisableFree = false;
151
8.97k
  return Invocation;
152
8.97k
}
153
154
bool runToolOnCode(std::unique_ptr<FrontendAction> ToolAction,
155
                   const Twine &Code, const Twine &FileName,
156
104
                   std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
157
104
  return runToolOnCodeWithArgs(std::move(ToolAction), Code,
158
104
                               std::vector<std::string>(), FileName,
159
104
                               "clang-tool", std::move(PCHContainerOps));
160
104
}
161
162
} // namespace tooling
163
} // namespace clang
164
165
static std::vector<std::string>
166
getSyntaxOnlyToolArgs(const Twine &ToolName,
167
                      const std::vector<std::string> &ExtraArgs,
168
8.58k
                      StringRef FileName) {
169
8.58k
  std::vector<std::string> Args;
170
8.58k
  Args.push_back(ToolName.str());
171
8.58k
  Args.push_back("-fsyntax-only");
172
8.58k
  Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
173
8.58k
  Args.push_back(FileName.str());
174
8.58k
  return Args;
175
8.58k
}
176
177
namespace clang {
178
namespace tooling {
179
180
bool runToolOnCodeWithArgs(
181
    std::unique_ptr<FrontendAction> ToolAction, const Twine &Code,
182
    llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
183
    const std::vector<std::string> &Args, const Twine &FileName,
184
    const Twine &ToolName,
185
3.45k
    std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
186
3.45k
  SmallString<16> FileNameStorage;
187
3.45k
  StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
188
3.45k
189
3.45k
  llvm::IntrusiveRefCntPtr<FileManager> Files(
190
3.45k
      new FileManager(FileSystemOptions(), VFS));
191
3.45k
  ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();
192
3.45k
  ToolInvocation Invocation(
193
3.45k
      getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
194
3.45k
      std::move(ToolAction), Files.get(), std::move(PCHContainerOps));
195
3.45k
  return Invocation.run();
196
3.45k
}
197
198
bool runToolOnCodeWithArgs(
199
    std::unique_ptr<FrontendAction> ToolAction, const Twine &Code,
200
    const std::vector<std::string> &Args, const Twine &FileName,
201
    const Twine &ToolName,
202
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
203
3.45k
    const FileContentMappings &VirtualMappedFiles) {
204
3.45k
  llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
205
3.45k
      new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
206
3.45k
  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
207
3.45k
      new llvm::vfs::InMemoryFileSystem);
208
3.45k
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
209
3.45k
210
3.45k
  SmallString<1024> CodeStorage;
211
3.45k
  InMemoryFileSystem->addFile(FileName, 0,
212
3.45k
                              llvm::MemoryBuffer::getMemBuffer(
213
3.45k
                                  Code.toNullTerminatedStringRef(CodeStorage)));
214
3.45k
215
3.45k
  for (auto &FilenameWithContent : VirtualMappedFiles) {
216
1.07k
    InMemoryFileSystem->addFile(
217
1.07k
        FilenameWithContent.first, 0,
218
1.07k
        llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
219
1.07k
  }
220
3.45k
221
3.45k
  return runToolOnCodeWithArgs(std::move(ToolAction), Code, OverlayFileSystem,
222
3.45k
                               Args, FileName, ToolName);
223
3.45k
}
224
225
llvm::Expected<std::string> getAbsolutePath(llvm::vfs::FileSystem &FS,
226
409
                                            StringRef File) {
227
409
  StringRef RelativePath(File);
228
409
  // FIXME: Should '.\\' be accepted on Win32?
229
409
  if (RelativePath.startswith("./")) {
230
0
    RelativePath = RelativePath.substr(strlen("./"));
231
0
  }
232
409
233
409
  SmallString<1024> AbsolutePath = RelativePath;
234
409
  if (auto EC = FS.makeAbsolute(AbsolutePath))
235
0
    return llvm::errorCodeToError(EC);
236
409
  llvm::sys::path::native(AbsolutePath);
237
409
  return std::string(AbsolutePath.str());
238
409
}
239
240
22
std::string getAbsolutePath(StringRef File) {
241
22
  return llvm::cantFail(getAbsolutePath(*llvm::vfs::getRealFileSystem(), File));
242
22
}
243
244
void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
245
27
                                    StringRef InvokedAs) {
246
27
  if (!CommandLine.empty() && !InvokedAs.empty()) {
247
26
    bool AlreadyHasTarget = false;
248
26
    bool AlreadyHasMode = false;
249
26
    // Skip CommandLine[0].
250
100
    for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
251
74
         ++Token) {
252
74
      StringRef TokenRef(*Token);
253
74
      AlreadyHasTarget |=
254
74
          (TokenRef == "-target" || 
TokenRef.startswith("-target=")71
);
255
74
      AlreadyHasMode |= (TokenRef == "--driver-mode" ||
256
74
                         
TokenRef.startswith("--driver-mode=")73
);
257
74
    }
258
26
    auto TargetMode =
259
26
        driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
260
26
    if (!AlreadyHasMode && 
TargetMode.DriverMode24
) {
261
20
      CommandLine.insert(++CommandLine.begin(), TargetMode.DriverMode);
262
20
    }
263
26
    if (!AlreadyHasTarget && 
TargetMode.TargetIsValid22
) {
264
4
      CommandLine.insert(++CommandLine.begin(), {"-target",
265
4
                                                 TargetMode.TargetPrefix});
266
4
    }
267
26
  }
268
27
}
269
270
} // namespace tooling
271
} // namespace clang
272
273
namespace {
274
275
class SingleFrontendActionFactory : public FrontendActionFactory {
276
  std::unique_ptr<FrontendAction> Action;
277
278
public:
279
  SingleFrontendActionFactory(std::unique_ptr<FrontendAction> Action)
280
3.45k
      : Action(std::move(Action)) {}
281
282
3.45k
  std::unique_ptr<FrontendAction> create() override {
283
3.45k
    return std::move(Action);
284
3.45k
  }
285
};
286
287
} // namespace
288
289
ToolInvocation::ToolInvocation(
290
    std::vector<std::string> CommandLine, ToolAction *Action,
291
    FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
292
    : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
293
5.52k
      Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {}
294
295
ToolInvocation::ToolInvocation(
296
    std::vector<std::string> CommandLine,
297
    std::unique_ptr<FrontendAction> FAction, FileManager *Files,
298
    std::shared_ptr<PCHContainerOperations> PCHContainerOps)
299
    : CommandLine(std::move(CommandLine)),
300
      Action(new SingleFrontendActionFactory(std::move(FAction))),
301
      OwnsAction(true), Files(Files),
302
3.45k
      PCHContainerOps(std::move(PCHContainerOps)) {}
303
304
8.97k
ToolInvocation::~ToolInvocation() {
305
8.97k
  if (OwnsAction)
306
3.45k
    delete Action;
307
8.97k
}
308
309
0
void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
310
0
  SmallString<1024> PathStorage;
311
0
  llvm::sys::path::native(FilePath, PathStorage);
312
0
  MappedFileContents[PathStorage] = Content;
313
0
}
314
315
8.97k
bool ToolInvocation::run() {
316
8.97k
  std::vector<const char*> Argv;
317
8.97k
  for (const std::string &Str : CommandLine)
318
54.3k
    Argv.push_back(Str.c_str());
319
8.97k
  const char *const BinaryName = Argv[0];
320
8.97k
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
321
8.97k
  unsigned MissingArgIndex, MissingArgCount;
322
8.97k
  llvm::opt::InputArgList ParsedArgs = driver::getDriverOptTable().ParseArgs(
323
8.97k
      ArrayRef<const char *>(Argv).slice(1), MissingArgIndex, MissingArgCount);
324
8.97k
  ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
325
8.97k
  TextDiagnosticPrinter DiagnosticPrinter(
326
8.97k
      llvm::errs(), &*DiagOpts);
327
8.97k
  DiagnosticsEngine Diagnostics(
328
8.97k
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
329
8.97k
      DiagConsumer ? 
DiagConsumer68
:
&DiagnosticPrinter8.90k
, false);
330
8.97k
331
8.97k
  const std::unique_ptr<driver::Driver> Driver(
332
8.97k
      newDriver(&Diagnostics, BinaryName, &Files->getVirtualFileSystem()));
333
8.97k
  // The "input file not found" diagnostics from the driver are useful.
334
8.97k
  // The driver is only aware of the VFS working directory, but some clients
335
8.97k
  // change this at the FileManager level instead.
336
8.97k
  // In this case the checks have false positives, so skip them.
337
8.97k
  if (!Files->getFileSystemOpts().WorkingDir.empty())
338
24
    Driver->setCheckInputsExist(false);
339
8.97k
  const std::unique_ptr<driver::Compilation> Compilation(
340
8.97k
      Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
341
8.97k
  if (!Compilation)
342
0
    return false;
343
8.97k
  const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
344
8.97k
      &Diagnostics, Compilation.get());
345
8.97k
  if (!CC1Args)
346
2
    return false;
347
8.97k
  std::unique_ptr<CompilerInvocation> Invocation(
348
8.97k
      newInvocation(&Diagnostics, *CC1Args));
349
8.97k
  // FIXME: remove this when all users have migrated!
350
8.97k
  for (const auto &It : MappedFileContents) {
351
0
    // Inject the code as the given file name into the preprocessor options.
352
0
    std::unique_ptr<llvm::MemoryBuffer> Input =
353
0
        llvm::MemoryBuffer::getMemBuffer(It.getValue());
354
0
    Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
355
0
                                                      Input.release());
356
0
  }
357
8.97k
  return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
358
8.97k
                       std::move(PCHContainerOps));
359
8.97k
}
360
361
bool ToolInvocation::runInvocation(
362
    const char *BinaryName, driver::Compilation *Compilation,
363
    std::shared_ptr<CompilerInvocation> Invocation,
364
8.97k
    std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
365
8.97k
  // Show the invocation, with -v.
366
8.97k
  if (Invocation->getHeaderSearchOpts().Verbose) {
367
1
    llvm::errs() << "clang Invocation:\n";
368
1
    Compilation->getJobs().Print(llvm::errs(), "\n", true);
369
1
    llvm::errs() << "\n";
370
1
  }
371
8.97k
372
8.97k
  return Action->runInvocation(std::move(Invocation), Files,
373
8.97k
                               std::move(PCHContainerOps), DiagConsumer);
374
8.97k
}
375
376
bool FrontendActionFactory::runInvocation(
377
    std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
378
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
379
3.74k
    DiagnosticConsumer *DiagConsumer) {
380
3.74k
  // Create a compiler instance to handle the actual work.
381
3.74k
  CompilerInstance Compiler(std::move(PCHContainerOps));
382
3.74k
  Compiler.setInvocation(std::move(Invocation));
383
3.74k
  Compiler.setFileManager(Files);
384
3.74k
385
3.74k
  // The FrontendAction can have lifetime requirements for Compiler or its
386
3.74k
  // members, and we need to ensure it's deleted earlier than Compiler. So we
387
3.74k
  // pass it to an std::unique_ptr declared after the Compiler variable.
388
3.74k
  std::unique_ptr<FrontendAction> ScopedToolAction(create());
389
3.74k
390
3.74k
  // Create the compiler's actual diagnostics engine.
391
3.74k
  Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
392
3.74k
  if (!Compiler.hasDiagnostics())
393
0
    return false;
394
3.74k
395
3.74k
  Compiler.createSourceManager(*Files);
396
3.74k
397
3.74k
  const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
398
3.74k
399
3.74k
  Files->clearStatCache();
400
3.74k
  return Success;
401
3.74k
}
402
403
ClangTool::ClangTool(const CompilationDatabase &Compilations,
404
                     ArrayRef<std::string> SourcePaths,
405
                     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
406
                     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
407
                     IntrusiveRefCntPtr<FileManager> Files)
408
    : Compilations(Compilations), SourcePaths(SourcePaths),
409
      PCHContainerOps(std::move(PCHContainerOps)),
410
      OverlayFileSystem(new llvm::vfs::OverlayFileSystem(std::move(BaseFS))),
411
      InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem),
412
      Files(Files ? Files
413
322
                  : new FileManager(FileSystemOptions(), OverlayFileSystem)) {
414
322
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
415
322
  appendArgumentsAdjuster(getClangStripOutputAdjuster());
416
322
  appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
417
322
  appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
418
322
  if (Files)
419
60
    Files->setVirtualFileSystem(OverlayFileSystem);
420
322
}
421
422
321
ClangTool::~ClangTool() = default;
423
424
9.96k
void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
425
9.96k
  MappedFileContents.push_back(std::make_pair(FilePath, Content));
426
9.96k
}
427
428
1.29k
void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
429
1.29k
  ArgsAdjuster = combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
430
1.29k
}
431
432
114
void ClangTool::clearArgumentsAdjusters() {
433
114
  ArgsAdjuster = nullptr;
434
114
}
435
436
static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
437
387
                              void *MainAddr) {
438
387
  // Allow users to override the resource dir.
439
387
  for (StringRef Arg : Args)
440
2.23k
    if (Arg.startswith("-resource-dir"))
441
0
      return;
442
387
443
387
  // If there's no override in place add our resource dir.
444
387
  Args.push_back("-resource-dir=" +
445
387
                 CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
446
387
}
447
448
382
int ClangTool::run(ToolAction *Action) {
449
382
  // Exists solely for the purpose of lookup of the resource path.
450
382
  // This just needs to be some symbol in the binary.
451
382
  static int StaticSymbol;
452
382
453
382
  // First insert all absolute paths into the in-memory VFS. These are global
454
382
  // for all compile commands.
455
382
  if (SeenWorkingDirectories.insert("/").second)
456
319
    for (const auto &MappedFile : MappedFileContents)
457
9.69k
      if (llvm::sys::path::is_absolute(MappedFile.first))
458
11
        InMemoryFileSystem->addFile(
459
11
            MappedFile.first, 0,
460
11
            llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
461
382
462
382
  bool ProcessingFailed = false;
463
382
  bool FileSkipped = false;
464
382
  // Compute all absolute paths before we run any actions, as those will change
465
382
  // the working directory.
466
382
  std::vector<std::string> AbsolutePaths;
467
382
  AbsolutePaths.reserve(SourcePaths.size());
468
387
  for (const auto &SourcePath : SourcePaths) {
469
387
    auto AbsPath = getAbsolutePath(*OverlayFileSystem, SourcePath);
470
387
    if (!AbsPath) {
471
0
      llvm::errs() << "Skipping " << SourcePath
472
0
                   << ". Error while getting an absolute path: "
473
0
                   << llvm::toString(AbsPath.takeError()) << "\n";
474
0
      continue;
475
0
    }
476
387
    AbsolutePaths.push_back(std::move(*AbsPath));
477
387
  }
478
382
479
382
  // Remember the working directory in case we need to restore it.
480
382
  std::string InitialWorkingDir;
481
382
  if (RestoreCWD) {
482
318
    if (auto CWD = OverlayFileSystem->getCurrentWorkingDirectory()) {
483
318
      InitialWorkingDir = std::move(*CWD);
484
318
    } else {
485
0
      llvm::errs() << "Could not get working directory: "
486
0
                   << CWD.getError().message() << "\n";
487
0
    }
488
318
  }
489
382
490
386
  for (llvm::StringRef File : AbsolutePaths) {
491
386
    // Currently implementations of CompilationDatabase::getCompileCommands can
492
386
    // change the state of the file system (e.g.  prepare generated headers), so
493
386
    // this method needs to run right before we invoke the tool, as the next
494
386
    // file may require a different (incompatible) state of the file system.
495
386
    //
496
386
    // FIXME: Make the compilation database interface more explicit about the
497
386
    // requirements to the order of invocation of its members.
498
386
    std::vector<CompileCommand> CompileCommandsForFile =
499
386
        Compilations.getCompileCommands(File);
500
386
    if (CompileCommandsForFile.empty()) {
501
0
      llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
502
0
      FileSkipped = true;
503
0
      continue;
504
0
    }
505
388
    
for (CompileCommand &CompileCommand : CompileCommandsForFile)386
{
506
388
      // FIXME: chdir is thread hostile; on the other hand, creating the same
507
388
      // behavior as chdir is complex: chdir resolves the path once, thus
508
388
      // guaranteeing that all subsequent relative path operations work
509
388
      // on the same path the original chdir resulted in. This makes a
510
388
      // difference for example on network filesystems, where symlinks might be
511
388
      // switched during runtime of the tool. Fixing this depends on having a
512
388
      // file system abstraction that allows openat() style interactions.
513
388
      if (OverlayFileSystem->setCurrentWorkingDirectory(
514
388
              CompileCommand.Directory))
515
0
        llvm::report_fatal_error("Cannot chdir into \"" +
516
0
                                 Twine(CompileCommand.Directory) + "\"!");
517
388
518
388
      // Now fill the in-memory VFS with the relative file mappings so it will
519
388
      // have the correct relative paths. We never remove mappings but that
520
388
      // should be fine.
521
388
      if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
522
310
        for (const auto &MappedFile : MappedFileContents)
523
9.95k
          if (!llvm::sys::path::is_absolute(MappedFile.first))
524
9.90k
            InMemoryFileSystem->addFile(
525
9.90k
                MappedFile.first, 0,
526
9.90k
                llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
527
388
528
388
      std::vector<std::string> CommandLine = CompileCommand.CommandLine;
529
388
      if (ArgsAdjuster)
530
317
        CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
531
388
      assert(!CommandLine.empty());
532
388
533
388
      // Add the resource dir based on the binary of this tool. argv[0] in the
534
388
      // compilation database may refer to a different compiler and we want to
535
388
      // pick up the very same standard library that compiler is using. The
536
388
      // builtin headers in the resource dir need to match the exact clang
537
388
      // version the tool is using.
538
388
      // FIXME: On linux, GetMainExecutable is independent of the value of the
539
388
      // first argument, thus allowing ClangTool and runToolOnCode to just
540
388
      // pass in made-up names here. Make sure this works on other platforms.
541
388
      injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
542
388
543
388
      // FIXME: We need a callback mechanism for the tool writer to output a
544
388
      // customized message for each file.
545
388
      LLVM_DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
546
388
      ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
547
388
                                PCHContainerOps);
548
388
      Invocation.setDiagnosticConsumer(DiagConsumer);
549
388
550
388
      if (!Invocation.run()) {
551
23
        // FIXME: Diagnostics should be used instead.
552
23
        if (PrintErrorMessage)
553
20
          llvm::errs() << "Error while processing " << File << ".\n";
554
23
        ProcessingFailed = true;
555
23
      }
556
388
    }
557
386
  }
558
382
559
382
  if (!InitialWorkingDir.empty()) {
560
318
    if (auto EC =
561
0
            OverlayFileSystem->setCurrentWorkingDirectory(InitialWorkingDir))
562
0
      llvm::errs() << "Error when trying to restore working dir: "
563
0
                   << EC.message() << "\n";
564
318
  }
565
382
  return ProcessingFailed ? 
123
:
(FileSkipped 359
?
20
:
0359
);
566
382
}
567
568
namespace {
569
570
class ASTBuilderAction : public ToolAction {
571
  std::vector<std::unique_ptr<ASTUnit>> &ASTs;
572
573
public:
574
5.15k
  ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
575
576
  bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
577
                     FileManager *Files,
578
                     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
579
5.15k
                     DiagnosticConsumer *DiagConsumer) override {
580
5.15k
    std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
581
5.15k
        Invocation, std::move(PCHContainerOps),
582
5.15k
        CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
583
5.15k
                                            DiagConsumer,
584
5.15k
                                            /*ShouldOwnClient=*/false),
585
5.15k
        Files);
586
5.15k
    if (!AST)
587
0
      return false;
588
5.15k
589
5.15k
    ASTs.push_back(std::move(AST));
590
5.15k
    return true;
591
5.15k
  }
592
};
593
594
} // namespace
595
596
19
int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
597
19
  ASTBuilderAction Action(ASTs);
598
19
  return run(&Action);
599
19
}
600
601
65
void ClangTool::setRestoreWorkingDir(bool RestoreCWD) {
602
65
  this->RestoreCWD = RestoreCWD;
603
65
}
604
605
65
void ClangTool::setPrintErrorMessage(bool PrintErrorMessage) {
606
65
  this->PrintErrorMessage = PrintErrorMessage;
607
65
}
608
609
namespace clang {
610
namespace tooling {
611
612
std::unique_ptr<ASTUnit>
613
buildASTFromCode(StringRef Code, StringRef FileName,
614
132
                 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
615
132
  return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
616
132
                                  "clang-tool", std::move(PCHContainerOps));
617
132
}
618
619
std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
620
    StringRef Code, const std::vector<std::string> &Args, StringRef FileName,
621
    StringRef ToolName, std::shared_ptr<PCHContainerOperations> PCHContainerOps,
622
    ArgumentsAdjuster Adjuster, const FileContentMappings &VirtualMappedFiles,
623
5.13k
    DiagnosticConsumer *DiagConsumer) {
624
5.13k
  std::vector<std::unique_ptr<ASTUnit>> ASTs;
625
5.13k
  ASTBuilderAction Action(ASTs);
626
5.13k
  llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
627
5.13k
      new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
628
5.13k
  llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
629
5.13k
      new llvm::vfs::InMemoryFileSystem);
630
5.13k
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
631
5.13k
  llvm::IntrusiveRefCntPtr<FileManager> Files(
632
5.13k
      new FileManager(FileSystemOptions(), OverlayFileSystem));
633
5.13k
634
5.13k
  ToolInvocation Invocation(
635
5.13k
      getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileName), FileName),
636
5.13k
      &Action, Files.get(), std::move(PCHContainerOps));
637
5.13k
  Invocation.setDiagnosticConsumer(DiagConsumer);
638
5.13k
639
5.13k
  InMemoryFileSystem->addFile(FileName, 0,
640
5.13k
                              llvm::MemoryBuffer::getMemBufferCopy(Code));
641
5.13k
  for (auto &FilenameWithContent : VirtualMappedFiles) {
642
0
    InMemoryFileSystem->addFile(
643
0
        FilenameWithContent.first, 0,
644
0
        llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
645
0
  }
646
5.13k
647
5.13k
  if (!Invocation.run())
648
0
    return nullptr;
649
5.13k
650
5.13k
  assert(ASTs.size() == 1);
651
5.13k
  return std::move(ASTs[0]);
652
5.13k
}
653
654
} // namespace tooling
655
} // namespace clang