LLVM 20.0.0git
ExecutionUtils.cpp
Go to the documentation of this file.
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
17#include "llvm/IR/Constants.h"
18#include "llvm/IR/Function.h"
20#include "llvm/IR/Module.h"
25#include <string>
26
27namespace llvm {
28namespace orc {
29
31 : InitList(
32 GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
33 I((InitList && End) ? InitList->getNumOperands() : 0) {
34}
35
37 assert(InitList == Other.InitList && "Incomparable iterators.");
38 return I == Other.I;
39}
40
42 return !(*this == Other);
43}
44
46 ++I;
47 return *this;
48}
49
51 CtorDtorIterator Temp = *this;
52 ++I;
53 return Temp;
54}
55
57 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(I));
58 assert(CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors");
59
60 Constant *FuncC = CS->getOperand(1);
61 Function *Func = nullptr;
62
63 // Extract function pointer, pulling off any casts.
64 while (FuncC) {
65 if (Function *F = dyn_cast_or_null<Function>(FuncC)) {
66 Func = F;
67 break;
68 } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
69 if (CE->isCast())
70 FuncC = CE->getOperand(0);
71 else
72 break;
73 } else {
74 // This isn't anything we recognize. Bail out with Func left set to null.
75 break;
76 }
77 }
78
79 auto *Priority = cast<ConstantInt>(CS->getOperand(0));
80 Value *Data = CS->getNumOperands() == 3 ? CS->getOperand(2) : nullptr;
81 if (Data && !isa<GlobalValue>(Data))
82 Data = nullptr;
83 return Element(Priority->getZExtValue(), Func, Data);
84}
85
87 const GlobalVariable *CtorsList = M.getNamedGlobal("llvm.global_ctors");
88 return make_range(CtorDtorIterator(CtorsList, false),
89 CtorDtorIterator(CtorsList, true));
90}
91
93 const GlobalVariable *DtorsList = M.getNamedGlobal("llvm.global_dtors");
94 return make_range(CtorDtorIterator(DtorsList, false),
95 CtorDtorIterator(DtorsList, true));
96}
97
98bool StaticInitGVIterator::isStaticInitGlobal(GlobalValue &GV) {
99 if (GV.isDeclaration())
100 return false;
101
102 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
103 GV.getName() == "llvm.global_dtors"))
104 return true;
105
106 if (ObjFmt == Triple::MachO) {
107 // FIXME: These section checks are too strict: We should match first and
108 // second word split by comma.
109 if (GV.hasSection() &&
110 (GV.getSection().starts_with("__DATA,__objc_classlist") ||
111 GV.getSection().starts_with("__DATA,__objc_selrefs")))
112 return true;
113 }
114
115 return false;
116}
117
119 if (CtorDtors.empty())
120 return;
121
122 MangleAndInterner Mangle(
124 (*CtorDtors.begin()).Func->getDataLayout());
125
126 for (auto CtorDtor : CtorDtors) {
127 assert(CtorDtor.Func && CtorDtor.Func->hasName() &&
128 "Ctor/Dtor function must be named to be runnable under the JIT");
129
130 // FIXME: Maybe use a symbol promoter here instead.
131 if (CtorDtor.Func->hasLocalLinkage()) {
132 CtorDtor.Func->setLinkage(GlobalValue::ExternalLinkage);
133 CtorDtor.Func->setVisibility(GlobalValue::HiddenVisibility);
134 }
135
136 if (CtorDtor.Data && cast<GlobalValue>(CtorDtor.Data)->isDeclaration()) {
137 dbgs() << " Skipping because why now?\n";
138 continue;
139 }
140
141 CtorDtorsByPriority[CtorDtor.Priority].push_back(
142 Mangle(CtorDtor.Func->getName()));
143 }
144}
145
147 using CtorDtorTy = void (*)();
148
149 SymbolLookupSet LookupSet;
150 for (auto &KV : CtorDtorsByPriority)
151 for (auto &Name : KV.second)
152 LookupSet.add(Name);
153 assert(!LookupSet.containsDuplicates() &&
154 "Ctor/Dtor list contains duplicates");
155
156 auto &ES = JD.getExecutionSession();
157 if (auto CtorDtorMap = ES.lookup(
159 std::move(LookupSet))) {
160 for (auto &KV : CtorDtorsByPriority) {
161 for (auto &Name : KV.second) {
162 assert(CtorDtorMap->count(Name) && "No entry for Name");
163 auto CtorDtor = (*CtorDtorMap)[Name].getAddress().toPtr<CtorDtorTy>();
164 CtorDtor();
165 }
166 }
167 CtorDtorsByPriority.clear();
168 return Error::success();
169 } else
170 return CtorDtorMap.takeError();
171}
172
174 auto& CXXDestructorDataPairs = DSOHandleOverride;
175 for (auto &P : CXXDestructorDataPairs)
176 P.first(P.second);
177 CXXDestructorDataPairs.clear();
178}
179
181 void *Arg,
182 void *DSOHandle) {
183 auto& CXXDestructorDataPairs =
184 *reinterpret_cast<CXXDestructorDataPairList*>(DSOHandle);
185 CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
186 return 0;
187}
188
190 MangleAndInterner &Mangle) {
191 SymbolMap RuntimeInterposes;
192 RuntimeInterposes[Mangle("__dso_handle")] = {
194 RuntimeInterposes[Mangle("__cxa_atexit")] = {
196
197 return JD.define(absoluteSymbols(std::move(RuntimeInterposes)));
198}
199
200void ItaniumCXAAtExitSupport::registerAtExit(void (*F)(void *), void *Ctx,
201 void *DSOHandle) {
202 std::lock_guard<std::mutex> Lock(AtExitsMutex);
203 AtExitRecords[DSOHandle].push_back({F, Ctx});
204}
205
207 std::vector<AtExitRecord> AtExitsToRun;
208
209 {
210 std::lock_guard<std::mutex> Lock(AtExitsMutex);
211 auto I = AtExitRecords.find(DSOHandle);
212 if (I != AtExitRecords.end()) {
213 AtExitsToRun = std::move(I->second);
214 AtExitRecords.erase(I);
215 }
216 }
217
218 while (!AtExitsToRun.empty()) {
219 AtExitsToRun.back().F(AtExitsToRun.back().Ctx);
220 AtExitsToRun.pop_back();
221 }
222}
223
226 AddAbsoluteSymbolsFn AddAbsoluteSymbols)
227 : Dylib(std::move(Dylib)), Allow(std::move(Allow)),
228 AddAbsoluteSymbols(std::move(AddAbsoluteSymbols)),
230
233 SymbolPredicate Allow,
234 AddAbsoluteSymbolsFn AddAbsoluteSymbols) {
235 std::string ErrMsg;
236 auto Lib = sys::DynamicLibrary::getPermanentLibrary(FileName, &ErrMsg);
237 if (!Lib.isValid())
238 return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
239 return std::make_unique<DynamicLibrarySearchGenerator>(
240 std::move(Lib), GlobalPrefix, std::move(Allow),
241 std::move(AddAbsoluteSymbols));
242}
243
245 LookupState &LS, LookupKind K, JITDylib &JD,
246 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
247 orc::SymbolMap NewSymbols;
248
249 bool HasGlobalPrefix = (GlobalPrefix != '\0');
250
251 for (auto &KV : Symbols) {
252 auto &Name = KV.first;
253
254 if ((*Name).empty())
255 continue;
256
257 if (Allow && !Allow(Name))
258 continue;
259
260 if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
261 continue;
262
263 std::string Tmp((*Name).data() + HasGlobalPrefix,
264 (*Name).size() - HasGlobalPrefix);
265 if (void *P = Dylib.getAddressOfSymbol(Tmp.c_str()))
267 }
268
269 if (NewSymbols.empty())
270 return Error::success();
271
272 if (AddAbsoluteSymbols)
273 return AddAbsoluteSymbols(JD, std::move(NewSymbols));
274 return JD.define(absoluteSymbols(std::move(NewSymbols)));
275}
276
279 JITDylib &JD) {
280 return [&](MemoryBufferRef Buf) -> Error {
281 switch (identify_magic(Buf.getBuffer())) {
285 return L.add(JD, MemoryBuffer::getMemBuffer(Buf));
286 default:
287 return Error::success();
288 }
289 };
290}
291
294 ObjectLayer &L, const char *FileName, VisitMembersFunction VisitMembers,
295 GetObjectFileInterface GetObjFileInterface) {
296
297 const auto &TT = L.getExecutionSession().getTargetTriple();
298 auto Linkable = loadLinkableFile(FileName, TT, LoadArchives::Required);
299 if (!Linkable)
300 return Linkable.takeError();
301
302 return Create(L, std::move(Linkable->first), std::move(VisitMembers),
303 std::move(GetObjFileInterface));
304}
305
308 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
309 std::unique_ptr<object::Archive> Archive, VisitMembersFunction VisitMembers,
310 GetObjectFileInterface GetObjFileInterface) {
311
312 Error Err = Error::success();
313
314 if (VisitMembers) {
315 for (auto Child : Archive->children(Err)) {
316 if (auto ChildBuf = Child.getMemoryBufferRef()) {
317 if (auto Err2 = VisitMembers(*ChildBuf))
318 return std::move(Err2);
319 } else {
320 // We silently allow non-object archive members. This matches the
321 // behavior of ld.
322 consumeError(ChildBuf.takeError());
323 }
324 }
325 if (Err)
326 return std::move(Err);
327 }
328
329 std::unique_ptr<StaticLibraryDefinitionGenerator> ADG(
331 L, std::move(ArchiveBuffer), std::move(Archive),
332 std::move(GetObjFileInterface), Err));
333
334 if (Err)
335 return std::move(Err);
336
337 return std::move(ADG);
338}
339
342 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
343 VisitMembersFunction VisitMembers,
344 GetObjectFileInterface GetObjFileInterface) {
345
346 auto B = object::createBinary(ArchiveBuffer->getMemBufferRef());
347 if (!B)
348 return B.takeError();
349
350 // If this is a regular archive then create an instance from it.
351 if (isa<object::Archive>(*B))
352 return Create(L, std::move(ArchiveBuffer),
353 std::unique_ptr<object::Archive>(
354 static_cast<object::Archive *>(B->release())),
355 std::move(VisitMembers), std::move(GetObjFileInterface));
356
357 // If this is a universal binary then search for a slice matching the given
358 // Triple.
359 if (auto *UB = dyn_cast<object::MachOUniversalBinary>(B->get())) {
360
361 const auto &TT = L.getExecutionSession().getTargetTriple();
362
363 auto SliceRange = getMachOSliceRangeForTriple(*UB, TT);
364 if (!SliceRange)
365 return SliceRange.takeError();
366
367 MemoryBufferRef SliceRef(
368 StringRef(ArchiveBuffer->getBufferStart() + SliceRange->first,
369 SliceRange->second),
370 ArchiveBuffer->getBufferIdentifier());
371
372 auto Archive = object::Archive::create(SliceRef);
373 if (!Archive)
374 return Archive.takeError();
375
376 return Create(L, std::move(ArchiveBuffer), std::move(*Archive),
377 std::move(VisitMembers), std::move(GetObjFileInterface));
378 }
379
380 return make_error<StringError>(Twine("Unrecognized file type for ") +
381 ArchiveBuffer->getBufferIdentifier(),
383}
384
386 LookupState &LS, LookupKind K, JITDylib &JD,
387 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
388 // Don't materialize symbols from static archives unless this is a static
389 // lookup.
390 if (K != LookupKind::Static)
391 return Error::success();
392
393 // Bail out early if we've already freed the archive.
394 if (!Archive)
395 return Error::success();
396
398
399 for (const auto &KV : Symbols) {
400 const auto &Name = KV.first;
401 if (!ObjectFilesMap.count(Name))
402 continue;
403 auto ChildBuffer = ObjectFilesMap[Name];
404 ChildBufferInfos.insert(
405 {ChildBuffer.getBuffer(), ChildBuffer.getBufferIdentifier()});
406 }
407
408 for (auto ChildBufferInfo : ChildBufferInfos) {
409 MemoryBufferRef ChildBufferRef(ChildBufferInfo.first,
410 ChildBufferInfo.second);
411
412 auto I = GetObjFileInterface(L.getExecutionSession(), ChildBufferRef);
413 if (!I)
414 return I.takeError();
415
416 if (auto Err = L.add(JD, MemoryBuffer::getMemBuffer(ChildBufferRef, false),
417 std::move(*I)))
418 return Err;
419 }
420
421 return Error::success();
422}
423
424Error StaticLibraryDefinitionGenerator::buildObjectFilesMap() {
426 DenseSet<uint64_t> Visited;
427 DenseSet<uint64_t> Excluded;
428 StringSaver FileNames(ObjFileNameStorage);
429 for (auto &S : Archive->symbols()) {
430 StringRef SymName = S.getName();
431 auto Member = S.getMember();
432 if (!Member)
433 return Member.takeError();
434 auto DataOffset = Member->getDataOffset();
435 if (!Visited.count(DataOffset)) {
436 Visited.insert(DataOffset);
437 auto Child = Member->getAsBinary();
438 if (!Child)
439 return Child.takeError();
440 if ((*Child)->isCOFFImportFile()) {
441 ImportedDynamicLibraries.insert((*Child)->getFileName().str());
442 Excluded.insert(DataOffset);
443 continue;
444 }
445
446 // Give members of the archive a name that contains the archive path so
447 // that they can be differentiated from a member with the same name in a
448 // different archive. This also ensure initializer symbols names will be
449 // unique within a JITDylib.
450 StringRef FullName = FileNames.save(Archive->getFileName() + "(" +
451 (*Child)->getFileName() + ")");
452 MemoryBufferRef MemBuffer((*Child)->getMemoryBufferRef().getBuffer(),
453 FullName);
454
455 MemoryBuffers[DataOffset] = MemBuffer;
456 }
457 if (!Excluded.count(DataOffset))
458 ObjectFilesMap[L.getExecutionSession().intern(SymName)] =
459 MemoryBuffers[DataOffset];
460 }
461
462 return Error::success();
463}
464
465StaticLibraryDefinitionGenerator::StaticLibraryDefinitionGenerator(
466 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
467 std::unique_ptr<object::Archive> Archive,
468 GetObjectFileInterface GetObjFileInterface, Error &Err)
469 : L(L), GetObjFileInterface(std::move(GetObjFileInterface)),
470 ArchiveBuffer(std::move(ArchiveBuffer)), Archive(std::move(Archive)) {
471 ErrorAsOutParameter _(Err);
472 if (!this->GetObjFileInterface)
473 this->GetObjFileInterface = getObjectFileInterface;
474 if (!Err)
475 Err = buildObjectFilesMap();
476}
477
478std::unique_ptr<DLLImportDefinitionGenerator>
481 return std::unique_ptr<DLLImportDefinitionGenerator>(
483}
484
486 LookupState &LS, LookupKind K, JITDylib &JD,
487 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
488 JITDylibSearchOrder LinkOrder;
489 JD.withLinkOrderDo([&](const JITDylibSearchOrder &LO) {
490 LinkOrder.reserve(LO.size());
491 for (auto &KV : LO) {
492 if (KV.first == &JD)
493 continue;
494 LinkOrder.push_back(KV);
495 }
496 });
497
498 // FIXME: if regular symbol name start with __imp_ we have to issue lookup of
499 // both __imp_ and stripped name and use the lookup information to resolve the
500 // real symbol name.
501 SymbolLookupSet LookupSet;
503 for (auto &KV : Symbols) {
504 StringRef Deinterned = *KV.first;
505 if (Deinterned.starts_with(getImpPrefix()))
506 Deinterned = Deinterned.drop_front(StringRef(getImpPrefix()).size());
507 // Don't degrade the required state
508 if (ToLookUpSymbols.count(Deinterned) &&
509 ToLookUpSymbols[Deinterned] == SymbolLookupFlags::RequiredSymbol)
510 continue;
511 ToLookUpSymbols[Deinterned] = KV.second;
512 }
513
514 for (auto &KV : ToLookUpSymbols)
515 LookupSet.add(ES.intern(KV.first), KV.second);
516
517 auto Resolved =
518 ES.lookup(LinkOrder, LookupSet, LookupKind::DLSym, SymbolState::Resolved);
519 if (!Resolved)
520 return Resolved.takeError();
521
522 auto G = createStubsGraph(*Resolved);
523 if (!G)
524 return G.takeError();
525 return L.add(JD, std::move(*G));
526}
527
529DLLImportDefinitionGenerator::getTargetPointerSize(const Triple &TT) {
530 switch (TT.getArch()) {
531 case Triple::x86_64:
532 return 8;
533 default:
534 return make_error<StringError>(
535 "architecture unsupported by DLLImportDefinitionGenerator",
537 }
538}
539
540Expected<llvm::endianness>
541DLLImportDefinitionGenerator::getEndianness(const Triple &TT) {
542 switch (TT.getArch()) {
543 case Triple::x86_64:
545 default:
546 return make_error<StringError>(
547 "architecture unsupported by DLLImportDefinitionGenerator",
549 }
550}
551
552Expected<std::unique_ptr<jitlink::LinkGraph>>
553DLLImportDefinitionGenerator::createStubsGraph(const SymbolMap &Resolved) {
554 Triple TT = ES.getTargetTriple();
555 auto PointerSize = getTargetPointerSize(TT);
556 if (!PointerSize)
557 return PointerSize.takeError();
558 auto Endianness = getEndianness(TT);
559 if (!Endianness)
560 return Endianness.takeError();
561
562 auto G = std::make_unique<jitlink::LinkGraph>(
563 "<DLLIMPORT_STUBS>", ES.getSymbolStringPool(), TT, *PointerSize,
565 jitlink::Section &Sec =
566 G->createSection(getSectionName(), MemProt::Read | MemProt::Exec);
567
568 for (auto &KV : Resolved) {
569 jitlink::Symbol &Target = G->addAbsoluteSymbol(
570 *KV.first, KV.second.getAddress(), *PointerSize,
572
573 // Create __imp_ symbol
574 jitlink::Symbol &Ptr =
576 Ptr.setName(G->intern((Twine(getImpPrefix()) + *KV.first).str()));
577 Ptr.setLinkage(jitlink::Linkage::Strong);
579
580 // Create PLT stub
581 // FIXME: check PLT stub of data symbol is not accessed
582 jitlink::Block &StubBlock =
584 G->addDefinedSymbol(StubBlock, 0, *KV.first, StubBlock.getSize(),
586 false);
587 }
588
589 return std::move(G);
590}
591
592} // End namespace orc.
593} // End namespace llvm.
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
@ GlobalPrefix
Definition: AsmWriter.cpp:375
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::string Name
bool End
Definition: ELF_riscv.cpp:480
#define _
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ConstantArray - Constant Array Declarations.
Definition: Constants.h:427
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1108
This is an important base class in LLVM.
Definition: Constant.h:42
bool empty() const
Definition: DenseMap.h:98
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:152
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:296
StringRef getSection() const
Definition: Globals.cpp:189
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
bool hasSection() const
Definition: GlobalValue.h:290
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:265
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:609
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
Value * getOperand(unsigned i) const
Definition: User.h:228
unsigned getNumOperands() const
Definition: User.h:250
LLVM Value Representation.
Definition: Value.h:74
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:95
A range adaptor for a pair of iterators.
IteratorT begin() const
static Expected< std::unique_ptr< Archive > > create(MemoryBufferRef Source)
Definition: Archive.cpp:668
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm....
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
Element operator*() const
Dereference iterator.
CtorDtorIterator(const GlobalVariable *GV, bool End)
Construct an iterator instance.
CtorDtorIterator & operator++()
Pre-increment iterator.
bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
void add(iterator_range< CtorDtorIterator > CtorDtors)
A utility class to create COFF dllimport GOT symbols (__imp_*) and PLT stubs.
static std::unique_ptr< DLLImportDefinitionGenerator > Create(ExecutionSession &ES, ObjectLinkingLayer &L)
Creates a DLLImportDefinitionGenerator instance.
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Create a DynamicLibrarySearchGenerator that searches for symbols in the given sys::DynamicLibrary.
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > Load(const char *FileName, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Permanently loads the library at the given path and, on success, returns a DynamicLibrarySearchGenera...
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
An ExecutionSession represents a running JIT program.
Definition: Core.h:1339
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition: Core.h:1382
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1393
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition: Core.h:1388
void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition: Core.cpp:1788
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
void registerAtExit(void(*F)(void *), void *Ctx, void *DSOHandle)
Represents a JIT'd dynamic library.
Definition: Core.h:897
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition: Core.h:1822
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition: Core.h:916
auto withLinkOrderDo(Func &&F) -> decltype(F(std::declval< const JITDylibSearchOrder & >()))
Do something with the link order (run under the session lock).
Definition: Core.h:1815
static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
CXXDestructorDataPairList DSOHandleOverride
void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
Error enable(JITDylib &JD, MangleAndInterner &Mangler)
Wraps state for a lookup-in-progress.
Definition: Core.h:829
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Mangling.h:26
Interface for Layers that accept object files.
Definition: Layer.h:133
virtual Error add(ResourceTrackerSP RT, std::unique_ptr< MemoryBuffer > O, MaterializationUnit::Interface I)
Adds a MaterializationUnit for the object file in the given memory buffer to the JITDylib for the giv...
Definition: Layer.cpp:170
ExecutionSession & getExecutionSession()
Returns the execution session for this layer.
Definition: Layer.h:141
An ObjectLayer implementation built on JITLink.
A utility class to expose symbols from a static library.
static VisitMembersFunction loadAllObjectFileMembers(ObjectLayer &L, JITDylib &JD)
A VisitMembersFunction that unconditionally loads all object files from the archive.
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Create(ObjectLayer &L, std::unique_ptr< MemoryBuffer > ArchiveBuffer, std::unique_ptr< object::Archive > Archive, VisitMembersFunction VisitMembers=VisitMembersFunction(), GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibrarySearchGenerator from the given memory buffer and Archive object.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName, VisitMembersFunction VisitMembers=VisitMembersFunction(), GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibraryDefinitionGenerator from the given path.
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:194
SymbolLookupSet & add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
Definition: Core.h:260
bool containsDuplicates()
Returns true if this set contains any duplicates.
Definition: Core.h:387
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
static DynamicLibrary getPermanentLibrary(const char *filename, std::string *errMsg=nullptr)
This function permanently loads the dynamic library at the given path using the library load operatio...
void * getAddressOfSymbol(const char *symbolName)
Searches through the library for the symbol symbolName.
constexpr llvm::endianness Endianness
The endianness of all multi-byte encoded values in MessagePack.
Definition: MsgPack.h:24
Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
Definition: Binary.cpp:45
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Definition: Core.h:177
Expected< std::pair< std::unique_ptr< MemoryBuffer >, LinkableFileKind > > loadLinkableFile(StringRef Path, const Triple &TT, LoadArchives LA, std::optional< StringRef > IdentifierOverride=std::nullopt)
Create a MemoryBuffer covering the "linkable" part of the given path.
iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition: Core.h:173
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:146
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
Expected< MaterializationUnit::Interface > getObjectFileInterface(ExecutionSession &ES, MemoryBufferRef ObjBuffer)
Returns a MaterializationUnit::Interface for the object file contained in the given buffer,...
Expected< std::pair< size_t, size_t > > getMachOSliceRangeForTriple(object::MachOUniversalBinary &UB, const Triple &TT)
Utility for identifying the file-slice compatible with TT in a universal binary.
Definition: MachO.cpp:202
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:168
@ Resolved
Queried, materialization begun.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Magic.cpp:33
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1697
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto dyn_cast_or_null(const Y &Val)
Definition: Casting.h:759
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
@ Other
Any other memory.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
@ elf_relocatable
ELF Relocatable object file.
Definition: Magic.h:27
@ macho_object
Mach-O Object file.
Definition: Magic.h:32
@ coff_object
COFF object file.
Definition: Magic.h:47
Accessor for an element of the global_ctors/global_dtors array.