xref: /llvm-project/clang/lib/Tooling/JSONCompilationDatabase.cpp (revision a1580d7b59b65b17f2ce7fdb95f46379e7df4089)
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 
13 #include "clang/Tooling/JSONCompilationDatabase.h"
14 #include "clang/Basic/LLVM.h"
15 #include "clang/Tooling/CompilationDatabase.h"
16 #include "clang/Tooling/CompilationDatabasePluginRegistry.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/VirtualFileSystem.h"
33 #include "llvm/Support/YAMLParser.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <cassert>
36 #include <memory>
37 #include <optional>
38 #include <string>
39 #include <system_error>
40 #include <tuple>
41 #include <utility>
42 #include <vector>
43 
44 using namespace clang;
45 using namespace tooling;
46 
47 namespace {
48 
49 /// A parser for escaped strings of command line arguments.
50 ///
51 /// Assumes \-escaping for quoted arguments (see the documentation of
52 /// unescapeCommandLine(...)).
53 class CommandLineArgumentParser {
54  public:
55   CommandLineArgumentParser(StringRef CommandLine)
56       : Input(CommandLine), Position(Input.begin()-1) {}
57 
58   std::vector<std::string> parse() {
59     bool HasMoreInput = true;
60     while (HasMoreInput && nextNonWhitespace()) {
61       std::string Argument;
62       HasMoreInput = parseStringInto(Argument);
63       CommandLine.push_back(Argument);
64     }
65     return CommandLine;
66   }
67 
68  private:
69   // All private methods return true if there is more input available.
70 
71   bool parseStringInto(std::string &String) {
72     do {
73       if (*Position == '"') {
74         if (!parseDoubleQuotedStringInto(String)) return false;
75       } else if (*Position == '\'') {
76         if (!parseSingleQuotedStringInto(String)) return false;
77       } else {
78         if (!parseFreeStringInto(String)) return false;
79       }
80     } while (*Position != ' ');
81     return true;
82   }
83 
84   bool parseDoubleQuotedStringInto(std::string &String) {
85     if (!next()) return false;
86     while (*Position != '"') {
87       if (!skipEscapeCharacter()) return false;
88       String.push_back(*Position);
89       if (!next()) return false;
90     }
91     return next();
92   }
93 
94   bool parseSingleQuotedStringInto(std::string &String) {
95     if (!next()) return false;
96     while (*Position != '\'') {
97       String.push_back(*Position);
98       if (!next()) return false;
99     }
100     return next();
101   }
102 
103   bool parseFreeStringInto(std::string &String) {
104     do {
105       if (!skipEscapeCharacter()) return false;
106       String.push_back(*Position);
107       if (!next()) return false;
108     } while (*Position != ' ' && *Position != '"' && *Position != '\'');
109     return true;
110   }
111 
112   bool skipEscapeCharacter() {
113     if (*Position == '\\') {
114       return next();
115     }
116     return true;
117   }
118 
119   bool nextNonWhitespace() {
120     do {
121       if (!next()) return false;
122     } while (*Position == ' ');
123     return true;
124   }
125 
126   bool next() {
127     ++Position;
128     return Position != Input.end();
129   }
130 
131   const StringRef Input;
132   StringRef::iterator Position;
133   std::vector<std::string> CommandLine;
134 };
135 
136 std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax,
137                                              StringRef EscapedCommandLine) {
138   if (Syntax == JSONCommandLineSyntax::AutoDetect) {
139 #ifdef _WIN32
140     // Assume Windows command line parsing on Win32
141     Syntax = JSONCommandLineSyntax::Windows;
142 #else
143     Syntax = JSONCommandLineSyntax::Gnu;
144 #endif
145   }
146 
147   if (Syntax == JSONCommandLineSyntax::Windows) {
148     llvm::BumpPtrAllocator Alloc;
149     llvm::StringSaver Saver(Alloc);
150     llvm::SmallVector<const char *, 64> T;
151     llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T);
152     std::vector<std::string> Result(T.begin(), T.end());
153     return Result;
154   }
155   assert(Syntax == JSONCommandLineSyntax::Gnu);
156   CommandLineArgumentParser parser(EscapedCommandLine);
157   return parser.parse();
158 }
159 
160 // This plugin locates a nearby compile_command.json file, and also infers
161 // compile commands for files not present in the database.
162 class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
163   std::unique_ptr<CompilationDatabase>
164   loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
165     SmallString<1024> JSONDatabasePath(Directory);
166     llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
167     auto Base = JSONCompilationDatabase::loadFromFile(
168         JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
169     return Base ? inferTargetAndDriverMode(
170                       inferMissingCompileCommands(expandResponseFiles(
171                           std::move(Base), llvm::vfs::getRealFileSystem())))
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>
194 JSONCompilationDatabase::loadFromFile(StringRef FilePath,
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, /*IsText=*/false,
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>
214 JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
215                                         std::string &ErrorMessage,
216                                         JSONCommandLineSyntax Syntax) {
217   std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
218       llvm::MemoryBuffer::getMemBufferCopy(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>
227 JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
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>
245 JSONCompilationDatabase::getAllFiles() const {
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>
253 JSONCompilationDatabase::getAllCompileCommands() const {
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       Wrapper == "sccache") {
275     // Most of these wrappers support being invoked 3 ways:
276     // `distcc g++ file.c` This is the mode we're trying to match.
277     //                     We need to drop `distcc`.
278     // `distcc file.c`     This acts like compiler is cc or similar.
279     //                     Clang's driver can handle this, no change needed.
280     // `g++ file.c`        g++ is a symlink to distcc.
281     //                     We don't even notice this case, and all is well.
282     //
283     // We need to distinguish between the first and second case.
284     // The wrappers themselves don't take flags, so Args[1] is a compiler flag,
285     // an input file, or a compiler. Inputs have extensions, compilers don't.
286     bool HasCompiler =
287         (Args[1][0] != '-') &&
288         !llvm::sys::path::has_extension(stripExecutableExtension(Args[1]));
289     if (HasCompiler) {
290       Args.erase(Args.begin());
291       return true;
292     }
293     // If !HasCompiler, wrappers act like GCC. Fine: so do we.
294   }
295   return false;
296 }
297 
298 static std::vector<std::string>
299 nodeToCommandLine(JSONCommandLineSyntax Syntax,
300                   const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
301   SmallString<1024> Storage;
302   std::vector<std::string> Arguments;
303   if (Nodes.size() == 1)
304     Arguments = unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
305   else
306     for (const auto *Node : Nodes)
307       Arguments.push_back(std::string(Node->getValue(Storage)));
308   // There may be multiple wrappers: using distcc and ccache together is common.
309   while (unwrapCommand(Arguments))
310     ;
311   return Arguments;
312 }
313 
314 void JSONCompilationDatabase::getCommands(
315     ArrayRef<CompileCommandRef> CommandsRef,
316     std::vector<CompileCommand> &Commands) const {
317   for (const auto &CommandRef : CommandsRef) {
318     SmallString<8> DirectoryStorage;
319     SmallString<32> FilenameStorage;
320     SmallString<32> OutputStorage;
321     auto Output = std::get<3>(CommandRef);
322     Commands.emplace_back(
323         std::get<0>(CommandRef)->getValue(DirectoryStorage),
324         std::get<1>(CommandRef)->getValue(FilenameStorage),
325         nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
326         Output ? Output->getValue(OutputStorage) : "");
327   }
328 }
329 
330 bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
331   llvm::yaml::document_iterator I = YAMLStream.begin();
332   if (I == YAMLStream.end()) {
333     ErrorMessage = "Error while parsing YAML.";
334     return false;
335   }
336   llvm::yaml::Node *Root = I->getRoot();
337   if (!Root) {
338     ErrorMessage = "Error while parsing YAML.";
339     return false;
340   }
341   auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
342   if (!Array) {
343     ErrorMessage = "Expected array.";
344     return false;
345   }
346   for (auto &NextObject : *Array) {
347     auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
348     if (!Object) {
349       ErrorMessage = "Expected object.";
350       return false;
351     }
352     llvm::yaml::ScalarNode *Directory = nullptr;
353     llvm::Optional<std::vector<llvm::yaml::ScalarNode *>> Command;
354     llvm::yaml::ScalarNode *File = nullptr;
355     llvm::yaml::ScalarNode *Output = nullptr;
356     for (auto& NextKeyValue : *Object) {
357       auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
358       if (!KeyString) {
359         ErrorMessage = "Expected strings as key.";
360         return false;
361       }
362       SmallString<10> KeyStorage;
363       StringRef KeyValue = KeyString->getValue(KeyStorage);
364       llvm::yaml::Node *Value = NextKeyValue.getValue();
365       if (!Value) {
366         ErrorMessage = "Expected value.";
367         return false;
368       }
369       auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
370       auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
371       if (KeyValue == "arguments") {
372         if (!SequenceString) {
373           ErrorMessage = "Expected sequence as value.";
374           return false;
375         }
376         Command = std::vector<llvm::yaml::ScalarNode *>();
377         for (auto &Argument : *SequenceString) {
378           auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
379           if (!Scalar) {
380             ErrorMessage = "Only strings are allowed in 'arguments'.";
381             return false;
382           }
383           Command->push_back(Scalar);
384         }
385       } else {
386         if (!ValueString) {
387           ErrorMessage = "Expected string as value.";
388           return false;
389         }
390         if (KeyValue == "directory") {
391           Directory = ValueString;
392         } else if (KeyValue == "command") {
393           if (!Command)
394             Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
395         } else if (KeyValue == "file") {
396           File = ValueString;
397         } else if (KeyValue == "output") {
398           Output = ValueString;
399         } else {
400           ErrorMessage =
401               ("Unknown key: \"" + KeyString->getRawValue() + "\"").str();
402           return false;
403         }
404       }
405     }
406     if (!File) {
407       ErrorMessage = "Missing key: \"file\".";
408       return false;
409     }
410     if (!Command) {
411       ErrorMessage = "Missing key: \"command\" or \"arguments\".";
412       return false;
413     }
414     if (!Directory) {
415       ErrorMessage = "Missing key: \"directory\".";
416       return false;
417     }
418     SmallString<8> FileStorage;
419     StringRef FileName = File->getValue(FileStorage);
420     SmallString<128> NativeFilePath;
421     if (llvm::sys::path::is_relative(FileName)) {
422       SmallString<8> DirectoryStorage;
423       SmallString<128> AbsolutePath(Directory->getValue(DirectoryStorage));
424       llvm::sys::path::append(AbsolutePath, FileName);
425       llvm::sys::path::native(AbsolutePath, NativeFilePath);
426     } else {
427       llvm::sys::path::native(FileName, NativeFilePath);
428     }
429     llvm::sys::path::remove_dots(NativeFilePath, /*remove_dot_dot=*/true);
430     auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
431     IndexByFile[NativeFilePath].push_back(Cmd);
432     AllCommands.push_back(Cmd);
433     MatchTrie.insert(NativeFilePath);
434   }
435   return true;
436 }
437