CIndexer.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. //===- CIndexer.cpp - Clang-C Source Indexing Library ---------------------===//
  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 implements the Clang-C Source Indexing library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CIndexer.h"
  13. #include "CXString.h"
  14. #include "clang/Basic/LLVM.h"
  15. #include "clang/Basic/Version.h"
  16. #include "clang/Driver/Driver.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/Support/FileSystem.h"
  20. #include "llvm/Support/MD5.h"
  21. #include "llvm/Support/Path.h"
  22. #include "llvm/Support/Program.h"
  23. #include "llvm/Support/YAMLParser.h"
  24. #include <cstdio>
  25. #include <mutex>
  26. #ifdef __CYGWIN__
  27. #include <cygwin/version.h>
  28. #include <sys/cygwin.h>
  29. #define _WIN32 1
  30. #endif
  31. #ifdef _WIN32
  32. #include <windows.h>
  33. #elif defined(_AIX)
  34. #include <errno.h>
  35. #error #include <sys/ldr.h>
  36. #else
  37. #include <dlfcn.h>
  38. #endif
  39. using namespace clang;
  40. #ifdef _AIX
  41. namespace clang {
  42. namespace {
  43. template <typename LibClangPathType>
  44. void getClangResourcesPathImplAIX(LibClangPathType &LibClangPath) {
  45. int PrevErrno = errno;
  46. size_t BufSize = 2048u;
  47. std::unique_ptr<char[]> Buf;
  48. while (true) {
  49. Buf = std::make_unique<char []>(BufSize);
  50. errno = 0;
  51. int Ret = loadquery(L_GETXINFO, Buf.get(), (unsigned int)BufSize);
  52. if (Ret != -1)
  53. break; // loadquery() was successful.
  54. if (errno != ENOMEM)
  55. llvm_unreachable("Encountered an unexpected loadquery() failure");
  56. // errno == ENOMEM; try to allocate more memory.
  57. if ((BufSize & ~((-1u) >> 1u)) != 0u)
  58. llvm::report_fatal_error("BufSize needed for loadquery() too large");
  59. Buf.release();
  60. BufSize <<= 1u;
  61. }
  62. // Extract the function entry point from the function descriptor.
  63. uint64_t EntryAddr =
  64. reinterpret_cast<uintptr_t &>(clang_createTranslationUnit);
  65. // Loop to locate the function entry point in the loadquery() results.
  66. ld_xinfo *CurInfo = reinterpret_cast<ld_xinfo *>(Buf.get());
  67. while (true) {
  68. uint64_t CurTextStart = (uint64_t)CurInfo->ldinfo_textorg;
  69. uint64_t CurTextEnd = CurTextStart + CurInfo->ldinfo_textsize;
  70. if (CurTextStart <= EntryAddr && EntryAddr < CurTextEnd)
  71. break; // Successfully located.
  72. if (CurInfo->ldinfo_next == 0u)
  73. llvm::report_fatal_error("Cannot locate entry point in "
  74. "the loadquery() results");
  75. CurInfo = reinterpret_cast<ld_xinfo *>(reinterpret_cast<char *>(CurInfo) +
  76. CurInfo->ldinfo_next);
  77. }
  78. LibClangPath += reinterpret_cast<char *>(CurInfo) + CurInfo->ldinfo_filename;
  79. errno = PrevErrno;
  80. }
  81. } // end anonymous namespace
  82. } // end namespace clang
  83. #endif
  84. const std::string &CIndexer::getClangResourcesPath() {
  85. // Did we already compute the path?
  86. if (!ResourcesPath.empty())
  87. return ResourcesPath;
  88. SmallString<128> LibClangPath;
  89. // Find the location where this library lives (libclang.dylib).
  90. #ifdef _WIN32
  91. MEMORY_BASIC_INFORMATION mbi;
  92. char path[MAX_PATH];
  93. VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit, &mbi,
  94. sizeof(mbi));
  95. GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH);
  96. #ifdef __CYGWIN__
  97. char w32path[MAX_PATH];
  98. strcpy(w32path, path);
  99. #if CYGWIN_VERSION_API_MAJOR > 0 || CYGWIN_VERSION_API_MINOR >= 181
  100. cygwin_conv_path(CCP_WIN_A_TO_POSIX, w32path, path, MAX_PATH);
  101. #else
  102. cygwin_conv_to_full_posix_path(w32path, path);
  103. #endif
  104. #endif
  105. LibClangPath += path;
  106. #elif defined(_AIX)
  107. getClangResourcesPathImplAIX(LibClangPath);
  108. #else
  109. // This silly cast below avoids a C++ warning.
  110. Dl_info info;
  111. if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) == 0)
  112. llvm_unreachable("Call to dladdr() failed");
  113. // We now have the CIndex directory, locate clang relative to it.
  114. LibClangPath += info.dli_fname;
  115. #endif
  116. // Cache our result.
  117. ResourcesPath = driver::Driver::GetResourcesPath(LibClangPath);
  118. return ResourcesPath;
  119. }
  120. StringRef CIndexer::getClangToolchainPath() {
  121. if (!ToolchainPath.empty())
  122. return ToolchainPath;
  123. StringRef ResourcePath = getClangResourcesPath();
  124. ToolchainPath =
  125. std::string(llvm::sys::path::parent_path(llvm::sys::path::parent_path(
  126. llvm::sys::path::parent_path(ResourcePath))));
  127. return ToolchainPath;
  128. }
  129. LibclangInvocationReporter::LibclangInvocationReporter(
  130. CIndexer &Idx, OperationKind Op, unsigned ParseOptions,
  131. llvm::ArrayRef<const char *> Args,
  132. llvm::ArrayRef<std::string> InvocationArgs,
  133. llvm::ArrayRef<CXUnsavedFile> UnsavedFiles) {
  134. StringRef Path = Idx.getInvocationEmissionPath();
  135. if (Path.empty())
  136. return;
  137. // Create a temporary file for the invocation log.
  138. SmallString<256> TempPath;
  139. TempPath = Path;
  140. llvm::sys::path::append(TempPath, "libclang-%%%%%%%%%%%%");
  141. int FD;
  142. if (llvm::sys::fs::createUniqueFile(TempPath, FD, TempPath,
  143. llvm::sys::fs::OF_Text))
  144. return;
  145. File = std::string(TempPath.begin(), TempPath.end());
  146. llvm::raw_fd_ostream OS(FD, /*ShouldClose=*/true);
  147. // Write out the information about the invocation to it.
  148. auto WriteStringKey = [&OS](StringRef Key, StringRef Value) {
  149. OS << R"(")" << Key << R"(":")";
  150. OS << llvm::yaml::escape(Value) << '"';
  151. };
  152. OS << '{';
  153. WriteStringKey("toolchain", Idx.getClangToolchainPath());
  154. OS << ',';
  155. WriteStringKey("libclang.operation",
  156. Op == OperationKind::ParseOperation ? "parse" : "complete");
  157. OS << ',';
  158. OS << R"("libclang.opts":)" << ParseOptions;
  159. OS << ',';
  160. OS << R"("args":[)";
  161. for (const auto &I : llvm::enumerate(Args)) {
  162. if (I.index())
  163. OS << ',';
  164. OS << '"' << llvm::yaml::escape(I.value()) << '"';
  165. }
  166. if (!InvocationArgs.empty()) {
  167. OS << R"(],"invocation-args":[)";
  168. for (const auto &I : llvm::enumerate(InvocationArgs)) {
  169. if (I.index())
  170. OS << ',';
  171. OS << '"' << llvm::yaml::escape(I.value()) << '"';
  172. }
  173. }
  174. if (!UnsavedFiles.empty()) {
  175. OS << R"(],"unsaved_file_hashes":[)";
  176. for (const auto &UF : llvm::enumerate(UnsavedFiles)) {
  177. if (UF.index())
  178. OS << ',';
  179. OS << '{';
  180. WriteStringKey("name", UF.value().Filename);
  181. OS << ',';
  182. llvm::MD5 Hash;
  183. Hash.update(getContents(UF.value()));
  184. llvm::MD5::MD5Result Result;
  185. Hash.final(Result);
  186. SmallString<32> Digest = Result.digest();
  187. WriteStringKey("md5", Digest);
  188. OS << '}';
  189. }
  190. }
  191. OS << "]}";
  192. }
  193. LibclangInvocationReporter::~LibclangInvocationReporter() {
  194. if (!File.empty())
  195. llvm::sys::fs::remove(File);
  196. }