JSONCompilationDatabase.cpp 15 KB

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