CIndexer.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. Dl_info info;
  110. std::string Path;
  111. // This silly cast below avoids a C++ warning.
  112. if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) != 0) {
  113. // We now have the CIndex directory, locate clang relative to it.
  114. LibClangPath += info.dli_fname;
  115. } else if (!(Path = llvm::sys::fs::getMainExecutable(nullptr, nullptr)).empty()) {
  116. // If we can't get the path using dladdr, try to get the main executable
  117. // path. This may be needed when we're statically linking libclang with
  118. // musl libc, for example.
  119. LibClangPath += Path;
  120. } else {
  121. // It's rather unlikely we end up here. But it could happen, so report an
  122. // error instead of crashing.
  123. llvm::report_fatal_error("could not locate Clang resource path");
  124. }
  125. #endif
  126. // Cache our result.
  127. ResourcesPath = driver::Driver::GetResourcesPath(LibClangPath);
  128. return ResourcesPath;
  129. }
  130. StringRef CIndexer::getClangToolchainPath() {
  131. if (!ToolchainPath.empty())
  132. return ToolchainPath;
  133. StringRef ResourcePath = getClangResourcesPath();
  134. ToolchainPath =
  135. std::string(llvm::sys::path::parent_path(llvm::sys::path::parent_path(
  136. llvm::sys::path::parent_path(ResourcePath))));
  137. return ToolchainPath;
  138. }
  139. LibclangInvocationReporter::LibclangInvocationReporter(
  140. CIndexer &Idx, OperationKind Op, unsigned ParseOptions,
  141. llvm::ArrayRef<const char *> Args,
  142. llvm::ArrayRef<std::string> InvocationArgs,
  143. llvm::ArrayRef<CXUnsavedFile> UnsavedFiles) {
  144. StringRef Path = Idx.getInvocationEmissionPath();
  145. if (Path.empty())
  146. return;
  147. // Create a temporary file for the invocation log.
  148. SmallString<256> TempPath;
  149. TempPath = Path;
  150. llvm::sys::path::append(TempPath, "libclang-%%%%%%%%%%%%");
  151. int FD;
  152. if (llvm::sys::fs::createUniqueFile(TempPath, FD, TempPath,
  153. llvm::sys::fs::OF_Text))
  154. return;
  155. File = static_cast<std::string>(TempPath);
  156. llvm::raw_fd_ostream OS(FD, /*ShouldClose=*/true);
  157. // Write out the information about the invocation to it.
  158. auto WriteStringKey = [&OS](StringRef Key, StringRef Value) {
  159. OS << R"(")" << Key << R"(":")";
  160. OS << llvm::yaml::escape(Value) << '"';
  161. };
  162. OS << '{';
  163. WriteStringKey("toolchain", Idx.getClangToolchainPath());
  164. OS << ',';
  165. WriteStringKey("libclang.operation",
  166. Op == OperationKind::ParseOperation ? "parse" : "complete");
  167. OS << ',';
  168. OS << R"("libclang.opts":)" << ParseOptions;
  169. OS << ',';
  170. OS << R"("args":[)";
  171. for (const auto &I : llvm::enumerate(Args)) {
  172. if (I.index())
  173. OS << ',';
  174. OS << '"' << llvm::yaml::escape(I.value()) << '"';
  175. }
  176. if (!InvocationArgs.empty()) {
  177. OS << R"(],"invocation-args":[)";
  178. for (const auto &I : llvm::enumerate(InvocationArgs)) {
  179. if (I.index())
  180. OS << ',';
  181. OS << '"' << llvm::yaml::escape(I.value()) << '"';
  182. }
  183. }
  184. if (!UnsavedFiles.empty()) {
  185. OS << R"(],"unsaved_file_hashes":[)";
  186. for (const auto &UF : llvm::enumerate(UnsavedFiles)) {
  187. if (UF.index())
  188. OS << ',';
  189. OS << '{';
  190. WriteStringKey("name", UF.value().Filename);
  191. OS << ',';
  192. llvm::MD5 Hash;
  193. Hash.update(getContents(UF.value()));
  194. llvm::MD5::MD5Result Result;
  195. Hash.final(Result);
  196. SmallString<32> Digest = Result.digest();
  197. WriteStringKey("md5", Digest);
  198. OS << '}';
  199. }
  200. }
  201. OS << "]}";
  202. }
  203. LibclangInvocationReporter::~LibclangInvocationReporter() {
  204. if (!File.empty())
  205. llvm::sys::fs::remove(File);
  206. }