xref: /netbsd-src/external/apache2/llvm/dist/clang/tools/libclang/CIndexer.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===- CIndexer.cpp - Clang-C Source Indexing Library ---------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file implements the Clang-C Source Indexing library.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg 
137330f729Sjoerg #include "CIndexer.h"
147330f729Sjoerg #include "CXString.h"
157330f729Sjoerg #include "clang/Basic/LLVM.h"
167330f729Sjoerg #include "clang/Basic/Version.h"
177330f729Sjoerg #include "clang/Driver/Driver.h"
187330f729Sjoerg #include "llvm/ADT/STLExtras.h"
197330f729Sjoerg #include "llvm/ADT/SmallString.h"
20*e038c9c4Sjoerg #include "llvm/Support/FileSystem.h"
217330f729Sjoerg #include "llvm/Support/MD5.h"
227330f729Sjoerg #include "llvm/Support/Path.h"
237330f729Sjoerg #include "llvm/Support/Program.h"
247330f729Sjoerg #include "llvm/Support/YAMLParser.h"
257330f729Sjoerg #include <cstdio>
267330f729Sjoerg #include <mutex>
277330f729Sjoerg 
287330f729Sjoerg #ifdef __CYGWIN__
297330f729Sjoerg #include <cygwin/version.h>
307330f729Sjoerg #include <sys/cygwin.h>
317330f729Sjoerg #define _WIN32 1
327330f729Sjoerg #endif
337330f729Sjoerg 
347330f729Sjoerg #ifdef _WIN32
357330f729Sjoerg #include <windows.h>
367330f729Sjoerg #elif defined(_AIX)
377330f729Sjoerg #include <errno.h>
387330f729Sjoerg #include <sys/ldr.h>
397330f729Sjoerg #else
407330f729Sjoerg #include <dlfcn.h>
417330f729Sjoerg #endif
427330f729Sjoerg 
437330f729Sjoerg using namespace clang;
447330f729Sjoerg 
457330f729Sjoerg #ifdef _AIX
467330f729Sjoerg namespace clang {
477330f729Sjoerg namespace {
487330f729Sjoerg 
497330f729Sjoerg template <typename LibClangPathType>
getClangResourcesPathImplAIX(LibClangPathType & LibClangPath)507330f729Sjoerg void getClangResourcesPathImplAIX(LibClangPathType &LibClangPath) {
517330f729Sjoerg   int PrevErrno = errno;
527330f729Sjoerg 
537330f729Sjoerg   size_t BufSize = 2048u;
547330f729Sjoerg   std::unique_ptr<char[]> Buf;
557330f729Sjoerg   while (true) {
567330f729Sjoerg     Buf = std::make_unique<char []>(BufSize);
577330f729Sjoerg     errno = 0;
587330f729Sjoerg     int Ret = loadquery(L_GETXINFO, Buf.get(), (unsigned int)BufSize);
597330f729Sjoerg     if (Ret != -1)
607330f729Sjoerg       break; // loadquery() was successful.
617330f729Sjoerg     if (errno != ENOMEM)
627330f729Sjoerg       llvm_unreachable("Encountered an unexpected loadquery() failure");
637330f729Sjoerg 
647330f729Sjoerg     // errno == ENOMEM; try to allocate more memory.
657330f729Sjoerg     if ((BufSize & ~((-1u) >> 1u)) != 0u)
667330f729Sjoerg       llvm::report_fatal_error("BufSize needed for loadquery() too large");
677330f729Sjoerg 
687330f729Sjoerg     Buf.release();
697330f729Sjoerg     BufSize <<= 1u;
707330f729Sjoerg   }
717330f729Sjoerg 
727330f729Sjoerg   // Extract the function entry point from the function descriptor.
737330f729Sjoerg   uint64_t EntryAddr =
747330f729Sjoerg       reinterpret_cast<uintptr_t &>(clang_createTranslationUnit);
757330f729Sjoerg 
767330f729Sjoerg   // Loop to locate the function entry point in the loadquery() results.
777330f729Sjoerg   ld_xinfo *CurInfo = reinterpret_cast<ld_xinfo *>(Buf.get());
787330f729Sjoerg   while (true) {
797330f729Sjoerg     uint64_t CurTextStart = (uint64_t)CurInfo->ldinfo_textorg;
807330f729Sjoerg     uint64_t CurTextEnd = CurTextStart + CurInfo->ldinfo_textsize;
817330f729Sjoerg     if (CurTextStart <= EntryAddr && EntryAddr < CurTextEnd)
827330f729Sjoerg       break; // Successfully located.
837330f729Sjoerg 
847330f729Sjoerg     if (CurInfo->ldinfo_next == 0u)
857330f729Sjoerg       llvm::report_fatal_error("Cannot locate entry point in "
867330f729Sjoerg                                "the loadquery() results");
877330f729Sjoerg     CurInfo = reinterpret_cast<ld_xinfo *>(reinterpret_cast<char *>(CurInfo) +
887330f729Sjoerg                                            CurInfo->ldinfo_next);
897330f729Sjoerg   }
907330f729Sjoerg 
917330f729Sjoerg   LibClangPath += reinterpret_cast<char *>(CurInfo) + CurInfo->ldinfo_filename;
927330f729Sjoerg   errno = PrevErrno;
937330f729Sjoerg }
947330f729Sjoerg 
957330f729Sjoerg } // end anonymous namespace
967330f729Sjoerg } // end namespace clang
977330f729Sjoerg #endif
987330f729Sjoerg 
getClangResourcesPath()997330f729Sjoerg const std::string &CIndexer::getClangResourcesPath() {
1007330f729Sjoerg   // Did we already compute the path?
1017330f729Sjoerg   if (!ResourcesPath.empty())
1027330f729Sjoerg     return ResourcesPath;
1037330f729Sjoerg 
1047330f729Sjoerg   SmallString<128> LibClangPath;
1057330f729Sjoerg 
1067330f729Sjoerg   // Find the location where this library lives (libclang.dylib).
1077330f729Sjoerg #ifdef _WIN32
1087330f729Sjoerg   MEMORY_BASIC_INFORMATION mbi;
1097330f729Sjoerg   char path[MAX_PATH];
1107330f729Sjoerg   VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit, &mbi,
1117330f729Sjoerg                sizeof(mbi));
1127330f729Sjoerg   GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH);
1137330f729Sjoerg 
1147330f729Sjoerg #ifdef __CYGWIN__
1157330f729Sjoerg   char w32path[MAX_PATH];
1167330f729Sjoerg   strcpy(w32path, path);
1177330f729Sjoerg #if CYGWIN_VERSION_API_MAJOR > 0 || CYGWIN_VERSION_API_MINOR >= 181
1187330f729Sjoerg   cygwin_conv_path(CCP_WIN_A_TO_POSIX, w32path, path, MAX_PATH);
1197330f729Sjoerg #else
1207330f729Sjoerg   cygwin_conv_to_full_posix_path(w32path, path);
1217330f729Sjoerg #endif
1227330f729Sjoerg #endif
1237330f729Sjoerg 
1247330f729Sjoerg   LibClangPath += path;
1257330f729Sjoerg #elif defined(_AIX)
1267330f729Sjoerg   getClangResourcesPathImplAIX(LibClangPath);
1277330f729Sjoerg #else
1287330f729Sjoerg   // This silly cast below avoids a C++ warning.
1297330f729Sjoerg   Dl_info info;
1307330f729Sjoerg   if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) == 0)
1317330f729Sjoerg     llvm_unreachable("Call to dladdr() failed");
1327330f729Sjoerg 
1337330f729Sjoerg   // We now have the CIndex directory, locate clang relative to it.
1347330f729Sjoerg   LibClangPath += info.dli_fname;
1357330f729Sjoerg #endif
1367330f729Sjoerg 
1377330f729Sjoerg   // Cache our result.
1387330f729Sjoerg   ResourcesPath = driver::Driver::GetResourcesPath(LibClangPath);
1397330f729Sjoerg   return ResourcesPath;
1407330f729Sjoerg }
1417330f729Sjoerg 
getClangToolchainPath()1427330f729Sjoerg StringRef CIndexer::getClangToolchainPath() {
1437330f729Sjoerg   if (!ToolchainPath.empty())
1447330f729Sjoerg     return ToolchainPath;
1457330f729Sjoerg   StringRef ResourcePath = getClangResourcesPath();
146*e038c9c4Sjoerg   ToolchainPath =
147*e038c9c4Sjoerg       std::string(llvm::sys::path::parent_path(llvm::sys::path::parent_path(
148*e038c9c4Sjoerg           llvm::sys::path::parent_path(ResourcePath))));
1497330f729Sjoerg   return ToolchainPath;
1507330f729Sjoerg }
1517330f729Sjoerg 
LibclangInvocationReporter(CIndexer & Idx,OperationKind Op,unsigned ParseOptions,llvm::ArrayRef<const char * > Args,llvm::ArrayRef<std::string> InvocationArgs,llvm::ArrayRef<CXUnsavedFile> UnsavedFiles)1527330f729Sjoerg LibclangInvocationReporter::LibclangInvocationReporter(
1537330f729Sjoerg     CIndexer &Idx, OperationKind Op, unsigned ParseOptions,
1547330f729Sjoerg     llvm::ArrayRef<const char *> Args,
1557330f729Sjoerg     llvm::ArrayRef<std::string> InvocationArgs,
1567330f729Sjoerg     llvm::ArrayRef<CXUnsavedFile> UnsavedFiles) {
1577330f729Sjoerg   StringRef Path = Idx.getInvocationEmissionPath();
1587330f729Sjoerg   if (Path.empty())
1597330f729Sjoerg     return;
1607330f729Sjoerg 
1617330f729Sjoerg   // Create a temporary file for the invocation log.
1627330f729Sjoerg   SmallString<256> TempPath;
1637330f729Sjoerg   TempPath = Path;
1647330f729Sjoerg   llvm::sys::path::append(TempPath, "libclang-%%%%%%%%%%%%");
1657330f729Sjoerg   int FD;
166*e038c9c4Sjoerg   if (llvm::sys::fs::createUniqueFile(TempPath, FD, TempPath,
167*e038c9c4Sjoerg                                       llvm::sys::fs::OF_Text))
1687330f729Sjoerg     return;
1697330f729Sjoerg   File = std::string(TempPath.begin(), TempPath.end());
1707330f729Sjoerg   llvm::raw_fd_ostream OS(FD, /*ShouldClose=*/true);
1717330f729Sjoerg 
1727330f729Sjoerg   // Write out the information about the invocation to it.
1737330f729Sjoerg   auto WriteStringKey = [&OS](StringRef Key, StringRef Value) {
1747330f729Sjoerg     OS << R"(")" << Key << R"(":")";
1757330f729Sjoerg     OS << llvm::yaml::escape(Value) << '"';
1767330f729Sjoerg   };
1777330f729Sjoerg   OS << '{';
1787330f729Sjoerg   WriteStringKey("toolchain", Idx.getClangToolchainPath());
1797330f729Sjoerg   OS << ',';
1807330f729Sjoerg   WriteStringKey("libclang.operation",
1817330f729Sjoerg                  Op == OperationKind::ParseOperation ? "parse" : "complete");
1827330f729Sjoerg   OS << ',';
1837330f729Sjoerg   OS << R"("libclang.opts":)" << ParseOptions;
1847330f729Sjoerg   OS << ',';
1857330f729Sjoerg   OS << R"("args":[)";
1867330f729Sjoerg   for (const auto &I : llvm::enumerate(Args)) {
1877330f729Sjoerg     if (I.index())
1887330f729Sjoerg       OS << ',';
1897330f729Sjoerg     OS << '"' << llvm::yaml::escape(I.value()) << '"';
1907330f729Sjoerg   }
1917330f729Sjoerg   if (!InvocationArgs.empty()) {
1927330f729Sjoerg     OS << R"(],"invocation-args":[)";
1937330f729Sjoerg     for (const auto &I : llvm::enumerate(InvocationArgs)) {
1947330f729Sjoerg       if (I.index())
1957330f729Sjoerg         OS << ',';
1967330f729Sjoerg       OS << '"' << llvm::yaml::escape(I.value()) << '"';
1977330f729Sjoerg     }
1987330f729Sjoerg   }
1997330f729Sjoerg   if (!UnsavedFiles.empty()) {
2007330f729Sjoerg     OS << R"(],"unsaved_file_hashes":[)";
2017330f729Sjoerg     for (const auto &UF : llvm::enumerate(UnsavedFiles)) {
2027330f729Sjoerg       if (UF.index())
2037330f729Sjoerg         OS << ',';
2047330f729Sjoerg       OS << '{';
2057330f729Sjoerg       WriteStringKey("name", UF.value().Filename);
2067330f729Sjoerg       OS << ',';
2077330f729Sjoerg       llvm::MD5 Hash;
2087330f729Sjoerg       Hash.update(getContents(UF.value()));
2097330f729Sjoerg       llvm::MD5::MD5Result Result;
2107330f729Sjoerg       Hash.final(Result);
2117330f729Sjoerg       SmallString<32> Digest = Result.digest();
2127330f729Sjoerg       WriteStringKey("md5", Digest);
2137330f729Sjoerg       OS << '}';
2147330f729Sjoerg     }
2157330f729Sjoerg   }
2167330f729Sjoerg   OS << "]}";
2177330f729Sjoerg }
2187330f729Sjoerg 
2197330f729Sjoerg LibclangInvocationReporter::~LibclangInvocationReporter() {
2207330f729Sjoerg   if (!File.empty())
2217330f729Sjoerg     llvm::sys::fs::remove(File);
2227330f729Sjoerg }
223