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 "llvm/ADT/Optional.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/ADT/Triple.h" 22 #include "llvm/Support/Allocator.h" 23 #include "llvm/Support/Casting.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Support/ErrorOr.h" 26 #include "llvm/Support/Host.h" 27 #include "llvm/Support/MemoryBuffer.h" 28 #include "llvm/Support/Path.h" 29 #include "llvm/Support/StringSaver.h" 30 #include "llvm/Support/YAMLParser.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <cassert> 33 #include <memory> 34 #include <string> 35 #include <system_error> 36 #include <tuple> 37 #include <utility> 38 #include <vector> 39 40 using namespace clang; 41 using namespace tooling; 42 43 namespace { 44 45 /// A parser for escaped strings of command line arguments. 46 /// 47 /// Assumes \-escaping for quoted arguments (see the documentation of 48 /// unescapeCommandLine(...)). 49 class CommandLineArgumentParser { 50 public: 51 CommandLineArgumentParser(StringRef CommandLine) 52 : Input(CommandLine), Position(Input.begin()-1) {} 53 54 std::vector<std::string> parse() { 55 bool HasMoreInput = true; 56 while (HasMoreInput && nextNonWhitespace()) { 57 std::string Argument; 58 HasMoreInput = parseStringInto(Argument); 59 CommandLine.push_back(Argument); 60 } 61 return CommandLine; 62 } 63 64 private: 65 // All private methods return true if there is more input available. 66 67 bool parseStringInto(std::string &String) { 68 do { 69 if (*Position == '"') { 70 if (!parseDoubleQuotedStringInto(String)) return false; 71 } else if (*Position == '\'') { 72 if (!parseSingleQuotedStringInto(String)) return false; 73 } else { 74 if (!parseFreeStringInto(String)) return false; 75 } 76 } while (*Position != ' '); 77 return true; 78 } 79 80 bool parseDoubleQuotedStringInto(std::string &String) { 81 if (!next()) return false; 82 while (*Position != '"') { 83 if (!skipEscapeCharacter()) return false; 84 String.push_back(*Position); 85 if (!next()) return false; 86 } 87 return next(); 88 } 89 90 bool parseSingleQuotedStringInto(std::string &String) { 91 if (!next()) return false; 92 while (*Position != '\'') { 93 String.push_back(*Position); 94 if (!next()) return false; 95 } 96 return next(); 97 } 98 99 bool parseFreeStringInto(std::string &String) { 100 do { 101 if (!skipEscapeCharacter()) return false; 102 String.push_back(*Position); 103 if (!next()) return false; 104 } while (*Position != ' ' && *Position != '"' && *Position != '\''); 105 return true; 106 } 107 108 bool skipEscapeCharacter() { 109 if (*Position == '\\') { 110 return next(); 111 } 112 return true; 113 } 114 115 bool nextNonWhitespace() { 116 do { 117 if (!next()) return false; 118 } while (*Position == ' '); 119 return true; 120 } 121 122 bool next() { 123 ++Position; 124 return Position != Input.end(); 125 } 126 127 const StringRef Input; 128 StringRef::iterator Position; 129 std::vector<std::string> CommandLine; 130 }; 131 132 std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax, 133 StringRef EscapedCommandLine) { 134 if (Syntax == JSONCommandLineSyntax::AutoDetect) { 135 Syntax = JSONCommandLineSyntax::Gnu; 136 llvm::Triple Triple(llvm::sys::getProcessTriple()); 137 if (Triple.getOS() == llvm::Triple::OSType::Win32) { 138 // Assume Windows command line parsing on Win32 unless the triple 139 // explicitly tells us otherwise. 140 if (!Triple.hasEnvironment() || 141 Triple.getEnvironment() == llvm::Triple::EnvironmentType::MSVC) 142 Syntax = JSONCommandLineSyntax::Windows; 143 } 144 } 145 146 if (Syntax == JSONCommandLineSyntax::Windows) { 147 llvm::BumpPtrAllocator Alloc; 148 llvm::StringSaver Saver(Alloc); 149 llvm::SmallVector<const char *, 64> T; 150 llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T); 151 std::vector<std::string> Result(T.begin(), T.end()); 152 return Result; 153 } 154 assert(Syntax == JSONCommandLineSyntax::Gnu); 155 CommandLineArgumentParser parser(EscapedCommandLine); 156 return parser.parse(); 157 } 158 159 // This plugin locates a nearby compile_command.json file, and also infers 160 // compile commands for files not present in the database. 161 class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin { 162 std::unique_ptr<CompilationDatabase> 163 loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override { 164 SmallString<1024> JSONDatabasePath(Directory); 165 llvm::sys::path::append(JSONDatabasePath, "compile_commands.json"); 166 auto Base = JSONCompilationDatabase::loadFromFile( 167 JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect); 168 return Base ? inferMissingCompileCommands(std::move(Base)) : nullptr; 169 } 170 }; 171 172 } // namespace 173 174 // Register the JSONCompilationDatabasePlugin with the 175 // CompilationDatabasePluginRegistry using this statically initialized variable. 176 static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin> 177 X("json-compilation-database", "Reads JSON formatted compilation databases"); 178 179 namespace clang { 180 namespace tooling { 181 182 // This anchor is used to force the linker to link in the generated object file 183 // and thus register the JSONCompilationDatabasePlugin. 184 volatile int JSONAnchorSource = 0; 185 186 } // namespace tooling 187 } // namespace clang 188 189 std::unique_ptr<JSONCompilationDatabase> 190 JSONCompilationDatabase::loadFromFile(StringRef FilePath, 191 std::string &ErrorMessage, 192 JSONCommandLineSyntax Syntax) { 193 // Don't mmap: if we're a long-lived process, the build system may overwrite. 194 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer = 195 llvm::MemoryBuffer::getFile(FilePath, /*FileSize=*/-1, 196 /*RequiresNullTerminator=*/true, 197 /*IsVolatile=*/true); 198 if (std::error_code Result = DatabaseBuffer.getError()) { 199 ErrorMessage = "Error while opening JSON database: " + Result.message(); 200 return nullptr; 201 } 202 std::unique_ptr<JSONCompilationDatabase> Database( 203 new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax)); 204 if (!Database->parse(ErrorMessage)) 205 return nullptr; 206 return Database; 207 } 208 209 std::unique_ptr<JSONCompilationDatabase> 210 JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString, 211 std::string &ErrorMessage, 212 JSONCommandLineSyntax Syntax) { 213 std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer( 214 llvm::MemoryBuffer::getMemBuffer(DatabaseString)); 215 std::unique_ptr<JSONCompilationDatabase> Database( 216 new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax)); 217 if (!Database->parse(ErrorMessage)) 218 return nullptr; 219 return Database; 220 } 221 222 std::vector<CompileCommand> 223 JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const { 224 SmallString<128> NativeFilePath; 225 llvm::sys::path::native(FilePath, NativeFilePath); 226 227 std::string Error; 228 llvm::raw_string_ostream ES(Error); 229 StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES); 230 if (Match.empty()) 231 return {}; 232 const auto CommandsRefI = IndexByFile.find(Match); 233 if (CommandsRefI == IndexByFile.end()) 234 return {}; 235 std::vector<CompileCommand> Commands; 236 getCommands(CommandsRefI->getValue(), Commands); 237 return Commands; 238 } 239 240 std::vector<std::string> 241 JSONCompilationDatabase::getAllFiles() const { 242 std::vector<std::string> Result; 243 for (const auto &CommandRef : IndexByFile) 244 Result.push_back(CommandRef.first().str()); 245 return Result; 246 } 247 248 std::vector<CompileCommand> 249 JSONCompilationDatabase::getAllCompileCommands() const { 250 std::vector<CompileCommand> Commands; 251 getCommands(AllCommands, Commands); 252 return Commands; 253 } 254 255 static std::vector<std::string> 256 nodeToCommandLine(JSONCommandLineSyntax Syntax, 257 const std::vector<llvm::yaml::ScalarNode *> &Nodes) { 258 SmallString<1024> Storage; 259 if (Nodes.size() == 1) 260 return unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage)); 261 std::vector<std::string> Arguments; 262 for (const auto *Node : Nodes) 263 Arguments.push_back(Node->getValue(Storage)); 264 return Arguments; 265 } 266 267 void JSONCompilationDatabase::getCommands( 268 ArrayRef<CompileCommandRef> CommandsRef, 269 std::vector<CompileCommand> &Commands) const { 270 for (const auto &CommandRef : CommandsRef) { 271 SmallString<8> DirectoryStorage; 272 SmallString<32> FilenameStorage; 273 SmallString<32> OutputStorage; 274 auto Output = std::get<3>(CommandRef); 275 Commands.emplace_back( 276 std::get<0>(CommandRef)->getValue(DirectoryStorage), 277 std::get<1>(CommandRef)->getValue(FilenameStorage), 278 nodeToCommandLine(Syntax, std::get<2>(CommandRef)), 279 Output ? Output->getValue(OutputStorage) : ""); 280 } 281 } 282 283 bool JSONCompilationDatabase::parse(std::string &ErrorMessage) { 284 llvm::yaml::document_iterator I = YAMLStream.begin(); 285 if (I == YAMLStream.end()) { 286 ErrorMessage = "Error while parsing YAML."; 287 return false; 288 } 289 llvm::yaml::Node *Root = I->getRoot(); 290 if (!Root) { 291 ErrorMessage = "Error while parsing YAML."; 292 return false; 293 } 294 auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root); 295 if (!Array) { 296 ErrorMessage = "Expected array."; 297 return false; 298 } 299 for (auto &NextObject : *Array) { 300 auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject); 301 if (!Object) { 302 ErrorMessage = "Expected object."; 303 return false; 304 } 305 llvm::yaml::ScalarNode *Directory = nullptr; 306 llvm::Optional<std::vector<llvm::yaml::ScalarNode *>> Command; 307 llvm::yaml::ScalarNode *File = nullptr; 308 llvm::yaml::ScalarNode *Output = nullptr; 309 for (auto& NextKeyValue : *Object) { 310 auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey()); 311 if (!KeyString) { 312 ErrorMessage = "Expected strings as key."; 313 return false; 314 } 315 SmallString<10> KeyStorage; 316 StringRef KeyValue = KeyString->getValue(KeyStorage); 317 llvm::yaml::Node *Value = NextKeyValue.getValue(); 318 if (!Value) { 319 ErrorMessage = "Expected value."; 320 return false; 321 } 322 auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value); 323 auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value); 324 if (KeyValue == "arguments" && !SequenceString) { 325 ErrorMessage = "Expected sequence as value."; 326 return false; 327 } else if (KeyValue != "arguments" && !ValueString) { 328 ErrorMessage = "Expected string as value."; 329 return false; 330 } 331 if (KeyValue == "directory") { 332 Directory = ValueString; 333 } else if (KeyValue == "arguments") { 334 Command = std::vector<llvm::yaml::ScalarNode *>(); 335 for (auto &Argument : *SequenceString) { 336 auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument); 337 if (!Scalar) { 338 ErrorMessage = "Only strings are allowed in 'arguments'."; 339 return false; 340 } 341 Command->push_back(Scalar); 342 } 343 } else if (KeyValue == "command") { 344 if (!Command) 345 Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString); 346 } else if (KeyValue == "file") { 347 File = ValueString; 348 } else if (KeyValue == "output") { 349 Output = ValueString; 350 } else { 351 ErrorMessage = ("Unknown key: \"" + 352 KeyString->getRawValue() + "\"").str(); 353 return false; 354 } 355 } 356 if (!File) { 357 ErrorMessage = "Missing key: \"file\"."; 358 return false; 359 } 360 if (!Command) { 361 ErrorMessage = "Missing key: \"command\" or \"arguments\"."; 362 return false; 363 } 364 if (!Directory) { 365 ErrorMessage = "Missing key: \"directory\"."; 366 return false; 367 } 368 SmallString<8> FileStorage; 369 StringRef FileName = File->getValue(FileStorage); 370 SmallString<128> NativeFilePath; 371 if (llvm::sys::path::is_relative(FileName)) { 372 SmallString<8> DirectoryStorage; 373 SmallString<128> AbsolutePath( 374 Directory->getValue(DirectoryStorage)); 375 llvm::sys::path::append(AbsolutePath, FileName); 376 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/ true); 377 llvm::sys::path::native(AbsolutePath, NativeFilePath); 378 } else { 379 llvm::sys::path::native(FileName, NativeFilePath); 380 } 381 auto Cmd = CompileCommandRef(Directory, File, *Command, Output); 382 IndexByFile[NativeFilePath].push_back(Cmd); 383 AllCommands.push_back(Cmd); 384 MatchTrie.insert(NativeFilePath); 385 } 386 return true; 387 } 388