16 #ifndef LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H 17 #define LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H 43 #define DEBUG_TYPE "orc-remote" 65 Client.destroyRemoteAllocator(
Id);
79 Unmapped.back().CodeAllocs.emplace_back(Size, Alignment);
80 uint8_t *Alloc =
reinterpret_cast<uint8_t *
>(
81 Unmapped.back().CodeAllocs.back().getLocalAddress());
83 << SectionName <<
": " << Alloc <<
" (" << Size
84 <<
" bytes, alignment " << Alignment <<
")\n");
90 bool IsReadOnly)
override {
92 Unmapped.back().RODataAllocs.emplace_back(Size, Alignment);
93 uint8_t *Alloc =
reinterpret_cast<uint8_t *
>(
94 Unmapped.back().RODataAllocs.back().getLocalAddress());
96 << SectionName <<
": " << Alloc <<
" (" << Size
97 <<
" bytes, alignment " << Alignment <<
")\n");
101 Unmapped.back().RWDataAllocs.emplace_back(Size, Alignment);
102 uint8_t *Alloc =
reinterpret_cast<uint8_t *
>(
103 Unmapped.back().RWDataAllocs.back().getLocalAddress());
105 << SectionName <<
": " << Alloc <<
" (" << Size
106 <<
" bytes, alignment " << Alignment <<
")\n");
111 uintptr_t RODataSize,
uint32_t RODataAlign,
112 uintptr_t RWDataSize,
114 Unmapped.push_back(ObjectAllocs());
119 Unmapped.back().RemoteCodeAddr =
120 Client.reserveMem(
Id, CodeSize, CodeAlign);
123 <<
format(
"0x%016x", Unmapped.back().RemoteCodeAddr)
124 <<
" (" << CodeSize <<
" bytes, alignment " 125 << CodeAlign <<
")\n");
128 if (RODataSize != 0) {
129 Unmapped.back().RemoteRODataAddr =
130 Client.reserveMem(
Id, RODataSize, RODataAlign);
133 <<
format(
"0x%016x", Unmapped.back().RemoteRODataAddr)
134 <<
" (" << RODataSize <<
" bytes, alignment " 135 << RODataAlign <<
")\n");
138 if (RWDataSize != 0) {
139 Unmapped.back().RemoteRWDataAddr =
140 Client.reserveMem(
Id, RWDataSize, RWDataAlign);
143 <<
format(
"0x%016x", Unmapped.back().RemoteRWDataAddr)
144 <<
" (" << RWDataSize <<
" bytes, alignment " 145 << RWDataAlign <<
")\n");
152 size_t Size)
override {
153 UnfinalizedEHFrames.push_back({LoadAddr, Size});
157 for (
auto &Frame : RegisteredEHFrames) {
159 Client.deregisterEHFrames(Frame.Addr, Frame.Size);
166 for (
auto &ObjAllocs : Unmapped) {
167 mapAllocsToRemoteAddrs(Dyld, ObjAllocs.CodeAllocs,
168 ObjAllocs.RemoteCodeAddr);
169 mapAllocsToRemoteAddrs(Dyld, ObjAllocs.RODataAllocs,
170 ObjAllocs.RemoteRODataAddr);
171 mapAllocsToRemoteAddrs(Dyld, ObjAllocs.RWDataAllocs,
172 ObjAllocs.RemoteRWDataAddr);
173 Unfinalized.push_back(std::move(ObjAllocs));
181 for (
auto &ObjAllocs : Unfinalized) {
182 if (copyAndProtect(ObjAllocs.CodeAllocs, ObjAllocs.RemoteCodeAddr,
186 if (copyAndProtect(ObjAllocs.RODataAllocs, ObjAllocs.RemoteRODataAddr,
190 if (copyAndProtect(ObjAllocs.RWDataAllocs, ObjAllocs.RemoteRWDataAddr,
196 for (
auto &EHFrame : UnfinalizedEHFrames) {
197 if (
auto Err = Client.registerEHFrames(EHFrame.Addr, EHFrame.Size)) {
208 RegisteredEHFrames = std::move(UnfinalizedEHFrames);
209 UnfinalizedEHFrames = {};
218 :
Size(Size),
Align(Align), Contents(
new char[Size + Align - 1]) {}
220 Alloc(
const Alloc &) =
delete;
221 Alloc &
operator=(
const Alloc &) =
delete;
222 Alloc(Alloc &&) =
default;
225 uint64_t getSize()
const {
return Size; }
229 char *getLocalAddress()
const {
230 uintptr_t LocalAddr =
reinterpret_cast<uintptr_t
>(Contents.get());
231 LocalAddr =
alignTo(LocalAddr, Align);
232 return reinterpret_cast<char *
>(LocalAddr);
236 this->RemoteAddr = RemoteAddr;
244 std::unique_ptr<char[]> Contents;
248 struct ObjectAllocs {
249 ObjectAllocs() =
default;
250 ObjectAllocs(
const ObjectAllocs &) =
delete;
251 ObjectAllocs &
operator=(
const ObjectAllocs &) =
delete;
252 ObjectAllocs(ObjectAllocs &&) =
default;
253 ObjectAllocs &
operator=(ObjectAllocs &&) =
default;
258 std::vector<Alloc> CodeAllocs, RODataAllocs, RWDataAllocs;
263 : Client(Client), Id(Id) {
268 void mapAllocsToRemoteAddrs(
RuntimeDyld &Dyld, std::vector<Alloc> &Allocs,
270 for (
auto &Alloc : Allocs) {
271 NextAddr =
alignTo(NextAddr, Alloc.getAlign());
274 << static_cast<void *>(Alloc.getLocalAddress())
275 <<
" -> " <<
format(
"0x%016x", NextAddr) <<
"\n");
276 Alloc.setRemoteAddress(NextAddr);
281 NextAddr += Alloc.getSize();
287 bool copyAndProtect(
const std::vector<Alloc> &Allocs,
289 unsigned Permissions) {
290 if (RemoteSegmentAddr) {
291 assert(!Allocs.empty() &&
"No sections in allocated segment");
293 for (
auto &Alloc : Allocs) {
295 << static_cast<void *>(Alloc.getLocalAddress())
297 <<
format(
"0x%016x", Alloc.getRemoteAddress())
298 <<
" (" << Alloc.getSize() <<
" bytes)\n";);
300 if (Client.writeMem(Alloc.getRemoteAddress(), Alloc.getLocalAddress(),
309 <<
" permissions on block: " 310 <<
format(
"0x%016x", RemoteSegmentAddr) <<
"\n");
311 if (Client.setProtections(Id, RemoteSegmentAddr, Permissions))
319 std::vector<ObjectAllocs> Unmapped;
320 std::vector<ObjectAllocs> Unfinalized;
326 std::vector<EHFrame> UnfinalizedEHFrames;
327 std::vector<EHFrame> RegisteredEHFrames;
335 : Client(Client), Id(Id) {}
338 Client.destroyIndirectStubsManager(Id);
343 if (
auto Err = reserveStubs(1))
346 return createStubInternal(StubName, StubAddr, StubFlags);
350 if (
auto Err = reserveStubs(StubInits.
size()))
353 for (
auto &Entry : StubInits)
354 if (
auto Err = createStubInternal(Entry.first(), Entry.second.first,
355 Entry.second.second))
362 auto I = StubIndexes.find(Name);
363 if (
I == StubIndexes.end())
365 auto Key =
I->second.first;
366 auto Flags =
I->second.second;
368 if (ExportedStubsOnly && !StubSymbol.getFlags().isExported())
374 auto I = StubIndexes.find(Name);
375 if (
I == StubIndexes.end())
377 auto Key =
I->second.first;
378 auto Flags =
I->second.second;
383 auto I = StubIndexes.find(Name);
384 assert(
I != StubIndexes.end() &&
"No stub pointer for symbol");
385 auto Key =
I->second.first;
386 return Client.writePointer(getPtrAddr(Key), NewAddr);
390 struct RemoteIndirectStubsInfo {
396 using StubKey = std::pair<uint16_t, uint16_t>;
398 Error reserveStubs(
unsigned NumStubs) {
399 if (NumStubs <= FreeStubs.size())
402 unsigned NewStubsRequired = NumStubs - FreeStubs.size();
405 unsigned NumStubsEmitted;
407 if (
auto StubInfoOrErr = Client.emitIndirectStubs(Id, NewStubsRequired))
408 std::tie(StubBase, PtrBase, NumStubsEmitted) = *StubInfoOrErr;
410 return StubInfoOrErr.takeError();
412 unsigned NewBlockId = RemoteIndirectStubsInfos.size();
413 RemoteIndirectStubsInfos.push_back({StubBase, PtrBase, NumStubsEmitted});
415 for (
unsigned I = 0;
I < NumStubsEmitted; ++
I)
416 FreeStubs.push_back(std::make_pair(NewBlockId,
I));
423 auto Key = FreeStubs.back();
424 FreeStubs.pop_back();
425 StubIndexes[StubName] = std::make_pair(
Key, StubFlags);
426 return Client.writePointer(getPtrAddr(
Key), InitAddr);
430 assert(RemoteIndirectStubsInfos[K.first].StubBase != 0 &&
431 "Missing stub address");
432 return RemoteIndirectStubsInfos[K.first].StubBase +
433 K.second * Client.getIndirectStubSize();
437 assert(RemoteIndirectStubsInfos[K.first].PtrBase != 0 &&
438 "Missing pointer address");
439 return RemoteIndirectStubsInfos[K.first].PtrBase +
440 K.second * Client.getPointerSize();
445 std::vector<RemoteIndirectStubsInfo> RemoteIndirectStubsInfos;
446 std::vector<StubKey> FreeStubs;
459 Error grow()
override {
462 if (
auto TrampolineInfoOrErr = Client.emitTrampolineBlock())
463 std::tie(BlockAddr, NumTrampolines) = *TrampolineInfoOrErr;
465 return TrampolineInfoOrErr.takeError();
467 uint32_t TrampolineSize = Client.getTrampolineSize();
468 for (
unsigned I = 0;
I < NumTrampolines; ++
I)
469 this->AvailableTrampolines.push_back(BlockAddr + (
I * TrampolineSize));
483 auto Client = std::unique_ptr<OrcRemoteTargetClient>(
486 return std::move(Err);
487 return std::move(Client);
495 return callB<exec::CallIntVoid>(Addr);
501 const std::vector<std::string> &
Args) {
503 <<
format(
"0x%016x", Addr) <<
"\n");
504 return callB<exec::CallMain>(Addr,
Args);
512 return callB<exec::CallVoidVoid>(Addr);
519 auto Id = AllocatorIds.getNext();
520 if (
auto Err = callB<mem::CreateRemoteAllocator>(Id))
521 return std::move(Err);
522 return std::unique_ptr<RemoteRTDyldMemoryManager>(
530 auto Id = IndirectStubOwnerIds.getNext();
531 if (
auto Err = callB<stubs::CreateIndirectStubsOwner>(Id))
532 return std::move(Err);
533 return llvm::make_unique<RemoteIndirectStubsManager>(*
this, Id);
538 assert(!CallbackManager &&
"CallbackManager already obtained");
541 if (
auto Err = callB<stubs::EmitResolverBlock>())
542 return std::move(Err);
545 CallbackManager.emplace(*
this, ES, ErrorHandlerAddress);
554 return callB<utils::GetSymbolAddress>(
Name);
569 addHandler<utils::RequestCompile>(
572 return CallbackManager->executeCompileCallback(Addr);
576 if (
auto RIOrErr = callB<utils::GetRemoteInfo>()) {
577 std::tie(RemoteTargetTriple, RemotePointerSize, RemotePageSize,
578 RemoteTrampolineSize, RemoteIndirectStubSize) = *RIOrErr;
581 Err = RIOrErr.takeError();
585 if (
auto Err = callB<eh::RegisterEHFrames>(Addr, Size))
590 if (
auto Err = callB<mem::DestroyRemoteAllocator>(Id)) {
594 AllocatorIds.release(Id);
599 IndirectStubOwnerIds.release(Id);
600 if (
auto Err = callB<stubs::DestroyIndirectStubsOwner>(Id))
606 return callB<stubs::EmitIndirectStubs>(Id, NumStubsRequired);
610 return callB<stubs::EmitTrampolineBlock>();
613 uint32_t getIndirectStubSize()
const {
return RemoteIndirectStubSize; }
614 uint32_t getPageSize()
const {
return RemotePageSize; }
615 uint32_t getPointerSize()
const {
return RemotePointerSize; }
617 uint32_t getTrampolineSize()
const {
return RemoteTrampolineSize; }
621 return callB<mem::ReadMem>(Src,
Size);
626 return callB<eh::RegisterEHFrames>(RAddr,
Size);
631 if (
auto AddrOrErr = callB<mem::ReserveMem>(Id, Size, Align))
641 if (
auto Err = callB<mem::SetProtections>(Id, RemoteSegAddr, ProtFlags)) {
657 return callB<mem::WritePtr>(Addr, PtrVal);
663 std::function<void(Error)> ReportError;
664 std::string RemoteTargetTriple;
668 uint32_t RemoteIndirectStubSize = 0;
679 #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)
Compute iterated dominance frontiers using a linear time algorithm.
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.
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...
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.
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.
void reportError(Error Err)
Report a error for this execution session.
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.
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.
Helper for Errors used as out-parameters.
RemoteRTDyldMemoryManager & operator=(const RemoteRTDyldMemoryManager &)=delete
~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.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
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)