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