15 #ifndef LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H 16 #define LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H 42 #define DEBUG_TYPE "orc-remote" 64 Client.destroyRemoteAllocator(
Id);
77 Unmapped.back().CodeAllocs.emplace_back(Size, Alignment);
78 uint8_t *Alloc =
reinterpret_cast<uint8_t *
>(
79 Unmapped.back().CodeAllocs.back().getLocalAddress());
81 << SectionName <<
": " << Alloc <<
" (" << Size
82 <<
" bytes, alignment " << Alignment <<
")\n");
88 bool IsReadOnly)
override {
90 Unmapped.back().RODataAllocs.emplace_back(Size, Alignment);
91 uint8_t *Alloc =
reinterpret_cast<uint8_t *
>(
92 Unmapped.back().RODataAllocs.back().getLocalAddress());
94 << SectionName <<
": " << Alloc <<
" (" << Size
95 <<
" bytes, alignment " << Alignment <<
")\n");
99 Unmapped.back().RWDataAllocs.emplace_back(Size, Alignment);
100 uint8_t *Alloc =
reinterpret_cast<uint8_t *
>(
101 Unmapped.back().RWDataAllocs.back().getLocalAddress());
103 << SectionName <<
": " << Alloc <<
" (" << Size
104 <<
" bytes, alignment " << Alignment <<
")\n");
109 uintptr_t RODataSize,
uint32_t RODataAlign,
110 uintptr_t RWDataSize,
112 Unmapped.push_back(ObjectAllocs());
117 Unmapped.back().RemoteCodeAddr =
118 Client.reserveMem(
Id, CodeSize, CodeAlign);
122 <<
format(
"0x%016" PRIx64, Unmapped.back().RemoteCodeAddr)
123 <<
" (" << CodeSize <<
" bytes, alignment " << CodeAlign
127 if (RODataSize != 0) {
128 Unmapped.back().RemoteRODataAddr =
129 Client.reserveMem(
Id, RODataSize, RODataAlign);
132 dbgs() <<
" ro-data: " 133 <<
format(
"0x%016" PRIx64, Unmapped.back().RemoteRODataAddr)
134 <<
" (" << RODataSize <<
" bytes, alignment " << RODataAlign
138 if (RWDataSize != 0) {
139 Unmapped.back().RemoteRWDataAddr =
140 Client.reserveMem(
Id, RWDataSize, RWDataAlign);
143 dbgs() <<
" rw-data: " 144 <<
format(
"0x%016" PRIx64, Unmapped.back().RemoteRWDataAddr)
145 <<
" (" << RWDataSize <<
" bytes, alignment " << RWDataAlign
153 size_t Size)
override {
154 UnfinalizedEHFrames.push_back({LoadAddr, Size});
158 for (
auto &Frame : RegisteredEHFrames) {
160 Client.deregisterEHFrames(Frame.Addr, Frame.Size);
167 for (
auto &ObjAllocs : Unmapped) {
168 mapAllocsToRemoteAddrs(Dyld, ObjAllocs.CodeAllocs,
169 ObjAllocs.RemoteCodeAddr);
170 mapAllocsToRemoteAddrs(Dyld, ObjAllocs.RODataAllocs,
171 ObjAllocs.RemoteRODataAddr);
172 mapAllocsToRemoteAddrs(Dyld, ObjAllocs.RWDataAllocs,
173 ObjAllocs.RemoteRWDataAddr);
174 Unfinalized.push_back(std::move(ObjAllocs));
182 for (
auto &ObjAllocs : Unfinalized) {
183 if (copyAndProtect(ObjAllocs.CodeAllocs, ObjAllocs.RemoteCodeAddr,
187 if (copyAndProtect(ObjAllocs.RODataAllocs, ObjAllocs.RemoteRODataAddr,
191 if (copyAndProtect(ObjAllocs.RWDataAllocs, ObjAllocs.RemoteRWDataAddr,
197 for (
auto &EHFrame : UnfinalizedEHFrames) {
198 if (
auto Err = Client.registerEHFrames(EHFrame.Addr, EHFrame.Size)) {
209 RegisteredEHFrames = std::move(UnfinalizedEHFrames);
210 UnfinalizedEHFrames = {};
219 :
Size(Size),
Align(Align), Contents(
new char[Size + Align - 1]) {}
221 Alloc(
const Alloc &) =
delete;
222 Alloc &
operator=(
const Alloc &) =
delete;
223 Alloc(Alloc &&) =
default;
226 uint64_t getSize()
const {
return Size; }
230 char *getLocalAddress()
const {
231 uintptr_t LocalAddr =
reinterpret_cast<uintptr_t
>(Contents.get());
232 LocalAddr =
alignTo(LocalAddr, Align);
233 return reinterpret_cast<char *
>(LocalAddr);
237 this->RemoteAddr = RemoteAddr;
245 std::unique_ptr<char[]> Contents;
249 struct ObjectAllocs {
250 ObjectAllocs() =
default;
251 ObjectAllocs(
const ObjectAllocs &) =
delete;
252 ObjectAllocs &
operator=(
const ObjectAllocs &) =
delete;
253 ObjectAllocs(ObjectAllocs &&) =
default;
254 ObjectAllocs &
operator=(ObjectAllocs &&) =
default;
259 std::vector<Alloc> CodeAllocs, RODataAllocs, RWDataAllocs;
264 : Client(Client), Id(Id) {
269 void mapAllocsToRemoteAddrs(
RuntimeDyld &Dyld, std::vector<Alloc> &Allocs,
271 for (
auto &Alloc : Allocs) {
272 NextAddr =
alignTo(NextAddr, Alloc.getAlign());
275 dbgs() <<
" " << static_cast<void *>(Alloc.getLocalAddress())
276 <<
" -> " <<
format(
"0x%016" PRIx64, NextAddr) <<
"\n");
277 Alloc.setRemoteAddress(NextAddr);
282 NextAddr += Alloc.getSize();
288 bool copyAndProtect(
const std::vector<Alloc> &Allocs,
290 unsigned Permissions) {
291 if (RemoteSegmentAddr) {
292 assert(!Allocs.empty() &&
"No sections in allocated segment");
294 for (
auto &Alloc : Allocs) {
296 << static_cast<void *>(Alloc.getLocalAddress())
298 <<
format(
"0x%016" PRIx64, Alloc.getRemoteAddress())
299 <<
" (" << Alloc.getSize() <<
" bytes)\n";);
301 if (Client.writeMem(Alloc.getRemoteAddress(), Alloc.getLocalAddress(),
310 <<
" permissions on block: " 311 <<
format(
"0x%016" PRIx64, RemoteSegmentAddr)
313 if (Client.setProtections(Id, RemoteSegmentAddr, Permissions))
321 std::vector<ObjectAllocs> Unmapped;
322 std::vector<ObjectAllocs> Unfinalized;
328 std::vector<EHFrame> UnfinalizedEHFrames;
329 std::vector<EHFrame> RegisteredEHFrames;
337 : Client(Client), Id(Id) {}
340 Client.destroyIndirectStubsManager(Id);
345 if (
auto Err = reserveStubs(1))
348 return createStubInternal(StubName, StubAddr, StubFlags);
352 if (
auto Err = reserveStubs(StubInits.
size()))
355 for (
auto &
Entry : StubInits)
356 if (
auto Err = createStubInternal(
Entry.first(),
Entry.second.first,
357 Entry.second.second))
364 auto I = StubIndexes.find(Name);
365 if (
I == StubIndexes.end())
367 auto Key =
I->second.first;
368 auto Flags =
I->second.second;
370 if (ExportedStubsOnly && !StubSymbol.getFlags().isExported())
376 auto I = StubIndexes.find(Name);
377 if (
I == StubIndexes.end())
379 auto Key =
I->second.first;
380 auto Flags =
I->second.second;
385 auto I = StubIndexes.find(Name);
386 assert(
I != StubIndexes.end() &&
"No stub pointer for symbol");
387 auto Key =
I->second.first;
388 return Client.writePointer(getPtrAddr(Key), NewAddr);
392 struct RemoteIndirectStubsInfo {
398 using StubKey = std::pair<uint16_t, uint16_t>;
400 Error reserveStubs(
unsigned NumStubs) {
401 if (NumStubs <= FreeStubs.size())
404 unsigned NewStubsRequired = NumStubs - FreeStubs.size();
407 unsigned NumStubsEmitted;
409 if (
auto StubInfoOrErr = Client.emitIndirectStubs(Id, NewStubsRequired))
410 std::tie(StubBase, PtrBase, NumStubsEmitted) = *StubInfoOrErr;
412 return StubInfoOrErr.takeError();
414 unsigned NewBlockId = RemoteIndirectStubsInfos.size();
415 RemoteIndirectStubsInfos.push_back({StubBase, PtrBase, NumStubsEmitted});
417 for (
unsigned I = 0;
I < NumStubsEmitted; ++
I)
418 FreeStubs.push_back(std::make_pair(NewBlockId,
I));
425 auto Key = FreeStubs.back();
426 FreeStubs.pop_back();
427 StubIndexes[StubName] = std::make_pair(
Key, StubFlags);
428 return Client.writePointer(getPtrAddr(
Key), InitAddr);
432 assert(RemoteIndirectStubsInfos[K.first].StubBase != 0 &&
433 "Missing stub address");
434 return RemoteIndirectStubsInfos[K.first].StubBase +
435 K.second * Client.getIndirectStubSize();
439 assert(RemoteIndirectStubsInfos[K.first].PtrBase != 0 &&
440 "Missing pointer address");
441 return RemoteIndirectStubsInfos[K.first].PtrBase +
442 K.second * Client.getPointerSize();
447 std::vector<RemoteIndirectStubsInfo> RemoteIndirectStubsInfos;
448 std::vector<StubKey> FreeStubs;
457 std::lock_guard<std::mutex>
Lock(RTPMutex);
458 if (AvailableTrampolines.empty()) {
459 if (
auto Err = grow())
460 return std::move(Err);
462 assert(!AvailableTrampolines.empty() &&
"Failed to grow trampoline pool");
463 auto TrampolineAddr = AvailableTrampolines.back();
464 AvailableTrampolines.pop_back();
465 return TrampolineAddr;
472 if (
auto TrampolineInfoOrErr = Client.emitTrampolineBlock())
473 std::tie(BlockAddr, NumTrampolines) = *TrampolineInfoOrErr;
475 return TrampolineInfoOrErr.takeError();
477 uint32_t TrampolineSize = Client.getTrampolineSize();
478 for (
unsigned I = 0;
I < NumTrampolines; ++
I)
479 this->AvailableTrampolines.push_back(BlockAddr + (
I * TrampolineSize));
486 std::vector<JITTargetAddress> AvailableTrampolines;
497 ErrorHandlerAddress) {}
506 auto Client = std::unique_ptr<OrcRemoteTargetClient>(
509 return std::move(Err);
510 return std::move(Client);
517 <<
format(
"0x%016" PRIx64, Addr) <<
"\n");
518 return callB<exec::CallIntVoid>(Addr);
524 const std::vector<std::string> &
Args) {
526 <<
format(
"0x%016" PRIx64, Addr) <<
"\n");
527 return callB<exec::CallMain>(Addr,
Args);
534 <<
format(
"0x%016" PRIx64, Addr) <<
"\n");
535 return callB<exec::CallVoidVoid>(Addr);
542 auto Id = AllocatorIds.getNext();
543 if (
auto Err = callB<mem::CreateRemoteAllocator>(Id))
544 return std::move(Err);
545 return std::unique_ptr<RemoteRTDyldMemoryManager>(
553 auto Id = IndirectStubOwnerIds.getNext();
554 if (
auto Err = callB<stubs::CreateIndirectStubsOwner>(Id))
555 return std::move(Err);
556 return std::make_unique<RemoteIndirectStubsManager>(*
this, Id);
561 assert(!CallbackManager &&
"CallbackManager already obtained");
564 if (
auto Err = callB<stubs::EmitResolverBlock>())
565 return std::move(Err);
568 CallbackManager.emplace(*
this, ES, ErrorHandlerAddress);
577 return callB<utils::GetSymbolAddress>(
Name);
592 addHandler<utils::RequestCompile>(
595 return CallbackManager->executeCompileCallback(Addr);
599 if (
auto RIOrErr = callB<utils::GetRemoteInfo>()) {
600 std::tie(RemoteTargetTriple, RemotePointerSize, RemotePageSize,
601 RemoteTrampolineSize, RemoteIndirectStubSize) = *RIOrErr;
604 Err = RIOrErr.takeError();
608 if (
auto Err = callB<eh::RegisterEHFrames>(Addr, Size))
613 if (
auto Err = callB<mem::DestroyRemoteAllocator>(Id)) {
617 AllocatorIds.release(Id);
622 IndirectStubOwnerIds.release(Id);
623 if (
auto Err = callB<stubs::DestroyIndirectStubsOwner>(Id))
629 return callB<stubs::EmitIndirectStubs>(Id, NumStubsRequired);
633 return callB<stubs::EmitTrampolineBlock>();
636 uint32_t getIndirectStubSize()
const {
return RemoteIndirectStubSize; }
637 uint32_t getPageSize()
const {
return RemotePageSize; }
638 uint32_t getPointerSize()
const {
return RemotePointerSize; }
640 uint32_t getTrampolineSize()
const {
return RemoteTrampolineSize; }
644 return callB<mem::ReadMem>(Src,
Size);
649 return callB<eh::RegisterEHFrames>(RAddr,
Size);
654 if (
auto AddrOrErr = callB<mem::ReserveMem>(Id, Size, Align))
664 if (
auto Err = callB<mem::SetProtections>(Id, RemoteSegAddr, ProtFlags)) {
680 return callB<mem::WritePtr>(Addr, PtrVal);
686 std::function<void(Error)> ReportError;
687 std::string RemoteTargetTriple;
691 uint32_t RemoteIndirectStubSize = 0;
702 #endif // LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H bool needsToReserveAllocationSpace() override
Override to return true to enable the reserveAllocationSpace callback.
Error createStubs(const StubInitsMap &StubInits) override
Create StubInits.size() stubs with the given names, target addresses, and flags.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Base class for managing collections of named indirect stubs.
bool getAlign(const Function &F, unsigned index, unsigned &align)
This class represents lattice values for constants.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Remote indirect stubs manager.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Interface for byte-streams to be used with RPC.
Expected< std::unique_ptr< RemoteRTDyldMemoryManager > > createRemoteMemoryManager()
Create an RCMemoryManager which will allocate its memory on the remote target.
This class is the base class for all object file types.
RemoteRTDyldMemoryManager(const RemoteRTDyldMemoryManager &)=delete
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...
Base class for error info classes.
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.
JITEvaluatedSymbol findStub(StringRef Name, bool ExportedStubsOnly) override
Find the stub with the given name.
Target-independent base class for compile callback management.
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 ...
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...
Error createStub(StringRef StubName, JITTargetAddress StubAddr, JITSymbolFlags StubFlags) override
Create a single stub with the given name, target address and flags.
RemoteCompileCallbackManager(OrcRemoteTargetClient &Client, ExecutionSession &ES, JITTargetAddress ErrorHandlerAddress)
virtual void log(raw_ostream &OS) const =0
Print an error message to an output stream.
Base class for pools of compiler re-entry trampolines.
Tagged union holding either a T or a Error.
Error callVoidVoid(JITTargetAddress Addr)
Call the void() function at the given address in the target and wait for it to finish.
Expected< JITTargetAddress > getSymbolAddress(StringRef Name)
Search for symbols in the remote process.
uint64_t JITTargetAddress
Represents an address in the target process's address space.
friend class OrcRemoteTargetClient
Remote compile callback manager.
const std::string & getTargetTriple() const
Get the triple for the remote target.
This class provides utilities (including memory manager, indirect stubs manager, and compile callback...
Flags for symbols in the JIT.
void deregisterEHFrames() override
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This struct is a compact representation of a valid (non-zero power of two) alignment.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
static ErrorSuccess success()
Create a success value.
Error updatePointer(StringRef Name, JITTargetAddress NewAddr) override
Change the value of the implementation pointer for the stub.
bool finalizeMemory(std::string *ErrMsg=nullptr) override
This method is called when object loading is complete and section page permissions can be applied...
An ExecutionSession represents a running JIT program.
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"...
Expected< RemoteCompileCallbackManager & > enableCompileCallbacks(JITTargetAddress ErrorHandlerAddress)
Represents a symbol that has been evaluated to an address already.
Expected< JITTargetAddress > getTrampoline() override
Get an available trampoline address.
Helper for Errors used as out-parameters.
void reportError(Error Err)
Report a error for this execution session.
RemoteRTDyldMemoryManager & operator=(const RemoteRTDyldMemoryManager &)=delete
RemoteTrampolinePool(OrcRemoteTargetClient &Client)
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
~RemoteIndirectStubsManager() override
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.
Expected< int > callIntVoid(JITTargetAddress Addr)
Call the int(void) function at the given address in the target and return its result.
~RemoteRTDyldMemoryManager()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
JITEvaluatedSymbol findPointer(StringRef Name) override
Find the implementation-pointer for the stub.
A raw_ostream that writes to an std::string.
Lightweight error class with error context and mandatory checking.
Remote-mapped RuntimeDyld-compatible memory manager.
static Expected< std::unique_ptr< OrcRemoteTargetClient > > Create(rpc::RawByteChannel &Channel, ExecutionSession &ES)
Create an OrcRemoteTargetClient.
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.
void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override
Register the EH frames with the runtime so that c++ exceptions work.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Expected< std::unique_ptr< RemoteIndirectStubsManager > > createIndirectStubsManager()
Create an RCIndirectStubsManager that will allocate stubs on the remote target.
RemoteIndirectStubsManager(OrcRemoteTargetClient &Client, ResourceIdMgr::ResourceId Id)