16 #ifndef LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H
17 #define LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H
43 #define DEBUG_TYPE "orc-remote"
56 template <
typename ChannelT>
63 : Client(Client), Id(Id) {
64 DEBUG(
dbgs() <<
"Created remote allocator " << Id <<
"\n");
73 Client.destroyRemoteAllocator(Id);
74 DEBUG(
dbgs() <<
"Destroyed remote allocator " << Id <<
"\n");
80 Unmapped.back().CodeAllocs.emplace_back(Size, Alignment);
81 uint8_t *
Alloc =
reinterpret_cast<uint8_t *
>(
82 Unmapped.back().CodeAllocs.back().getLocalAddress());
83 DEBUG(
dbgs() <<
"Allocator " << Id <<
" allocated code for "
84 << SectionName <<
": " << Alloc <<
" (" << Size
85 <<
" bytes, alignment " << Alignment <<
")\n");
91 bool IsReadOnly)
override {
93 Unmapped.back().RODataAllocs.emplace_back(Size, Alignment);
94 uint8_t *
Alloc =
reinterpret_cast<uint8_t *
>(
95 Unmapped.back().RODataAllocs.back().getLocalAddress());
96 DEBUG(
dbgs() <<
"Allocator " << Id <<
" allocated ro-data for "
97 << SectionName <<
": " << Alloc <<
" (" << Size
98 <<
" bytes, alignment " << Alignment <<
")\n");
102 Unmapped.back().RWDataAllocs.emplace_back(Size, Alignment);
103 uint8_t *
Alloc =
reinterpret_cast<uint8_t *
>(
104 Unmapped.back().RWDataAllocs.back().getLocalAddress());
105 DEBUG(
dbgs() <<
"Allocator " << Id <<
" allocated rw-data for "
106 << SectionName <<
": " << Alloc <<
" (" << Size
107 <<
" bytes, alignment " << Alignment <<
")\n");
112 uintptr_t RODataSize,
uint32_t RODataAlign,
113 uintptr_t RWDataSize,
115 Unmapped.push_back(ObjectAllocs());
117 DEBUG(
dbgs() <<
"Allocator " << Id <<
" reserved:\n");
120 if (
auto AddrOrErr = Client.reserveMem(Id, CodeSize, CodeAlign))
121 Unmapped.back().RemoteCodeAddr = *AddrOrErr;
124 assert(!AddrOrErr.takeError() &&
"Failed reserving remote memory.");
128 <<
format(
"0x%016x", Unmapped.back().RemoteCodeAddr)
129 <<
" (" << CodeSize <<
" bytes, alignment " << CodeAlign
133 if (RODataSize != 0) {
134 if (
auto AddrOrErr = Client.reserveMem(Id, RODataSize, RODataAlign))
135 Unmapped.back().RemoteRODataAddr = *AddrOrErr;
138 assert(!AddrOrErr.takeError() &&
"Failed reserving remote memory.");
142 <<
format(
"0x%016x", Unmapped.back().RemoteRODataAddr)
143 <<
" (" << RODataSize <<
" bytes, alignment "
144 << RODataAlign <<
")\n");
147 if (RWDataSize != 0) {
148 if (
auto AddrOrErr = Client.reserveMem(Id, RWDataSize, RWDataAlign))
149 Unmapped.back().RemoteRWDataAddr = *AddrOrErr;
152 assert(!AddrOrErr.takeError() &&
"Failed reserving remote memory.");
156 <<
format(
"0x%016x", Unmapped.back().RemoteRWDataAddr)
157 <<
" (" << RWDataSize <<
" bytes, alignment "
158 << RWDataAlign <<
")\n");
165 size_t Size)
override {
166 UnfinalizedEHFrames.push_back({LoadAddr, Size});
170 for (
auto &Frame : RegisteredEHFrames) {
171 auto Err = Client.deregisterEHFrames(Frame.Addr, Frame.Size);
173 assert(!Err &&
"Failed to register remote EH frames.");
180 DEBUG(
dbgs() <<
"Allocator " << Id <<
" applied mappings:\n");
181 for (
auto &ObjAllocs : Unmapped) {
184 for (
auto &
Alloc : ObjAllocs.CodeAllocs) {
188 << static_cast<void *>(
Alloc.getLocalAddress())
189 <<
" -> " <<
format(
"0x%016x", NextCodeAddr) <<
"\n");
190 Alloc.setRemoteAddress(NextCodeAddr);
191 NextCodeAddr +=
Alloc.getSize();
196 for (
auto &
Alloc : ObjAllocs.RODataAllocs) {
197 NextRODataAddr =
alignTo(NextRODataAddr,
Alloc.getAlign());
200 << static_cast<void *>(
Alloc.getLocalAddress())
201 <<
" -> " <<
format(
"0x%016x", NextRODataAddr)
203 Alloc.setRemoteAddress(NextRODataAddr);
204 NextRODataAddr +=
Alloc.getSize();
209 for (
auto &
Alloc : ObjAllocs.RWDataAllocs) {
210 NextRWDataAddr =
alignTo(NextRWDataAddr,
Alloc.getAlign());
213 << static_cast<void *>(
Alloc.getLocalAddress())
214 <<
" -> " <<
format(
"0x%016x", NextRWDataAddr)
216 Alloc.setRemoteAddress(NextRWDataAddr);
217 NextRWDataAddr +=
Alloc.getSize();
220 Unfinalized.push_back(std::move(ObjAllocs));
226 DEBUG(
dbgs() <<
"Allocator " << Id <<
" finalizing:\n");
228 for (
auto &ObjAllocs : Unfinalized) {
229 for (
auto &
Alloc : ObjAllocs.CodeAllocs) {
231 << static_cast<void *>(
Alloc.getLocalAddress()) <<
" -> "
232 <<
format(
"0x%016x",
Alloc.getRemoteAddress()) <<
" ("
233 <<
Alloc.getSize() <<
" bytes)\n");
235 Client.writeMem(
Alloc.getRemoteAddress(),
248 if (ObjAllocs.RemoteCodeAddr) {
249 DEBUG(
dbgs() <<
" setting R-X permissions on code block: "
250 <<
format(
"0x%016x", ObjAllocs.RemoteCodeAddr) <<
"\n");
251 if (
auto Err = Client.setProtections(Id, ObjAllocs.RemoteCodeAddr,
265 for (
auto &
Alloc : ObjAllocs.RODataAllocs) {
267 << static_cast<void *>(
Alloc.getLocalAddress()) <<
" -> "
268 <<
format(
"0x%016x",
Alloc.getRemoteAddress()) <<
" ("
269 <<
Alloc.getSize() <<
" bytes)\n");
271 Client.writeMem(
Alloc.getRemoteAddress(),
284 if (ObjAllocs.RemoteRODataAddr) {
285 DEBUG(
dbgs() <<
" setting R-- permissions on ro-data block: "
286 <<
format(
"0x%016x", ObjAllocs.RemoteRODataAddr)
288 if (
auto Err = Client.setProtections(Id, ObjAllocs.RemoteRODataAddr,
301 for (
auto &
Alloc : ObjAllocs.RWDataAllocs) {
303 << static_cast<void *>(
Alloc.getLocalAddress()) <<
" -> "
304 <<
format(
"0x%016x",
Alloc.getRemoteAddress()) <<
" ("
305 <<
Alloc.getSize() <<
" bytes)\n");
307 Client.writeMem(
Alloc.getRemoteAddress(),
320 if (ObjAllocs.RemoteRWDataAddr) {
321 DEBUG(
dbgs() <<
" setting RW- permissions on rw-data block: "
322 <<
format(
"0x%016x", ObjAllocs.RemoteRWDataAddr)
324 if (
auto Err = Client.setProtections(Id, ObjAllocs.RemoteRWDataAddr,
340 for (
auto &EHFrame : UnfinalizedEHFrames) {
341 if (
auto Err = Client.registerEHFrames(EHFrame.Addr, EHFrame.Size)) {
352 RegisteredEHFrames = std::move(UnfinalizedEHFrames);
353 UnfinalizedEHFrames = {};
362 : Size(Size), Align(Align), Contents(new
char[Size + Align - 1]) {}
369 uint64_t getSize()
const {
return Size; }
373 char *getLocalAddress()
const {
374 uintptr_t LocalAddr =
reinterpret_cast<uintptr_t
>(Contents.get());
376 return reinterpret_cast<char *
>(LocalAddr);
380 this->RemoteAddr = RemoteAddr;
388 std::unique_ptr<char[]> Contents;
392 struct ObjectAllocs {
393 ObjectAllocs() =
default;
394 ObjectAllocs(
const ObjectAllocs &) =
delete;
395 ObjectAllocs &
operator=(
const ObjectAllocs &) =
delete;
396 ObjectAllocs(ObjectAllocs &&) =
default;
397 ObjectAllocs &
operator=(ObjectAllocs &&) =
default;
402 std::vector<Alloc> CodeAllocs, RODataAllocs, RWDataAllocs;
405 OrcRemoteTargetClient &Client;
407 std::vector<ObjectAllocs> Unmapped;
408 std::vector<ObjectAllocs> Unfinalized;
414 std::vector<EHFrame> UnfinalizedEHFrames;
415 std::vector<EHFrame> RegisteredEHFrames;
423 : Remote(Remote), Id(Id) {}
426 if (
auto Err = Remote.destroyIndirectStubsManager(Id)) {
434 if (
auto Err = reserveStubs(1))
437 return createStubInternal(StubName, StubAddr, StubFlags);
441 if (
auto Err = reserveStubs(StubInits.
size()))
444 for (
auto &Entry : StubInits)
445 if (
auto Err = createStubInternal(Entry.first(), Entry.second.first,
446 Entry.second.second))
453 auto I = StubIndexes.find(Name);
454 if (
I == StubIndexes.end())
456 auto Key =
I->second.first;
457 auto Flags =
I->second.second;
459 if (ExportedStubsOnly && !StubSymbol.getFlags().isExported())
465 auto I = StubIndexes.find(Name);
466 if (
I == StubIndexes.end())
468 auto Key =
I->second.first;
469 auto Flags =
I->second.second;
474 auto I = StubIndexes.find(Name);
475 assert(
I != StubIndexes.end() &&
"No stub pointer for symbol");
476 auto Key =
I->second.first;
477 return Remote.writePointer(getPtrAddr(Key), NewAddr);
481 struct RemoteIndirectStubsInfo {
489 std::vector<RemoteIndirectStubsInfo> RemoteIndirectStubsInfos;
490 using StubKey = std::pair<uint16_t, uint16_t>;
491 std::vector<StubKey> FreeStubs;
494 Error reserveStubs(
unsigned NumStubs) {
495 if (NumStubs <= FreeStubs.size())
498 unsigned NewStubsRequired = NumStubs - FreeStubs.size();
501 unsigned NumStubsEmitted;
503 if (
auto StubInfoOrErr = Remote.emitIndirectStubs(Id, NewStubsRequired))
504 std::tie(StubBase, PtrBase, NumStubsEmitted) = *StubInfoOrErr;
506 return StubInfoOrErr.takeError();
508 unsigned NewBlockId = RemoteIndirectStubsInfos.size();
509 RemoteIndirectStubsInfos.push_back({StubBase, PtrBase, NumStubsEmitted});
511 for (
unsigned I = 0;
I < NumStubsEmitted; ++
I)
512 FreeStubs.push_back(std::make_pair(NewBlockId,
I));
519 auto Key = FreeStubs.back();
520 FreeStubs.pop_back();
521 StubIndexes[StubName] = std::make_pair(Key, StubFlags);
522 return Remote.writePointer(getPtrAddr(Key), InitAddr);
526 assert(RemoteIndirectStubsInfos[K.first].StubBase != 0 &&
527 "Missing stub address");
528 return RemoteIndirectStubsInfos[K.first].StubBase +
529 K.second * Remote.getIndirectStubSize();
533 assert(RemoteIndirectStubsInfos[K.first].PtrBase != 0 &&
534 "Missing pointer address");
535 return RemoteIndirectStubsInfos[K.first].PtrBase +
536 K.second * Remote.getPointerSize();
548 void grow()
override {
551 if (
auto TrampolineInfoOrErr = Remote.emitTrampolineBlock())
552 std::tie(BlockAddr, NumTrampolines) = *TrampolineInfoOrErr;
558 uint32_t TrampolineSize = Remote.getTrampolineSize();
559 for (
unsigned I = 0;
I < NumTrampolines; ++
I)
563 OrcRemoteTargetClient &Remote;
572 std::unique_ptr<OrcRemoteTargetClient> Client(
575 return std::move(Err);
576 return std::move(Client);
582 DEBUG(
dbgs() <<
"Calling int(*)(void) " <<
format(
"0x%016x", Addr) <<
"\n");
583 return callB<CallIntVoid>(Addr);
589 const std::vector<std::string> &
Args) {
590 DEBUG(
dbgs() <<
"Calling int(*)(int, char*[]) " <<
format(
"0x%016x", Addr)
592 return callB<CallMain>(Addr,
Args);
600 return callB<CallVoidVoid>(Addr);
606 assert(!MM &&
"MemoryManager should be null before creation.");
609 if (
auto Err = callB<CreateRemoteAllocator>(
Id))
611 MM = llvm::make_unique<RCMemoryManager>(*
this,
Id);
618 assert(!I &&
"Indirect stubs manager should be null before creation.");
619 auto Id = IndirectStubOwnerIds.
getNext();
620 if (
auto Err = callB<CreateIndirectStubsOwner>(
Id))
622 I = llvm::make_unique<RCIndirectStubsManager>(*
this,
Id);
630 return std::move(ExistingError);
633 if (
auto Err = callB<EmitResolverBlock>())
634 return std::move(Err);
637 CallbackManager.emplace(ErrorHandlerAddress, *
this);
648 return std::move(ExistingError);
650 return callB<GetSymbolAddress>(
Name);
663 addHandler<RequestCompile>(
666 return CallbackManager->executeCompileCallback(Addr);
670 if (
auto RIOrErr = callB<GetRemoteInfo>()) {
671 std::tie(RemoteTargetTriple, RemotePointerSize, RemotePageSize,
672 RemoteTrampolineSize, RemoteIndirectStubSize) = *RIOrErr;
675 Err =
joinErrors(RIOrErr.takeError(), std::move(ExistingError));
680 return callB<RegisterEHFrames>(Addr,
Size);
684 if (
auto Err = callB<DestroyRemoteAllocator>(Id)) {
693 IndirectStubOwnerIds.
release(Id);
694 return callB<DestroyIndirectStubsOwner>(
Id);
697 Expected<std::tuple<JITTargetAddress, JITTargetAddress, uint32_t>>
699 return callB<EmitIndirectStubs>(
Id, NumStubsRequired);
702 Expected<std::tuple<JITTargetAddress, uint32_t>> emitTrampolineBlock() {
705 return std::move(ExistingError);
707 return callB<EmitTrampolineBlock>();
710 uint32_t getIndirectStubSize()
const {
return RemoteIndirectStubSize; }
711 uint32_t getPageSize()
const {
return RemotePageSize; }
712 uint32_t getPointerSize()
const {
return RemotePointerSize; }
714 uint32_t getTrampolineSize()
const {
return RemoteTrampolineSize; }
720 return std::move(ExistingError);
722 return callB<ReadMem>(Src,
Size);
726 return callB<RegisterEHFrames>(RAddr,
Size);
733 return std::move(ExistingError);
740 return callB<SetProtections>(
Id, RemoteSegAddr, ProtFlags);
746 return std::move(ExistingError);
748 return callB<WriteMem>(DirectBufferWriter(Src, Addr, Size));
754 return std::move(ExistingError);
756 return callB<WritePtr>(Addr, PtrVal);
762 std::string RemoteTargetTriple;
766 uint32_t RemoteIndirectStubSize = 0;
767 ResourceIdMgr AllocatorIds, IndirectStubOwnerIds;
768 Optional<RCCompileCallbackManager> CallbackManager;
777 #endif // LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H
bool finalizeMemory(std::string *ErrMsg=nullptr) override
This method is called when object loading is complete and section page permissions can be applied...
Base class for managing collections of named indirect stubs.
Represents a symbol in the JIT.
bool getAlign(const Function &F, unsigned index, unsigned &align)
This class is the base class for all object file types.
Expected< RCCompileCallbackManager & > enableCompileCallbacks(JITTargetAddress ErrorHandlerAddress)
Error callVoidVoid(JITTargetAddress Addr)
Call the void() function at the given address in the target and wait for it to finish.
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
RCIndirectStubsManager(OrcRemoteTargetClient &Remote, ResourceIdMgr::ResourceId Id)
void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign, uintptr_t RODataSize, uint32_t RODataAlign, uintptr_t RWDataSize, uint32_t RWDataAlign) override
Inform the memory manager about the total amount of memory required to allocate all sections to be lo...
void notifyObjectLoaded(RuntimeDyld &Dyld, const object::ObjectFile &Obj) override
This method is called after an object has been loaded into memory but before relocations are applied ...
Base class for error info classes.
Expected< int > callIntVoid(JITTargetAddress Addr)
Call the int(void) function at the given address in the target and return its result.
Target-independent base class for compile callback management.
RCMemoryManager & operator=(const RCMemoryManager &)=delete
Expected< JITTargetAddress > getSymbolAddress(StringRef Name)
Search for symbols in the remote process.
virtual void log(raw_ostream &OS) const =0
Print an error message to an output stream.
JITSymbol findPointer(StringRef Name) override
Find the implementation-pointer for the stub.
Tagged union holding either a T or a Error.
JITTargetAddress ErrorHandlerAddress
JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override
Find the stub with the given name.
RCCompileCallbackManager(JITTargetAddress ErrorHandlerAddress, OrcRemoteTargetClient &Remote)
uint64_t JITTargetAddress
Represents an address in the target process's address space.
~RCMemoryManager() override
Expected< int > callMain(JITTargetAddress Addr, const std::vector< std::string > &Args)
Call the int(int, char*[]) function at the given address in the target and return its result...
void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override
Register the EH frames with the runtime so that c++ exceptions work.
std::vector< JITTargetAddress > AvailableTrampolines
Remote indirect stubs manager.
format_object< Ts...> format(const char *Fmt, const Ts &...Vals)
These are helper functions used to produce formatted output.
Error createStubs(const StubInitsMap &StubInits) override
Create StubInits.size() stubs with the given names, target addresses, and flags.
Error createStub(StringRef StubName, JITTargetAddress StubAddr, JITSymbolFlags StubFlags) override
Create a single stub with the given name, target address and flags.
RCMemoryManager(OrcRemoteTargetClient &Client, ResourceIdMgr::ResourceId Id)
uint8_t * allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly) override
Allocate a memory block of (at least) the given size suitable for data.
Error createRemoteMemoryManager(std::unique_ptr< RCMemoryManager > &MM)
Create an RCMemoryManager which will allocate its memory on the remote target.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
This class provides utilities (including memory manager, indirect stubs manager, and compile callback...
Flags for symbols in the JIT.
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
void deregisterEHFrames() override
void consumeError(Error Err)
Consume a Error without doing anything.
static ErrorSuccess success()
Create a success value.
void release(ResourceId I)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Error createIndirectStubsManager(std::unique_ptr< RCIndirectStubsManager > &I)
Create an RCIndirectStubsManager that will allocate stubs on the remote target.
Helper for Errors used as out-parameters.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
static std::vector< std::string > Flags
Error joinErrors(Error E1, Error E2)
Concatenate errors.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
~RCIndirectStubsManager() override
static Expected< std::unique_ptr< OrcRemoteTargetClient > > Create(ChannelT &Channel)
Create an OrcRemoteTargetClient.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
uint8_t * allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) override
Allocate a memory block of (at least) the given size suitable for executable code.
A raw_ostream that writes to an std::string.
Error updatePointer(StringRef Name, JITTargetAddress NewAddr) override
Change the value of the implementation pointer for the stub.
bool needsToReserveAllocationSpace() override
Override to return true to enable the reserveAllocationSpace callback.
Lightweight error class with error context and mandatory checking.
Remote compile callback manager.
StringRef - Represent a constant reference to a string, i.e.
void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress)
Map a section to its target address space value.
const std::string & getTargetTriple() const
Get the triple for the remote target.