Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp
Warning:line 120, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ExecutionUtils.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/ExecutionEngine/Orc -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/ExecutionEngine/Orc -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp

/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp

1//===---- ExecutionUtils.cpp - Utilities for executing functions in Orc ---===//
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#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
10#include "llvm/ExecutionEngine/JITLink/x86_64.h"
11#include "llvm/ExecutionEngine/Orc/Layer.h"
12#include "llvm/ExecutionEngine/Orc/ObjectFileInterface.h"
13#include "llvm/IR/Constants.h"
14#include "llvm/IR/Function.h"
15#include "llvm/IR/GlobalVariable.h"
16#include "llvm/IR/Module.h"
17#include "llvm/MC/TargetRegistry.h"
18#include "llvm/Object/MachOUniversal.h"
19#include "llvm/Support/FormatVariadic.h"
20#include "llvm/Target/TargetMachine.h"
21#include <string>
22
23namespace llvm {
24namespace orc {
25
26CtorDtorIterator::CtorDtorIterator(const GlobalVariable *GV, bool End)
27 : InitList(
28 GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
29 I((InitList && End) ? InitList->getNumOperands() : 0) {
30}
31
32bool CtorDtorIterator::operator==(const CtorDtorIterator &Other) const {
33 assert(InitList == Other.InitList && "Incomparable iterators.")(static_cast <bool> (InitList == Other.InitList &&
"Incomparable iterators.") ? void (0) : __assert_fail ("InitList == Other.InitList && \"Incomparable iterators.\""
, "llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp", 33, __extension__
__PRETTY_FUNCTION__))
;
34 return I == Other.I;
35}
36
37bool CtorDtorIterator::operator!=(const CtorDtorIterator &Other) const {
38 return !(*this == Other);
39}
40
41CtorDtorIterator& CtorDtorIterator::operator++() {
42 ++I;
43 return *this;
44}
45
46CtorDtorIterator CtorDtorIterator::operator++(int) {
47 CtorDtorIterator Temp = *this;
48 ++I;
49 return Temp;
50}
51
52CtorDtorIterator::Element CtorDtorIterator::operator*() const {
53 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(I));
4
Assuming the object is a 'CastReturnType'
54 assert(CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors")(static_cast <bool> (CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors"
) ? void (0) : __assert_fail ("CS && \"Unrecognized type in llvm.global_ctors/llvm.global_dtors\""
, "llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp", 54, __extension__
__PRETTY_FUNCTION__))
;
5
'?' condition is true
55
56 Constant *FuncC = CS->getOperand(1);
57 Function *Func = nullptr;
6
'Func' initialized to a null pointer value
58
59 // Extract function pointer, pulling off any casts.
60 while (FuncC) {
7
Loop condition is false. Execution continues on line 75
61 if (Function *F = dyn_cast_or_null<Function>(FuncC)) {
62 Func = F;
63 break;
64 } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
65 if (CE->isCast())
66 FuncC = CE->getOperand(0);
67 else
68 break;
69 } else {
70 // This isn't anything we recognize. Bail out with Func left set to null.
71 break;
72 }
73 }
74
75 auto *Priority = cast<ConstantInt>(CS->getOperand(0));
8
The object is a 'CastReturnType'
76 Value *Data = CS->getNumOperands() == 3 ? CS->getOperand(2) : nullptr;
9
Assuming the condition is false
10
'?' condition is false
77 if (Data
10.1
'Data' is null
10.1
'Data' is null
&& !isa<GlobalValue>(Data))
78 Data = nullptr;
79 return Element(Priority->getZExtValue(), Func, Data);
11
Passing null pointer value via 2nd parameter 'Func'
12
Calling constructor for 'Element'
14
Returning from constructor for 'Element'
80}
81
82iterator_range<CtorDtorIterator> getConstructors(const Module &M) {
83 const GlobalVariable *CtorsList = M.getNamedGlobal("llvm.global_ctors");
84 return make_range(CtorDtorIterator(CtorsList, false),
85 CtorDtorIterator(CtorsList, true));
86}
87
88iterator_range<CtorDtorIterator> getDestructors(const Module &M) {
89 const GlobalVariable *DtorsList = M.getNamedGlobal("llvm.global_dtors");
90 return make_range(CtorDtorIterator(DtorsList, false),
91 CtorDtorIterator(DtorsList, true));
92}
93
94bool StaticInitGVIterator::isStaticInitGlobal(GlobalValue &GV) {
95 if (GV.isDeclaration())
96 return false;
97
98 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
99 GV.getName() == "llvm.global_dtors"))
100 return true;
101
102 if (ObjFmt == Triple::MachO) {
103 // FIXME: These section checks are too strict: We should match first and
104 // second word split by comma.
105 if (GV.hasSection() &&
106 (GV.getSection().startswith("__DATA,__objc_classlist") ||
107 GV.getSection().startswith("__DATA,__objc_selrefs")))
108 return true;
109 }
110
111 return false;
112}
113
114void CtorDtorRunner::add(iterator_range<CtorDtorIterator> CtorDtors) {
115 if (CtorDtors.empty())
1
Assuming the condition is false
2
Taking false branch
116 return;
117
118 MangleAndInterner Mangle(
119 JD.getExecutionSession(),
120 (*CtorDtors.begin()).Func->getParent()->getDataLayout());
3
Calling 'CtorDtorIterator::operator*'
15
Returning from 'CtorDtorIterator::operator*'
16
Called C++ object pointer is null
121
122 for (auto CtorDtor : CtorDtors) {
123 assert(CtorDtor.Func && CtorDtor.Func->hasName() &&(static_cast <bool> (CtorDtor.Func && CtorDtor.
Func->hasName() && "Ctor/Dtor function must be named to be runnable under the JIT"
) ? void (0) : __assert_fail ("CtorDtor.Func && CtorDtor.Func->hasName() && \"Ctor/Dtor function must be named to be runnable under the JIT\""
, "llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp", 124, __extension__
__PRETTY_FUNCTION__))
124 "Ctor/Dtor function must be named to be runnable under the JIT")(static_cast <bool> (CtorDtor.Func && CtorDtor.
Func->hasName() && "Ctor/Dtor function must be named to be runnable under the JIT"
) ? void (0) : __assert_fail ("CtorDtor.Func && CtorDtor.Func->hasName() && \"Ctor/Dtor function must be named to be runnable under the JIT\""
, "llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp", 124, __extension__
__PRETTY_FUNCTION__))
;
125
126 // FIXME: Maybe use a symbol promoter here instead.
127 if (CtorDtor.Func->hasLocalLinkage()) {
128 CtorDtor.Func->setLinkage(GlobalValue::ExternalLinkage);
129 CtorDtor.Func->setVisibility(GlobalValue::HiddenVisibility);
130 }
131
132 if (CtorDtor.Data && cast<GlobalValue>(CtorDtor.Data)->isDeclaration()) {
133 dbgs() << " Skipping because why now?\n";
134 continue;
135 }
136
137 CtorDtorsByPriority[CtorDtor.Priority].push_back(
138 Mangle(CtorDtor.Func->getName()));
139 }
140}
141
142Error CtorDtorRunner::run() {
143 using CtorDtorTy = void (*)();
144
145 SymbolLookupSet LookupSet;
146 for (auto &KV : CtorDtorsByPriority)
147 for (auto &Name : KV.second)
148 LookupSet.add(Name);
149 assert(!LookupSet.containsDuplicates() &&(static_cast <bool> (!LookupSet.containsDuplicates() &&
"Ctor/Dtor list contains duplicates") ? void (0) : __assert_fail
("!LookupSet.containsDuplicates() && \"Ctor/Dtor list contains duplicates\""
, "llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp", 150, __extension__
__PRETTY_FUNCTION__))
150 "Ctor/Dtor list contains duplicates")(static_cast <bool> (!LookupSet.containsDuplicates() &&
"Ctor/Dtor list contains duplicates") ? void (0) : __assert_fail
("!LookupSet.containsDuplicates() && \"Ctor/Dtor list contains duplicates\""
, "llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp", 150, __extension__
__PRETTY_FUNCTION__))
;
151
152 auto &ES = JD.getExecutionSession();
153 if (auto CtorDtorMap = ES.lookup(
154 makeJITDylibSearchOrder(&JD, JITDylibLookupFlags::MatchAllSymbols),
155 std::move(LookupSet))) {
156 for (auto &KV : CtorDtorsByPriority) {
157 for (auto &Name : KV.second) {
158 assert(CtorDtorMap->count(Name) && "No entry for Name")(static_cast <bool> (CtorDtorMap->count(Name) &&
"No entry for Name") ? void (0) : __assert_fail ("CtorDtorMap->count(Name) && \"No entry for Name\""
, "llvm/lib/ExecutionEngine/Orc/ExecutionUtils.cpp", 158, __extension__
__PRETTY_FUNCTION__))
;
159 auto CtorDtor = reinterpret_cast<CtorDtorTy>(
160 static_cast<uintptr_t>((*CtorDtorMap)[Name].getAddress()));
161 CtorDtor();
162 }
163 }
164 CtorDtorsByPriority.clear();
165 return Error::success();
166 } else
167 return CtorDtorMap.takeError();
168}
169
170void LocalCXXRuntimeOverridesBase::runDestructors() {
171 auto& CXXDestructorDataPairs = DSOHandleOverride;
172 for (auto &P : CXXDestructorDataPairs)
173 P.first(P.second);
174 CXXDestructorDataPairs.clear();
175}
176
177int LocalCXXRuntimeOverridesBase::CXAAtExitOverride(DestructorPtr Destructor,
178 void *Arg,
179 void *DSOHandle) {
180 auto& CXXDestructorDataPairs =
181 *reinterpret_cast<CXXDestructorDataPairList*>(DSOHandle);
182 CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
183 return 0;
184}
185
186Error LocalCXXRuntimeOverrides::enable(JITDylib &JD,
187 MangleAndInterner &Mangle) {
188 SymbolMap RuntimeInterposes;
189 RuntimeInterposes[Mangle("__dso_handle")] =
190 JITEvaluatedSymbol(toTargetAddress(&DSOHandleOverride),
191 JITSymbolFlags::Exported);
192 RuntimeInterposes[Mangle("__cxa_atexit")] =
193 JITEvaluatedSymbol(toTargetAddress(&CXAAtExitOverride),
194 JITSymbolFlags::Exported);
195
196 return JD.define(absoluteSymbols(std::move(RuntimeInterposes)));
197}
198
199void ItaniumCXAAtExitSupport::registerAtExit(void (*F)(void *), void *Ctx,
200 void *DSOHandle) {
201 std::lock_guard<std::mutex> Lock(AtExitsMutex);
202 AtExitRecords[DSOHandle].push_back({F, Ctx});
203}
204
205void ItaniumCXAAtExitSupport::runAtExits(void *DSOHandle) {
206 std::vector<AtExitRecord> AtExitsToRun;
207
208 {
209 std::lock_guard<std::mutex> Lock(AtExitsMutex);
210 auto I = AtExitRecords.find(DSOHandle);
211 if (I != AtExitRecords.end()) {
212 AtExitsToRun = std::move(I->second);
213 AtExitRecords.erase(I);
214 }
215 }
216
217 while (!AtExitsToRun.empty()) {
218 AtExitsToRun.back().F(AtExitsToRun.back().Ctx);
219 AtExitsToRun.pop_back();
220 }
221}
222
223DynamicLibrarySearchGenerator::DynamicLibrarySearchGenerator(
224 sys::DynamicLibrary Dylib, char GlobalPrefix, SymbolPredicate Allow)
225 : Dylib(std::move(Dylib)), Allow(std::move(Allow)),
226 GlobalPrefix(GlobalPrefix) {}
227
228Expected<std::unique_ptr<DynamicLibrarySearchGenerator>>
229DynamicLibrarySearchGenerator::Load(const char *FileName, char GlobalPrefix,
230 SymbolPredicate Allow) {
231 std::string ErrMsg;
232 auto Lib = sys::DynamicLibrary::getPermanentLibrary(FileName, &ErrMsg);
233 if (!Lib.isValid())
234 return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
235 return std::make_unique<DynamicLibrarySearchGenerator>(
236 std::move(Lib), GlobalPrefix, std::move(Allow));
237}
238
239Error DynamicLibrarySearchGenerator::tryToGenerate(
240 LookupState &LS, LookupKind K, JITDylib &JD,
241 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
242 orc::SymbolMap NewSymbols;
243
244 bool HasGlobalPrefix = (GlobalPrefix != '\0');
245
246 for (auto &KV : Symbols) {
247 auto &Name = KV.first;
248
249 if ((*Name).empty())
250 continue;
251
252 if (Allow && !Allow(Name))
253 continue;
254
255 if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
256 continue;
257
258 std::string Tmp((*Name).data() + HasGlobalPrefix,
259 (*Name).size() - HasGlobalPrefix);
260 if (void *Addr = Dylib.getAddressOfSymbol(Tmp.c_str())) {
261 NewSymbols[Name] = JITEvaluatedSymbol(
262 static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(Addr)),
263 JITSymbolFlags::Exported);
264 }
265 }
266
267 if (NewSymbols.empty())
268 return Error::success();
269
270 return JD.define(absoluteSymbols(std::move(NewSymbols)));
271}
272
273Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
274StaticLibraryDefinitionGenerator::Load(
275 ObjectLayer &L, const char *FileName,
276 GetObjectFileInterface GetObjFileInterface) {
277 auto ArchiveBuffer = MemoryBuffer::getFile(FileName);
278
279 if (!ArchiveBuffer)
280 return createFileError(FileName, ArchiveBuffer.getError());
281
282 return Create(L, std::move(*ArchiveBuffer), std::move(GetObjFileInterface));
283}
284
285Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
286StaticLibraryDefinitionGenerator::Load(
287 ObjectLayer &L, const char *FileName, const Triple &TT,
288 GetObjectFileInterface GetObjFileInterface) {
289
290 auto B = object::createBinary(FileName);
291 if (!B)
292 return createFileError(FileName, B.takeError());
293
294 // If this is a regular archive then create an instance from it.
295 if (isa<object::Archive>(B->getBinary()))
296 return Create(L, std::move(B->takeBinary().second),
297 std::move(GetObjFileInterface));
298
299 // If this is a universal binary then search for a slice matching the given
300 // Triple.
301 if (auto *UB = cast<object::MachOUniversalBinary>(B->getBinary())) {
302 for (const auto &Obj : UB->objects()) {
303 auto ObjTT = Obj.getTriple();
304 if (ObjTT.getArch() == TT.getArch() &&
305 ObjTT.getSubArch() == TT.getSubArch() &&
306 (TT.getVendor() == Triple::UnknownVendor ||
307 ObjTT.getVendor() == TT.getVendor())) {
308 // We found a match. Create an instance from a buffer covering this
309 // slice.
310 auto SliceBuffer = MemoryBuffer::getFileSlice(FileName, Obj.getSize(),
311 Obj.getOffset());
312 if (!SliceBuffer)
313 return make_error<StringError>(
314 Twine("Could not create buffer for ") + TT.str() + " slice of " +
315 FileName + ": [ " + formatv("{0:x}", Obj.getOffset()) +
316 " .. " + formatv("{0:x}", Obj.getOffset() + Obj.getSize()) +
317 ": " + SliceBuffer.getError().message(),
318 SliceBuffer.getError());
319 return Create(L, std::move(*SliceBuffer),
320 std::move(GetObjFileInterface));
321 }
322 }
323
324 return make_error<StringError>(Twine("Universal binary ") + FileName +
325 " does not contain a slice for " +
326 TT.str(),
327 inconvertibleErrorCode());
328 }
329
330 return make_error<StringError>(Twine("Unrecognized file type for ") +
331 FileName,
332 inconvertibleErrorCode());
333}
334
335Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
336StaticLibraryDefinitionGenerator::Create(
337 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
338 GetObjectFileInterface GetObjFileInterface) {
339 Error Err = Error::success();
340
341 std::unique_ptr<StaticLibraryDefinitionGenerator> ADG(
342 new StaticLibraryDefinitionGenerator(
343 L, std::move(ArchiveBuffer), std::move(GetObjFileInterface), Err));
344
345 if (Err)
346 return std::move(Err);
347
348 return std::move(ADG);
349}
350
351Error StaticLibraryDefinitionGenerator::tryToGenerate(
352 LookupState &LS, LookupKind K, JITDylib &JD,
353 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
354 // Don't materialize symbols from static archives unless this is a static
355 // lookup.
356 if (K != LookupKind::Static)
357 return Error::success();
358
359 // Bail out early if we've already freed the archive.
360 if (!Archive)
361 return Error::success();
362
363 DenseSet<std::pair<StringRef, StringRef>> ChildBufferInfos;
364
365 for (const auto &KV : Symbols) {
366 const auto &Name = KV.first;
367 if (!ObjectFilesMap.count(Name))
368 continue;
369 auto ChildBuffer = ObjectFilesMap[Name];
370 ChildBufferInfos.insert(
371 {ChildBuffer.getBuffer(), ChildBuffer.getBufferIdentifier()});
372 }
373
374 for (auto ChildBufferInfo : ChildBufferInfos) {
375 MemoryBufferRef ChildBufferRef(ChildBufferInfo.first,
376 ChildBufferInfo.second);
377
378 auto I = GetObjFileInterface(L.getExecutionSession(), ChildBufferRef);
379 if (!I)
380 return I.takeError();
381
382 if (auto Err = L.add(JD, MemoryBuffer::getMemBuffer(ChildBufferRef, false),
383 std::move(*I)))
384 return Err;
385 }
386
387 return Error::success();
388}
389
390Error StaticLibraryDefinitionGenerator::buildObjectFilesMap() {
391 DenseMap<uint64_t, MemoryBufferRef> MemoryBuffers;
392 DenseSet<uint64_t> Visited;
393 DenseSet<uint64_t> Excluded;
394 for (auto &S : Archive->symbols()) {
395 StringRef SymName = S.getName();
396 auto Member = S.getMember();
397 if (!Member)
398 return Member.takeError();
399 auto DataOffset = Member->getDataOffset();
400 if (!Visited.count(DataOffset)) {
401 Visited.insert(DataOffset);
402 auto Child = Member->getAsBinary();
403 if (!Child)
404 return Child.takeError();
405 if ((*Child)->isCOFFImportFile()) {
406 ImportedDynamicLibraries.insert((*Child)->getFileName().str());
407 Excluded.insert(DataOffset);
408 continue;
409 }
410 MemoryBuffers[DataOffset] = (*Child)->getMemoryBufferRef();
411 }
412 if (!Excluded.count(DataOffset))
413 ObjectFilesMap[L.getExecutionSession().intern(SymName)] =
414 MemoryBuffers[DataOffset];
415 }
416
417 return Error::success();
418}
419
420StaticLibraryDefinitionGenerator::StaticLibraryDefinitionGenerator(
421 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
422 GetObjectFileInterface GetObjFileInterface, Error &Err)
423 : L(L), GetObjFileInterface(std::move(GetObjFileInterface)),
424 ArchiveBuffer(std::move(ArchiveBuffer)),
425 Archive(std::make_unique<object::Archive>(*this->ArchiveBuffer, Err)) {
426 ErrorAsOutParameter _(&Err);
427 if (!this->GetObjFileInterface)
428 this->GetObjFileInterface = getObjectFileInterface;
429 if (!Err)
430 Err = buildObjectFilesMap();
431}
432
433std::unique_ptr<DLLImportDefinitionGenerator>
434DLLImportDefinitionGenerator::Create(ExecutionSession &ES,
435 ObjectLinkingLayer &L) {
436 return std::unique_ptr<DLLImportDefinitionGenerator>(
437 new DLLImportDefinitionGenerator(ES, L));
438}
439
440Error DLLImportDefinitionGenerator::tryToGenerate(
441 LookupState &LS, LookupKind K, JITDylib &JD,
442 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
443 JITDylibSearchOrder LinkOrder;
444 JD.withLinkOrderDo([&](const JITDylibSearchOrder &LO) {
445 LinkOrder.reserve(LO.size());
446 for (auto &KV : LO) {
447 if (KV.first == &JD)
448 continue;
449 LinkOrder.push_back(KV);
450 }
451 });
452
453 // FIXME: if regular symbol name start with __imp_ we have to issue lookup of
454 // both __imp_ and stripped name and use the lookup information to resolve the
455 // real symbol name.
456 SymbolLookupSet LookupSet;
457 DenseMap<StringRef, SymbolLookupFlags> ToLookUpSymbols;
458 for (auto &KV : Symbols) {
459 StringRef Deinterned = *KV.first;
460 if (Deinterned.startswith(getImpPrefix()))
461 Deinterned = Deinterned.drop_front(StringRef(getImpPrefix()).size());
462 // Don't degrade the required state
463 if (ToLookUpSymbols.count(Deinterned) &&
464 ToLookUpSymbols[Deinterned] == SymbolLookupFlags::RequiredSymbol)
465 continue;
466 ToLookUpSymbols[Deinterned] = KV.second;
467 }
468
469 for (auto &KV : ToLookUpSymbols)
470 LookupSet.add(ES.intern(KV.first), KV.second);
471
472 auto Resolved =
473 ES.lookup(LinkOrder, LookupSet, LookupKind::DLSym, SymbolState::Resolved);
474 if (!Resolved)
475 return Resolved.takeError();
476
477 auto G = createStubsGraph(*Resolved);
478 if (!G)
479 return G.takeError();
480 return L.add(JD, std::move(*G));
481}
482
483Expected<unsigned>
484DLLImportDefinitionGenerator::getTargetPointerSize(const Triple &TT) {
485 switch (TT.getArch()) {
486 case Triple::x86_64:
487 return 8;
488 default:
489 return make_error<StringError>(
490 "architecture unsupported by DLLImportDefinitionGenerator",
491 inconvertibleErrorCode());
492 }
493}
494
495Expected<support::endianness>
496DLLImportDefinitionGenerator::getTargetEndianness(const Triple &TT) {
497 switch (TT.getArch()) {
498 case Triple::x86_64:
499 return support::endianness::little;
500 default:
501 return make_error<StringError>(
502 "architecture unsupported by DLLImportDefinitionGenerator",
503 inconvertibleErrorCode());
504 }
505}
506
507Expected<std::unique_ptr<jitlink::LinkGraph>>
508DLLImportDefinitionGenerator::createStubsGraph(const SymbolMap &Resolved) {
509 Triple TT = ES.getExecutorProcessControl().getTargetTriple();
510 auto PointerSize = getTargetEndianness(TT);
511 if (!PointerSize)
512 return PointerSize.takeError();
513 auto Endianness = getTargetEndianness(TT);
514 if (!Endianness)
515 return Endianness.takeError();
516
517 auto G = std::make_unique<jitlink::LinkGraph>(
518 "<DLLIMPORT_STUBS>", TT, *PointerSize, *Endianness,
519 jitlink::getGenericEdgeKindName);
520 jitlink::Section &Sec = G->createSection(
521 getSectionName(), jitlink::MemProt::Read | jitlink::MemProt::Exec);
522
523 for (auto &KV : Resolved) {
524 jitlink::Symbol &Target = G->addAbsoluteSymbol(
525 *KV.first, ExecutorAddr(KV.second.getAddress()), *PointerSize,
526 jitlink::Linkage::Strong, jitlink::Scope::Local, false);
527
528 // Create __imp_ symbol
529 jitlink::Symbol &Ptr =
530 jitlink::x86_64::createAnonymousPointer(*G, Sec, &Target);
531 auto NameCopy = G->allocateString(Twine(getImpPrefix()) + *KV.first);
532 StringRef NameCopyRef = StringRef(NameCopy.data(), NameCopy.size());
533 Ptr.setName(NameCopyRef);
534 Ptr.setLinkage(jitlink::Linkage::Strong);
535 Ptr.setScope(jitlink::Scope::Default);
536
537 // Create PLT stub
538 // FIXME: check PLT stub of data symbol is not accessed
539 jitlink::Block &StubBlock =
540 jitlink::x86_64::createPointerJumpStubBlock(*G, Sec, Ptr);
541 G->addDefinedSymbol(StubBlock, 0, *KV.first, StubBlock.getSize(),
542 jitlink::Linkage::Strong, jitlink::Scope::Default, true,
543 false);
544 }
545
546 return std::move(G);
547}
548
549} // End namespace orc.
550} // End namespace llvm.

/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h

1//===- ExecutionUtils.h - Utilities for executing code in Orc ---*- C++ -*-===//
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// Contains utilities for executing code in Orc.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
14#define LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
15
16#include "llvm/ADT/StringMap.h"
17#include "llvm/ADT/iterator_range.h"
18#include "llvm/ExecutionEngine/JITSymbol.h"
19#include "llvm/ExecutionEngine/Orc/Core.h"
20#include "llvm/ExecutionEngine/Orc/Mangling.h"
21#include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
22#include "llvm/ExecutionEngine/Orc/Shared/OrcError.h"
23#include "llvm/ExecutionEngine/RuntimeDyld.h"
24#include "llvm/Object/Archive.h"
25#include "llvm/Support/DynamicLibrary.h"
26#include <algorithm>
27#include <cstdint>
28#include <utility>
29#include <vector>
30
31namespace llvm {
32
33class ConstantArray;
34class GlobalVariable;
35class Function;
36class Module;
37class Value;
38
39namespace orc {
40
41class ObjectLayer;
42
43/// This iterator provides a convenient way to iterate over the elements
44/// of an llvm.global_ctors/llvm.global_dtors instance.
45///
46/// The easiest way to get hold of instances of this class is to use the
47/// getConstructors/getDestructors functions.
48class CtorDtorIterator {
49public:
50 /// Accessor for an element of the global_ctors/global_dtors array.
51 ///
52 /// This class provides a read-only view of the element with any casts on
53 /// the function stripped away.
54 struct Element {
55 Element(unsigned Priority, Function *Func, Value *Data)
56 : Priority(Priority), Func(Func), Data(Data) {}
13
Null pointer value stored to field 'Func'
57
58 unsigned Priority;
59 Function *Func;
60 Value *Data;
61 };
62
63 /// Construct an iterator instance. If End is true then this iterator
64 /// acts as the end of the range, otherwise it is the beginning.
65 CtorDtorIterator(const GlobalVariable *GV, bool End);
66
67 /// Test iterators for equality.
68 bool operator==(const CtorDtorIterator &Other) const;
69
70 /// Test iterators for inequality.
71 bool operator!=(const CtorDtorIterator &Other) const;
72
73 /// Pre-increment iterator.
74 CtorDtorIterator& operator++();
75
76 /// Post-increment iterator.
77 CtorDtorIterator operator++(int);
78
79 /// Dereference iterator. The resulting value provides a read-only view
80 /// of this element of the global_ctors/global_dtors list.
81 Element operator*() const;
82
83private:
84 const ConstantArray *InitList;
85 unsigned I;
86};
87
88/// Create an iterator range over the entries of the llvm.global_ctors
89/// array.
90iterator_range<CtorDtorIterator> getConstructors(const Module &M);
91
92/// Create an iterator range over the entries of the llvm.global_ctors
93/// array.
94iterator_range<CtorDtorIterator> getDestructors(const Module &M);
95
96/// This iterator provides a convenient way to iterate over GlobalValues that
97/// have initialization effects.
98class StaticInitGVIterator {
99public:
100 StaticInitGVIterator() = default;
101
102 StaticInitGVIterator(Module &M)
103 : I(M.global_values().begin()), E(M.global_values().end()),
104 ObjFmt(Triple(M.getTargetTriple()).getObjectFormat()) {
105 if (I != E) {
106 if (!isStaticInitGlobal(*I))
107 moveToNextStaticInitGlobal();
108 } else
109 I = E = Module::global_value_iterator();
110 }
111
112 bool operator==(const StaticInitGVIterator &O) const { return I == O.I; }
113 bool operator!=(const StaticInitGVIterator &O) const { return I != O.I; }
114
115 StaticInitGVIterator &operator++() {
116 assert(I != E && "Increment past end of range")(static_cast <bool> (I != E && "Increment past end of range"
) ? void (0) : __assert_fail ("I != E && \"Increment past end of range\""
, "llvm/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h", 116
, __extension__ __PRETTY_FUNCTION__))
;
117 moveToNextStaticInitGlobal();
118 return *this;
119 }
120
121 GlobalValue &operator*() { return *I; }
122
123private:
124 bool isStaticInitGlobal(GlobalValue &GV);
125 void moveToNextStaticInitGlobal() {
126 ++I;
127 while (I != E && !isStaticInitGlobal(*I))
128 ++I;
129 if (I == E)
130 I = E = Module::global_value_iterator();
131 }
132
133 Module::global_value_iterator I, E;
134 Triple::ObjectFormatType ObjFmt;
135};
136
137/// Create an iterator range over the GlobalValues that contribute to static
138/// initialization.
139inline iterator_range<StaticInitGVIterator> getStaticInitGVs(Module &M) {
140 return make_range(StaticInitGVIterator(M), StaticInitGVIterator());
141}
142
143class CtorDtorRunner {
144public:
145 CtorDtorRunner(JITDylib &JD) : JD(JD) {}
146 void add(iterator_range<CtorDtorIterator> CtorDtors);
147 Error run();
148
149private:
150 using CtorDtorList = std::vector<SymbolStringPtr>;
151 using CtorDtorPriorityMap = std::map<unsigned, CtorDtorList>;
152
153 JITDylib &JD;
154 CtorDtorPriorityMap CtorDtorsByPriority;
155};
156
157/// Support class for static dtor execution. For hosted (in-process) JITs
158/// only!
159///
160/// If a __cxa_atexit function isn't found C++ programs that use static
161/// destructors will fail to link. However, we don't want to use the host
162/// process's __cxa_atexit, because it will schedule JIT'd destructors to run
163/// after the JIT has been torn down, which is no good. This class makes it easy
164/// to override __cxa_atexit (and the related __dso_handle).
165///
166/// To use, clients should manually call searchOverrides from their symbol
167/// resolver. This should generally be done after attempting symbol resolution
168/// inside the JIT, but before searching the host process's symbol table. When
169/// the client determines that destructors should be run (generally at JIT
170/// teardown or after a return from main), the runDestructors method should be
171/// called.
172class LocalCXXRuntimeOverridesBase {
173public:
174 /// Run any destructors recorded by the overriden __cxa_atexit function
175 /// (CXAAtExitOverride).
176 void runDestructors();
177
178protected:
179 template <typename PtrTy> JITTargetAddress toTargetAddress(PtrTy *P) {
180 return static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(P));
181 }
182
183 using DestructorPtr = void (*)(void *);
184 using CXXDestructorDataPair = std::pair<DestructorPtr, void *>;
185 using CXXDestructorDataPairList = std::vector<CXXDestructorDataPair>;
186 CXXDestructorDataPairList DSOHandleOverride;
187 static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg,
188 void *DSOHandle);
189};
190
191class LocalCXXRuntimeOverrides : public LocalCXXRuntimeOverridesBase {
192public:
193 Error enable(JITDylib &JD, MangleAndInterner &Mangler);
194};
195
196/// An interface for Itanium __cxa_atexit interposer implementations.
197class ItaniumCXAAtExitSupport {
198public:
199 struct AtExitRecord {
200 void (*F)(void *);
201 void *Ctx;
202 };
203
204 void registerAtExit(void (*F)(void *), void *Ctx, void *DSOHandle);
205 void runAtExits(void *DSOHandle);
206
207private:
208 std::mutex AtExitsMutex;
209 DenseMap<void *, std::vector<AtExitRecord>> AtExitRecords;
210};
211
212/// A utility class to expose symbols found via dlsym to the JIT.
213///
214/// If an instance of this class is attached to a JITDylib as a fallback
215/// definition generator, then any symbol found in the given DynamicLibrary that
216/// passes the 'Allow' predicate will be added to the JITDylib.
217class DynamicLibrarySearchGenerator : public DefinitionGenerator {
218public:
219 using SymbolPredicate = std::function<bool(const SymbolStringPtr &)>;
220
221 /// Create a DynamicLibrarySearchGenerator that searches for symbols in the
222 /// given sys::DynamicLibrary.
223 ///
224 /// If the Allow predicate is given then only symbols matching the predicate
225 /// will be searched for. If the predicate is not given then all symbols will
226 /// be searched for.
227 DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix,
228 SymbolPredicate Allow = SymbolPredicate());
229
230 /// Permanently loads the library at the given path and, on success, returns
231 /// a DynamicLibrarySearchGenerator that will search it for symbol definitions
232 /// in the library. On failure returns the reason the library failed to load.
233 static Expected<std::unique_ptr<DynamicLibrarySearchGenerator>>
234 Load(const char *FileName, char GlobalPrefix,
235 SymbolPredicate Allow = SymbolPredicate());
236
237 /// Creates a DynamicLibrarySearchGenerator that searches for symbols in
238 /// the current process.
239 static Expected<std::unique_ptr<DynamicLibrarySearchGenerator>>
240 GetForCurrentProcess(char GlobalPrefix,
241 SymbolPredicate Allow = SymbolPredicate()) {
242 return Load(nullptr, GlobalPrefix, std::move(Allow));
243 }
244
245 Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
246 JITDylibLookupFlags JDLookupFlags,
247 const SymbolLookupSet &Symbols) override;
248
249private:
250 sys::DynamicLibrary Dylib;
251 SymbolPredicate Allow;
252 char GlobalPrefix;
253};
254
255/// A utility class to expose symbols from a static library.
256///
257/// If an instance of this class is attached to a JITDylib as a fallback
258/// definition generator, then any symbol found in the archive will result in
259/// the containing object being added to the JITDylib.
260class StaticLibraryDefinitionGenerator : public DefinitionGenerator {
261public:
262 // Interface builder function for objects loaded from this archive.
263 using GetObjectFileInterface =
264 unique_function<Expected<MaterializationUnit::Interface>(
265 ExecutionSession &ES, MemoryBufferRef ObjBuffer)>;
266
267 /// Try to create a StaticLibraryDefinitionGenerator from the given path.
268 ///
269 /// This call will succeed if the file at the given path is a static library
270 /// is a valid archive, otherwise it will return an error.
271 static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
272 Load(ObjectLayer &L, const char *FileName,
273 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
274
275 /// Try to create a StaticLibraryDefinitionGenerator from the given path.
276 ///
277 /// This call will succeed if the file at the given path is a static library
278 /// or a MachO universal binary containing a static library that is compatible
279 /// with the given triple. Otherwise it will return an error.
280 static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
281 Load(ObjectLayer &L, const char *FileName, const Triple &TT,
282 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
283
284 /// Try to create a StaticLibrarySearchGenerator from the given memory buffer.
285 /// This call will succeed if the buffer contains a valid archive, otherwise
286 /// it will return an error.
287 static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
288 Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
289 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
290
291 /// Returns a list of filenames of dynamic libraries that this archive has
292 /// imported. This class does not load these libraries by itself. User is
293 /// responsible for making sure these libraries are avaliable to the JITDylib.
294 const std::set<std::string> &getImportedDynamicLibraries() const {
295 return ImportedDynamicLibraries;
296 }
297
298 Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
299 JITDylibLookupFlags JDLookupFlags,
300 const SymbolLookupSet &Symbols) override;
301
302private:
303 StaticLibraryDefinitionGenerator(ObjectLayer &L,
304 std::unique_ptr<MemoryBuffer> ArchiveBuffer,
305 GetObjectFileInterface GetObjFileInterface,
306 Error &Err);
307
308 Error buildObjectFilesMap();
309
310 ObjectLayer &L;
311 GetObjectFileInterface GetObjFileInterface;
312 std::set<std::string> ImportedDynamicLibraries;
313 std::unique_ptr<MemoryBuffer> ArchiveBuffer;
314 std::unique_ptr<object::Archive> Archive;
315 DenseMap<SymbolStringPtr, MemoryBufferRef> ObjectFilesMap;
316};
317
318/// A utility class to create COFF dllimport GOT symbols (__imp_*) and PLT
319/// stubs.
320///
321/// If an instance of this class is attached to a JITDylib as a fallback
322/// definition generator, PLT stubs and dllimport __imp_ symbols will be
323/// generated for external symbols found outside the given jitdylib. Currently
324/// only supports x86_64 architecture.
325class DLLImportDefinitionGenerator : public DefinitionGenerator {
326public:
327 /// Creates a DLLImportDefinitionGenerator instance.
328 static std::unique_ptr<DLLImportDefinitionGenerator>
329 Create(ExecutionSession &ES, ObjectLinkingLayer &L);
330
331 Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
332 JITDylibLookupFlags JDLookupFlags,
333 const SymbolLookupSet &Symbols) override;
334
335private:
336 DLLImportDefinitionGenerator(ExecutionSession &ES, ObjectLinkingLayer &L)
337 : ES(ES), L(L) {}
338
339 static Expected<unsigned> getTargetPointerSize(const Triple &TT);
340 static Expected<support::endianness> getTargetEndianness(const Triple &TT);
341 Expected<std::unique_ptr<jitlink::LinkGraph>>
342 createStubsGraph(const SymbolMap &Resolved);
343
344 static StringRef getImpPrefix() { return "__imp_"; }
345
346 static StringRef getSectionName() { return "$__DLLIMPORT_STUBS"; }
347
348 ExecutionSession &ES;
349 ObjectLinkingLayer &L;
350};
351
352} // end namespace orc
353} // end namespace llvm
354
355#endif // LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H