clang  10.0.0svn
JSONCompilationDatabase.cpp
Go to the documentation of this file.
1 //===- JSONCompilationDatabase.cpp ----------------------------------------===//
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 contains the implementation of the JSONCompilationDatabase.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "clang/Basic/LLVM.h"
17 #include "clang/Tooling/Tooling.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/Support/Allocator.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ErrorOr.h"
28 #include "llvm/Support/Host.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/StringSaver.h"
32 #include "llvm/Support/YAMLParser.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <cassert>
35 #include <memory>
36 #include <string>
37 #include <system_error>
38 #include <tuple>
39 #include <utility>
40 #include <vector>
41 
42 using namespace clang;
43 using namespace tooling;
44 
45 namespace {
46 
47 /// A parser for escaped strings of command line arguments.
48 ///
49 /// Assumes \-escaping for quoted arguments (see the documentation of
50 /// unescapeCommandLine(...)).
51 class CommandLineArgumentParser {
52  public:
53  CommandLineArgumentParser(StringRef CommandLine)
54  : Input(CommandLine), Position(Input.begin()-1) {}
55 
56  std::vector<std::string> parse() {
57  bool HasMoreInput = true;
58  while (HasMoreInput && nextNonWhitespace()) {
59  std::string Argument;
60  HasMoreInput = parseStringInto(Argument);
61  CommandLine.push_back(Argument);
62  }
63  return CommandLine;
64  }
65 
66  private:
67  // All private methods return true if there is more input available.
68 
69  bool parseStringInto(std::string &String) {
70  do {
71  if (*Position == '"') {
72  if (!parseDoubleQuotedStringInto(String)) return false;
73  } else if (*Position == '\'') {
74  if (!parseSingleQuotedStringInto(String)) return false;
75  } else {
76  if (!parseFreeStringInto(String)) return false;
77  }
78  } while (*Position != ' ');
79  return true;
80  }
81 
82  bool parseDoubleQuotedStringInto(std::string &String) {
83  if (!next()) return false;
84  while (*Position != '"') {
85  if (!skipEscapeCharacter()) return false;
86  String.push_back(*Position);
87  if (!next()) return false;
88  }
89  return next();
90  }
91 
92  bool parseSingleQuotedStringInto(std::string &String) {
93  if (!next()) return false;
94  while (*Position != '\'') {
95  String.push_back(*Position);
96  if (!next()) return false;
97  }
98  return next();
99  }
100 
101  bool parseFreeStringInto(std::string &String) {
102  do {
103  if (!skipEscapeCharacter()) return false;
104  String.push_back(*Position);
105  if (!next()) return false;
106  } while (*Position != ' ' && *Position != '"' && *Position != '\'');
107  return true;
108  }
109 
110  bool skipEscapeCharacter() {
111  if (*Position == '\\') {
112  return next();
113  }
114  return true;
115  }
116 
117  bool nextNonWhitespace() {
118  do {
119  if (!next()) return false;
120  } while (*Position == ' ');
121  return true;
122  }
123 
124  bool next() {
125  ++Position;
126  return Position != Input.end();
127  }
128 
129  const StringRef Input;
130  StringRef::iterator Position;
131  std::vector<std::string> CommandLine;
132 };
133 
134 std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax,
135  StringRef EscapedCommandLine) {
136  if (Syntax == JSONCommandLineSyntax::AutoDetect) {
138  llvm::Triple Triple(llvm::sys::getProcessTriple());
139  if (Triple.getOS() == llvm::Triple::OSType::Win32) {
140  // Assume Windows command line parsing on Win32 unless the triple
141  // explicitly tells us otherwise.
142  if (!Triple.hasEnvironment() ||
143  Triple.getEnvironment() == llvm::Triple::EnvironmentType::MSVC)
145  }
146  }
147 
148  if (Syntax == JSONCommandLineSyntax::Windows) {
149  llvm::BumpPtrAllocator Alloc;
150  llvm::StringSaver Saver(Alloc);
152  llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T);
153  std::vector<std::string> Result(T.begin(), T.end());
154  return Result;
155  }
156  assert(Syntax == JSONCommandLineSyntax::Gnu);
157  CommandLineArgumentParser parser(EscapedCommandLine);
158  return parser.parse();
159 }
160 
161 // This plugin locates a nearby compile_command.json file, and also infers
162 // compile commands for files not present in the database.
163 class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
164  std::unique_ptr<CompilationDatabase>
165  loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
166  SmallString<1024> JSONDatabasePath(Directory);
167  llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
169  JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
171  inferMissingCompileCommands(std::move(Base)))
172  : nullptr;
173  }
174 };
175 
176 } // namespace
177 
178 // Register the JSONCompilationDatabasePlugin with the
179 // CompilationDatabasePluginRegistry using this statically initialized variable.
180 static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
181 X("json-compilation-database", "Reads JSON formatted compilation databases");
182 
183 namespace clang {
184 namespace tooling {
185 
186 // This anchor is used to force the linker to link in the generated object file
187 // and thus register the JSONCompilationDatabasePlugin.
188 volatile int JSONAnchorSource = 0;
189 
190 } // namespace tooling
191 } // namespace clang
192 
193 std::unique_ptr<JSONCompilationDatabase>
195  std::string &ErrorMessage,
196  JSONCommandLineSyntax Syntax) {
197  // Don't mmap: if we're a long-lived process, the build system may overwrite.
198  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
199  llvm::MemoryBuffer::getFile(FilePath, /*FileSize=*/-1,
200  /*RequiresNullTerminator=*/true,
201  /*IsVolatile=*/true);
202  if (std::error_code Result = DatabaseBuffer.getError()) {
203  ErrorMessage = "Error while opening JSON database: " + Result.message();
204  return nullptr;
205  }
206  std::unique_ptr<JSONCompilationDatabase> Database(
207  new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
208  if (!Database->parse(ErrorMessage))
209  return nullptr;
210  return Database;
211 }
212 
213 std::unique_ptr<JSONCompilationDatabase>
215  std::string &ErrorMessage,
216  JSONCommandLineSyntax Syntax) {
217  std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
218  llvm::MemoryBuffer::getMemBuffer(DatabaseString));
219  std::unique_ptr<JSONCompilationDatabase> Database(
220  new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
221  if (!Database->parse(ErrorMessage))
222  return nullptr;
223  return Database;
224 }
225 
226 std::vector<CompileCommand>
228  SmallString<128> NativeFilePath;
229  llvm::sys::path::native(FilePath, NativeFilePath);
230 
231  std::string Error;
232  llvm::raw_string_ostream ES(Error);
233  StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);
234  if (Match.empty())
235  return {};
236  const auto CommandsRefI = IndexByFile.find(Match);
237  if (CommandsRefI == IndexByFile.end())
238  return {};
239  std::vector<CompileCommand> Commands;
240  getCommands(CommandsRefI->getValue(), Commands);
241  return Commands;
242 }
243 
244 std::vector<std::string>
246  std::vector<std::string> Result;
247  for (const auto &CommandRef : IndexByFile)
248  Result.push_back(CommandRef.first().str());
249  return Result;
250 }
251 
252 std::vector<CompileCommand>
254  std::vector<CompileCommand> Commands;
255  getCommands(AllCommands, Commands);
256  return Commands;
257 }
258 
259 static llvm::StringRef stripExecutableExtension(llvm::StringRef Name) {
260  Name.consume_back(".exe");
261  return Name;
262 }
263 
264 // There are compiler-wrappers (ccache, distcc, gomacc) that take the "real"
265 // compiler as an argument, e.g. distcc gcc -O3 foo.c.
266 // These end up in compile_commands.json when people set CC="distcc gcc".
267 // Clang's driver doesn't understand this, so we need to unwrap.
268 static bool unwrapCommand(std::vector<std::string> &Args) {
269  if (Args.size() < 2)
270  return false;
271  StringRef Wrapper =
272  stripExecutableExtension(llvm::sys::path::filename(Args.front()));
273  if (Wrapper == "distcc" || Wrapper == "gomacc" || Wrapper == "ccache") {
274  // Most of these wrappers support being invoked 3 ways:
275  // `distcc g++ file.c` This is the mode we're trying to match.
276  // We need to drop `distcc`.
277  // `distcc file.c` This acts like compiler is cc or similar.
278  // Clang's driver can handle this, no change needed.
279  // `g++ file.c` g++ is a symlink to distcc.
280  // We don't even notice this case, and all is well.
281  //
282  // We need to distinguish between the first and second case.
283  // The wrappers themselves don't take flags, so Args[1] is a compiler flag,
284  // an input file, or a compiler. Inputs have extensions, compilers don't.
285  bool HasCompiler =
286  (Args[1][0] != '-') &&
287  !llvm::sys::path::has_extension(stripExecutableExtension(Args[1]));
288  if (HasCompiler) {
289  Args.erase(Args.begin());
290  return true;
291  }
292  // If !HasCompiler, wrappers act like GCC. Fine: so do we.
293  }
294  return false;
295 }
296 
297 static std::vector<std::string>
299  const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
300  SmallString<1024> Storage;
301  std::vector<std::string> Arguments;
302  if (Nodes.size() == 1)
303  Arguments = unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
304  else
305  for (const auto *Node : Nodes)
306  Arguments.push_back(Node->getValue(Storage));
307  // There may be multiple wrappers: using distcc and ccache together is common.
308  while (unwrapCommand(Arguments))
309  ;
310  return Arguments;
311 }
312 
313 void JSONCompilationDatabase::getCommands(
314  ArrayRef<CompileCommandRef> CommandsRef,
315  std::vector<CompileCommand> &Commands) const {
316  for (const auto &CommandRef : CommandsRef) {
317  SmallString<8> DirectoryStorage;
318  SmallString<32> FilenameStorage;
319  SmallString<32> OutputStorage;
320  auto Output = std::get<3>(CommandRef);
321  Commands.emplace_back(
322  std::get<0>(CommandRef)->getValue(DirectoryStorage),
323  std::get<1>(CommandRef)->getValue(FilenameStorage),
324  nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
325  Output ? Output->getValue(OutputStorage) : "");
326  }
327 }
328 
329 bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
330  llvm::yaml::document_iterator I = YAMLStream.begin();
331  if (I == YAMLStream.end()) {
332  ErrorMessage = "Error while parsing YAML.";
333  return false;
334  }
335  llvm::yaml::Node *Root = I->getRoot();
336  if (!Root) {
337  ErrorMessage = "Error while parsing YAML.";
338  return false;
339  }
340  auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
341  if (!Array) {
342  ErrorMessage = "Expected array.";
343  return false;
344  }
345  for (auto &NextObject : *Array) {
346  auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
347  if (!Object) {
348  ErrorMessage = "Expected object.";
349  return false;
350  }
351  llvm::yaml::ScalarNode *Directory = nullptr;
353  llvm::yaml::ScalarNode *File = nullptr;
354  llvm::yaml::ScalarNode *Output = nullptr;
355  for (auto& NextKeyValue : *Object) {
356  auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
357  if (!KeyString) {
358  ErrorMessage = "Expected strings as key.";
359  return false;
360  }
361  SmallString<10> KeyStorage;
362  StringRef KeyValue = KeyString->getValue(KeyStorage);
363  llvm::yaml::Node *Value = NextKeyValue.getValue();
364  if (!Value) {
365  ErrorMessage = "Expected value.";
366  return false;
367  }
368  auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
369  auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
370  if (KeyValue == "arguments" && !SequenceString) {
371  ErrorMessage = "Expected sequence as value.";
372  return false;
373  } else if (KeyValue != "arguments" && !ValueString) {
374  ErrorMessage = "Expected string as value.";
375  return false;
376  }
377  if (KeyValue == "directory") {
378  Directory = ValueString;
379  } else if (KeyValue == "arguments") {
380  Command = std::vector<llvm::yaml::ScalarNode *>();
381  for (auto &Argument : *SequenceString) {
382  auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
383  if (!Scalar) {
384  ErrorMessage = "Only strings are allowed in 'arguments'.";
385  return false;
386  }
387  Command->push_back(Scalar);
388  }
389  } else if (KeyValue == "command") {
390  if (!Command)
391  Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
392  } else if (KeyValue == "file") {
393  File = ValueString;
394  } else if (KeyValue == "output") {
395  Output = ValueString;
396  } else {
397  ErrorMessage = ("Unknown key: \"" +
398  KeyString->getRawValue() + "\"").str();
399  return false;
400  }
401  }
402  if (!File) {
403  ErrorMessage = "Missing key: \"file\".";
404  return false;
405  }
406  if (!Command) {
407  ErrorMessage = "Missing key: \"command\" or \"arguments\".";
408  return false;
409  }
410  if (!Directory) {
411  ErrorMessage = "Missing key: \"directory\".";
412  return false;
413  }
414  SmallString<8> FileStorage;
415  StringRef FileName = File->getValue(FileStorage);
416  SmallString<128> NativeFilePath;
417  if (llvm::sys::path::is_relative(FileName)) {
418  SmallString<8> DirectoryStorage;
419  SmallString<128> AbsolutePath(
420  Directory->getValue(DirectoryStorage));
421  llvm::sys::path::append(AbsolutePath, FileName);
422  llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/ true);
423  llvm::sys::path::native(AbsolutePath, NativeFilePath);
424  } else {
425  llvm::sys::path::native(FileName, NativeFilePath);
426  }
427  auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
428  IndexByFile[NativeFilePath].push_back(Cmd);
429  AllCommands.push_back(Cmd);
430  MatchTrie.insert(NativeFilePath);
431  }
432  return true;
433 }
static std::unique_ptr< JSONCompilationDatabase > loadFromFile(StringRef FilePath, std::string &ErrorMessage, JSONCommandLineSyntax Syntax)
Loads a JSON compilation database from the specified file.
Interface for compilation database plugins.
std::vector< std::string > getAllFiles() const override
Returns the list of all files available in the compilation database.
BoundNodesTreeBuilder Nodes
static llvm::StringRef stripExecutableExtension(llvm::StringRef Name)
std::unique_ptr< CompilationDatabase > inferTargetAndDriverMode(std::unique_ptr< CompilationDatabase > Base)
Returns a wrapped CompilationDatabase that will add -target and -mode flags to commandline when they ...
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
CompileCommand Cmd
llvm::Error Error
static std::unique_ptr< JSONCompilationDatabase > loadFromBuffer(StringRef DatabaseString, std::string &ErrorMessage, JSONCommandLineSyntax Syntax)
Loads a JSON compilation database from a data buffer.
static SVal getValue(SVal val, SValBuilder &svalBuilder)
std::vector< CompileCommand > getCompileCommands(StringRef FilePath) const override
Returns all compile commands in which the specified file was compiled.
static bool unwrapCommand(std::vector< std::string > &Args)
std::unique_ptr< CompilationDatabase > inferMissingCompileCommands(std::unique_ptr< CompilationDatabase >)
Returns a wrapped CompilationDatabase that defers to the provided one, but getCompileCommands() will ...
ast_type_traits::DynTypedNode Node
Dataflow Directional Tag Classes.
std::vector< CompileCommand > getAllCompileCommands() const override
Returns all compile commands for all the files in the compilation database.
static ToolExecutorPluginRegistry::Add< AllTUsToolExecutorPlugin > X("all-TUs", "Runs FrontendActions on all TUs in the compilation database. " "Tool results are stored in memory.")
JSONCommandLineSyntax
A JSON based compilation database.
static std::vector< std::string > nodeToCommandLine(JSONCommandLineSyntax Syntax, const std::vector< llvm::yaml::ScalarNode *> &Nodes)