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 std::unique_ptr<JSONCompilationDatabase> Database(
201 new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
202 if (!Database->parse(ErrorMessage))
203 return nullptr;
204 return Database;
205}
206
207std::unique_ptr<JSONCompilationDatabase>
208JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
209 std::string &ErrorMessage,
210 JSONCommandLineSyntax Syntax) {
211 std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
212 llvm::MemoryBuffer::getMemBufferCopy(InputData: DatabaseString));
213 std::unique_ptr<JSONCompilationDatabase> Database(
214 new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
215 if (!Database->parse(ErrorMessage))
216 return nullptr;
217 return Database;
218}
219
220std::vector<CompileCommand>
221JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
222 SmallString<128> NativeFilePath;
223 llvm::sys::path::native(path: FilePath, result&: NativeFilePath);
224
225 std::string Error;
226 llvm::raw_string_ostream ES(Error);
227 StringRef Match = MatchTrie.findEquivalent(FileName: NativeFilePath, Error&: ES);
228 if (Match.empty())
229 return {};
230 const auto CommandsRefI = IndexByFile.find(Key: Match);
231 if (CommandsRefI == IndexByFile.end())
232 return {};
233 std::vector<CompileCommand> Commands;
234 getCommands(CommandsRef: CommandsRefI->getValue(), Commands);
235 return Commands;
236}
237
238std::vector<std::string>
239JSONCompilationDatabase::getAllFiles() const {
240 std::vector<std::string> Result;
241 for (const auto &CommandRef : IndexByFile)
242 Result.push_back(x: CommandRef.first().str());
243 return Result;
244}
245
246std::vector<CompileCommand>
247JSONCompilationDatabase::getAllCompileCommands() const {
248 std::vector<CompileCommand> Commands;
249 getCommands(CommandsRef: AllCommands, Commands);
250 return Commands;
251}
252
253static llvm::StringRef stripExecutableExtension(llvm::StringRef Name) {
254 Name.consume_back(Suffix: ".exe");
255 return Name;
256}
257
258// There are compiler-wrappers (ccache, distcc) that take the "real"
259// compiler as an argument, e.g. distcc gcc -O3 foo.c.
260// These end up in compile_commands.json when people set CC="distcc gcc".
261// Clang's driver doesn't understand this, so we need to unwrap.
262static bool unwrapCommand(std::vector<std::string> &Args) {
263 if (Args.size() < 2)
264 return false;
265 StringRef Wrapper =
266 stripExecutableExtension(Name: llvm::sys::path::filename(path: Args.front()));
267 if (Wrapper == "distcc" || Wrapper == "ccache" || Wrapper == "sccache") {
268 // Most of these wrappers support being invoked 3 ways:
269 // `distcc g++ file.c` This is the mode we're trying to match.
270 // We need to drop `distcc`.
271 // `distcc file.c` This acts like compiler is cc or similar.
272 // Clang's driver can handle this, no change needed.
273 // `g++ file.c` g++ is a symlink to distcc.
274 // We don't even notice this case, and all is well.
275 //
276 // We need to distinguish between the first and second case.
277 // The wrappers themselves don't take flags, so Args[1] is a compiler flag,
278 // an input file, or a compiler. Inputs have extensions, compilers don't.
279 bool HasCompiler =
280 (Args[1][0] != '-') &&
281 !llvm::sys::path::has_extension(path: stripExecutableExtension(Name: Args[1]));
282 if (HasCompiler) {
283 Args.erase(position: Args.begin());
284 return true;
285 }
286 // If !HasCompiler, wrappers act like GCC. Fine: so do we.
287 }
288 return false;
289}
290
291static std::vector<std::string>
292nodeToCommandLine(JSONCommandLineSyntax Syntax,
293 const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
294 SmallString<1024> Storage;
295 std::vector<std::string> Arguments;
296 if (Nodes.size() == 1)
297 Arguments = unescapeCommandLine(Syntax, EscapedCommandLine: Nodes[0]->getValue(Storage));
298 else
299 for (const auto *Node : Nodes)
300 Arguments.push_back(x: std::string(Node->getValue(Storage)));
301 // There may be multiple wrappers: using distcc and ccache together is common.
302 while (unwrapCommand(Args&: Arguments))
303 ;
304 return Arguments;
305}
306
307void JSONCompilationDatabase::getCommands(
308 ArrayRef<CompileCommandRef> CommandsRef,
309 std::vector<CompileCommand> &Commands) const {
310 for (const auto &CommandRef : CommandsRef) {
311 SmallString<8> DirectoryStorage;
312 SmallString<32> FilenameStorage;
313 SmallString<32> OutputStorage;
314 auto Output = std::get<3>(t: CommandRef);
315 Commands.emplace_back(
316 args: std::get<0>(t: CommandRef)->getValue(Storage&: DirectoryStorage),
317 args: std::get<1>(t: CommandRef)->getValue(Storage&: FilenameStorage),
318 args: nodeToCommandLine(Syntax, Nodes: std::get<2>(t: CommandRef)),
319 args: Output ? Output->getValue(Storage&: OutputStorage) : "");
320 }
321}
322
323bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
324 llvm::yaml::document_iterator I = YAMLStream.begin();
325 if (I == YAMLStream.end()) {
326 ErrorMessage = "Error while parsing YAML.";
327 return false;
328 }
329 llvm::yaml::Node *Root = I->getRoot();
330 if (!Root) {
331 ErrorMessage = "Error while parsing YAML.";
332 return false;
333 }
334 auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Val: Root);
335 if (!Array) {
336 ErrorMessage = "Expected array.";
337 return false;
338 }
339 for (auto &NextObject : *Array) {
340 auto *Object = dyn_cast<llvm::yaml::MappingNode>(Val: &NextObject);
341 if (!Object) {
342 ErrorMessage = "Expected object.";
343 return false;
344 }
345 llvm::yaml::ScalarNode *Directory = nullptr;
346 std::optional<std::vector<llvm::yaml::ScalarNode *>> Command;
347 llvm::yaml::ScalarNode *File = nullptr;
348 llvm::yaml::ScalarNode *Output = nullptr;
349 for (auto& NextKeyValue : *Object) {
350 auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(Val: NextKeyValue.getKey());
351 if (!KeyString) {
352 ErrorMessage = "Expected strings as key.";
353 return false;
354 }
355 SmallString<10> KeyStorage;
356 StringRef KeyValue = KeyString->getValue(Storage&: KeyStorage);
357 llvm::yaml::Node *Value = NextKeyValue.getValue();
358 if (!Value) {
359 ErrorMessage = "Expected value.";
360 return false;
361 }
362 auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Val: Value);
363 auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Val: Value);
364 if (KeyValue == "arguments") {
365 if (!SequenceString) {
366 ErrorMessage = "Expected sequence as value.";
367 return false;
368 }
369 Command = std::vector<llvm::yaml::ScalarNode *>();
370 for (auto &Argument : *SequenceString) {
371 auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(Val: &Argument);
372 if (!Scalar) {
373 ErrorMessage = "Only strings are allowed in 'arguments'.";
374 return false;
375 }
376 Command->push_back(x: Scalar);
377 }
378 } else {
379 if (!ValueString) {
380 ErrorMessage = "Expected string as value.";
381 return false;
382 }
383 if (KeyValue == "directory") {
384 Directory = ValueString;
385 } else if (KeyValue == "command") {
386 if (!Command)
387 Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
388 } else if (KeyValue == "file") {
389 File = ValueString;
390 } else if (KeyValue == "output") {
391 Output = ValueString;
392 } else {
393 ErrorMessage =
394 ("Unknown key: \"" + KeyString->getRawValue() + "\"").str();
395 return false;
396 }
397 }
398 }
399 if (!File) {
400 ErrorMessage = "Missing key: \"file\".";
401 return false;
402 }
403 if (!Command) {
404 ErrorMessage = "Missing key: \"command\" or \"arguments\".";
405 return false;
406 }
407 if (!Directory) {
408 ErrorMessage = "Missing key: \"directory\".";
409 return false;
410 }
411 SmallString<8> FileStorage;
412 StringRef FileName = File->getValue(Storage&: FileStorage);
413 SmallString<128> NativeFilePath;
414 if (llvm::sys::path::is_relative(path: FileName)) {
415 SmallString<8> DirectoryStorage;
416 SmallString<128> AbsolutePath(Directory->getValue(Storage&: DirectoryStorage));
417 llvm::sys::path::append(path&: AbsolutePath, a: FileName);
418 llvm::sys::path::native(path: AbsolutePath, result&: NativeFilePath);
419 } else {
420 llvm::sys::path::native(path: FileName, result&: NativeFilePath);
421 }
422 llvm::sys::path::remove_dots(path&: NativeFilePath, /*remove_dot_dot=*/true);
423 auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
424 IndexByFile[NativeFilePath].push_back(x: Cmd);
425 AllCommands.push_back(x: Cmd);
426 MatchTrie.insert(NewPath: NativeFilePath);
427 }
428 return true;
429}
430

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang/lib/Tooling/JSONCompilationDatabase.cpp