1 //===- CIndexer.cpp - Clang-C Source Indexing Library ---------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Clang-C Source Indexing library.
11 //===----------------------------------------------------------------------===//
15 #include "clang/Basic/LLVM.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/Driver/Driver.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Config/llvm-config.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/MD5.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/Program.h"
25 #include "llvm/Support/YAMLParser.h"
30 #include <cygwin/version.h>
31 #include <sys/cygwin.h>
44 using namespace clang
;
50 template <typename LibClangPathType
>
51 void getClangResourcesPathImplAIX(LibClangPathType
&LibClangPath
) {
52 int PrevErrno
= errno
;
54 size_t BufSize
= 2048u;
55 std::unique_ptr
<char[]> Buf
;
57 Buf
= std::make_unique
<char []>(BufSize
);
59 int Ret
= loadquery(L_GETXINFO
, Buf
.get(), (unsigned int)BufSize
);
61 break; // loadquery() was successful.
63 llvm_unreachable("Encountered an unexpected loadquery() failure");
65 // errno == ENOMEM; try to allocate more memory.
66 if ((BufSize
& ~((-1u) >> 1u)) != 0u)
67 llvm::report_fatal_error("BufSize needed for loadquery() too large");
73 // Extract the function entry point from the function descriptor.
75 reinterpret_cast<uintptr_t &>(clang_createTranslationUnit
);
77 // Loop to locate the function entry point in the loadquery() results.
78 ld_xinfo
*CurInfo
= reinterpret_cast<ld_xinfo
*>(Buf
.get());
80 uint64_t CurTextStart
= (uint64_t)CurInfo
->ldinfo_textorg
;
81 uint64_t CurTextEnd
= CurTextStart
+ CurInfo
->ldinfo_textsize
;
82 if (CurTextStart
<= EntryAddr
&& EntryAddr
< CurTextEnd
)
83 break; // Successfully located.
85 if (CurInfo
->ldinfo_next
== 0u)
86 llvm::report_fatal_error("Cannot locate entry point in "
87 "the loadquery() results");
88 CurInfo
= reinterpret_cast<ld_xinfo
*>(reinterpret_cast<char *>(CurInfo
) +
89 CurInfo
->ldinfo_next
);
92 LibClangPath
+= reinterpret_cast<char *>(CurInfo
) + CurInfo
->ldinfo_filename
;
96 } // end anonymous namespace
97 } // end namespace clang
100 const std::string
&CIndexer::getClangResourcesPath() {
101 // Did we already compute the path?
102 if (!ResourcesPath
.empty())
103 return ResourcesPath
;
105 SmallString
<128> LibClangPath
;
107 // Find the location where this library lives (libclang.dylib).
109 MEMORY_BASIC_INFORMATION mbi
;
111 VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit
, &mbi
,
113 GetModuleFileNameA((HINSTANCE
)mbi
.AllocationBase
, path
, MAX_PATH
);
116 char w32path
[MAX_PATH
];
117 strcpy(w32path
, path
);
118 #if CYGWIN_VERSION_API_MAJOR > 0 || CYGWIN_VERSION_API_MINOR >= 181
119 cygwin_conv_path(CCP_WIN_A_TO_POSIX
, w32path
, path
, MAX_PATH
);
121 cygwin_conv_to_full_posix_path(w32path
, path
);
125 LibClangPath
+= path
;
127 getClangResourcesPathImplAIX(LibClangPath
);
129 bool PathFound
= false;
130 #if defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
132 // This silly cast below avoids a C++ warning.
133 if (dladdr((void *)(uintptr_t)clang_createTranslationUnit
, &info
) != 0) {
134 // We now have the CIndex directory, locate clang relative to it.
135 LibClangPath
+= info
.dli_fname
;
141 if (!(Path
= llvm::sys::fs::getMainExecutable(nullptr, nullptr)).empty()) {
142 // If we can't get the path using dladdr, try to get the main executable
143 // path. This may be needed when we're statically linking libclang with
144 // musl libc, for example.
145 LibClangPath
+= Path
;
147 // It's rather unlikely we end up here. But it could happen, so report an
148 // error instead of crashing.
149 llvm::report_fatal_error("could not locate Clang resource path");
156 ResourcesPath
= driver::Driver::GetResourcesPath(LibClangPath
);
157 return ResourcesPath
;
160 StringRef
CIndexer::getClangToolchainPath() {
161 if (!ToolchainPath
.empty())
162 return ToolchainPath
;
163 StringRef ResourcePath
= getClangResourcesPath();
165 std::string(llvm::sys::path::parent_path(llvm::sys::path::parent_path(
166 llvm::sys::path::parent_path(ResourcePath
))));
167 return ToolchainPath
;
170 LibclangInvocationReporter::LibclangInvocationReporter(
171 CIndexer
&Idx
, OperationKind Op
, unsigned ParseOptions
,
172 llvm::ArrayRef
<const char *> Args
,
173 llvm::ArrayRef
<std::string
> InvocationArgs
,
174 llvm::ArrayRef
<CXUnsavedFile
> UnsavedFiles
) {
175 StringRef Path
= Idx
.getInvocationEmissionPath();
179 // Create a temporary file for the invocation log.
180 SmallString
<256> TempPath
;
182 llvm::sys::path::append(TempPath
, "libclang-%%%%%%%%%%%%");
184 if (llvm::sys::fs::createUniqueFile(TempPath
, FD
, TempPath
,
185 llvm::sys::fs::OF_Text
))
187 File
= static_cast<std::string
>(TempPath
);
188 llvm::raw_fd_ostream
OS(FD
, /*ShouldClose=*/true);
190 // Write out the information about the invocation to it.
191 auto WriteStringKey
= [&OS
](StringRef Key
, StringRef Value
) {
192 OS
<< R
"(")" << Key << R"(":")";
193 OS << llvm::yaml::escape(Value) << '"';
196 WriteStringKey("toolchain", Idx.getClangToolchainPath());
198 WriteStringKey("libclang.operation",
199 Op == OperationKind::ParseOperation ? "parse" : "complete");
201 OS << R"("libclang.opts":)" << ParseOptions;
204 for (const auto &I : llvm::enumerate(Args)) {
207 OS << '"' << llvm::yaml::escape(I.value()) << '"';
209 if (!InvocationArgs.empty()) {
210 OS << R"(],"invocation-args":[)";
211 for (const auto &I : llvm::enumerate(InvocationArgs)) {
214 OS << '"' << llvm::yaml::escape(I.value()) << '"';
217 if (!UnsavedFiles.empty()) {
218 OS << R"(],"unsaved_file_hashes":[)";
219 for (const auto &UF : llvm::enumerate(UnsavedFiles)) {
223 WriteStringKey("name", UF.value().Filename);
226 Hash.update(getContents(UF.value()));
227 llvm::MD5::MD5Result Result;
229 SmallString<32> Digest = Result.digest();
230 WriteStringKey("md5", Digest);
237 LibclangInvocationReporter::~LibclangInvocationReporter() {
239 llvm::sys::fs::remove(File);