accf4e0f674ef738095f4693f6e5af33ddb3cba2
[oota-llvm.git] / include / llvm / ExecutionEngine / Orc / OrcRemoteTargetClient.h
1 //===---- OrcRemoteTargetClient.h - Orc Remote-target Client ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the OrcRemoteTargetClient class and helpers. This class
11 // can be used to communicate over an RPCChannel with an OrcRemoteTargetServer
12 // instance to support remote-JITing.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H
17 #define LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H
18
19 #include "IndirectionUtils.h"
20 #include "OrcRemoteTargetRPCAPI.h"
21
22 #define DEBUG_TYPE "orc-remote"
23
24 namespace llvm {
25 namespace orc {
26 namespace remote {
27
28 /// This class provides utilities (including memory manager, indirect stubs
29 /// manager, and compile callback manager types) that support remote JITing
30 /// in ORC.
31 ///
32 /// Each of the utility classes talks to a JIT server (an instance of the
33 /// OrcRemoteTargetServer class) via an RPC system (see RPCUtils.h) to carry out
34 /// its actions.
35 template <typename ChannelT>
36 class OrcRemoteTargetClient : public OrcRemoteTargetRPCAPI {
37 public:
38   /// Remote memory manager.
39   class RCMemoryManager : public RuntimeDyld::MemoryManager {
40   public:
41     RCMemoryManager(OrcRemoteTargetClient &Client, ResourceIdMgr::ResourceId Id)
42         : Client(Client), Id(Id) {
43       DEBUG(dbgs() << "Created remote allocator " << Id << "\n");
44     }
45
46     ~RCMemoryManager() {
47       Client.destroyRemoteAllocator(Id);
48       DEBUG(dbgs() << "Destroyed remote allocator " << Id << "\n");
49     }
50
51     uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
52                                  unsigned SectionID,
53                                  StringRef SectionName) override {
54       Unmapped.back().CodeAllocs.emplace_back(Size, Alignment);
55       uint8_t *Alloc = reinterpret_cast<uint8_t *>(
56           Unmapped.back().CodeAllocs.back().getLocalAddress());
57       DEBUG(dbgs() << "Allocator " << Id << " allocated code for "
58                    << SectionName << ": " << Alloc << " (" << Size
59                    << " bytes, alignment " << Alignment << ")\n");
60       return Alloc;
61     }
62
63     uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
64                                  unsigned SectionID, StringRef SectionName,
65                                  bool IsReadOnly) override {
66       if (IsReadOnly) {
67         Unmapped.back().RODataAllocs.emplace_back(Size, Alignment);
68         uint8_t *Alloc = reinterpret_cast<uint8_t *>(
69             Unmapped.back().RODataAllocs.back().getLocalAddress());
70         DEBUG(dbgs() << "Allocator " << Id << " allocated ro-data for "
71                      << SectionName << ": " << Alloc << " (" << Size
72                      << " bytes, alignment " << Alignment << ")\n");
73         return Alloc;
74       } // else...
75
76       Unmapped.back().RWDataAllocs.emplace_back(Size, Alignment);
77       uint8_t *Alloc = reinterpret_cast<uint8_t *>(
78           Unmapped.back().RWDataAllocs.back().getLocalAddress());
79       DEBUG(dbgs() << "Allocator " << Id << " allocated rw-data for "
80                    << SectionName << ": " << Alloc << " (" << Size
81                    << " bytes, alignment " << Alignment << "\n");
82       return Alloc;
83     }
84
85     void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
86                                 uintptr_t RODataSize, uint32_t RODataAlign,
87                                 uintptr_t RWDataSize,
88                                 uint32_t RWDataAlign) override {
89       Unmapped.push_back(ObjectAllocs());
90
91       DEBUG(dbgs() << "Allocator " << Id << " reserved:\n");
92
93       if (CodeSize != 0) {
94         if (std::error_code EC = Client.reserveMem(
95                 Unmapped.back().RemoteCodeAddr, Id, CodeSize, CodeAlign)) {
96           (void)EC;
97           // FIXME; Add error to poll.
98           llvm_unreachable("Failed reserving remote memory.");
99         }
100         DEBUG(dbgs() << "  code: "
101                      << format("0x%016x", Unmapped.back().RemoteCodeAddr)
102                      << " (" << CodeSize << " bytes, alignment " << CodeAlign
103                      << ")\n");
104       }
105
106       if (RODataSize != 0) {
107         if (auto EC = Client.reserveMem(Unmapped.back().RemoteRODataAddr, Id,
108                                         RODataSize, RODataAlign)) {
109           // FIXME; Add error to poll.
110           llvm_unreachable("Failed reserving remote memory.");
111         }
112         DEBUG(dbgs() << "  ro-data: "
113                      << format("0x%016x", Unmapped.back().RemoteRODataAddr)
114                      << " (" << RODataSize << " bytes, alignment "
115                      << RODataAlign << ")\n");
116       }
117
118       if (RWDataSize != 0) {
119         if (auto EC = Client.reserveMem(Unmapped.back().RemoteRWDataAddr, Id,
120                                         RWDataSize, RWDataAlign)) {
121           // FIXME; Add error to poll.
122           llvm_unreachable("Failed reserving remote memory.");
123         }
124         DEBUG(dbgs() << "  rw-data: "
125                      << format("0x%016x", Unmapped.back().RemoteRWDataAddr)
126                      << " (" << RWDataSize << " bytes, alignment "
127                      << RWDataAlign << ")\n");
128       }
129     }
130
131     bool needsToReserveAllocationSpace() override { return true; }
132
133     void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
134                           size_t Size) override {}
135
136     void deregisterEHFrames(uint8_t *addr, uint64_t LoadAddr,
137                             size_t Size) override {}
138
139     void notifyObjectLoaded(RuntimeDyld &Dyld,
140                             const object::ObjectFile &Obj) override {
141       DEBUG(dbgs() << "Allocator " << Id << " applied mappings:\n");
142       for (auto &ObjAllocs : Unmapped) {
143         {
144           TargetAddress NextCodeAddr = ObjAllocs.RemoteCodeAddr;
145           for (auto &Alloc : ObjAllocs.CodeAllocs) {
146             NextCodeAddr = RoundUpToAlignment(NextCodeAddr, Alloc.getAlign());
147             Dyld.mapSectionAddress(Alloc.getLocalAddress(), NextCodeAddr);
148             DEBUG(dbgs() << "     code: "
149                          << static_cast<void *>(Alloc.getLocalAddress())
150                          << " -> " << format("0x%016x", NextCodeAddr) << "\n");
151             Alloc.setRemoteAddress(NextCodeAddr);
152             NextCodeAddr += Alloc.getSize();
153           }
154         }
155         {
156           TargetAddress NextRODataAddr = ObjAllocs.RemoteRODataAddr;
157           for (auto &Alloc : ObjAllocs.RODataAllocs) {
158             NextRODataAddr =
159                 RoundUpToAlignment(NextRODataAddr, Alloc.getAlign());
160             Dyld.mapSectionAddress(Alloc.getLocalAddress(), NextRODataAddr);
161             DEBUG(dbgs() << "  ro-data: "
162                          << static_cast<void *>(Alloc.getLocalAddress())
163                          << " -> " << format("0x%016x", NextRODataAddr)
164                          << "\n");
165             Alloc.setRemoteAddress(NextRODataAddr);
166             NextRODataAddr += Alloc.getSize();
167           }
168         }
169         {
170           TargetAddress NextRWDataAddr = ObjAllocs.RemoteRWDataAddr;
171           for (auto &Alloc : ObjAllocs.RWDataAllocs) {
172             NextRWDataAddr =
173                 RoundUpToAlignment(NextRWDataAddr, Alloc.getAlign());
174             Dyld.mapSectionAddress(Alloc.getLocalAddress(), NextRWDataAddr);
175             DEBUG(dbgs() << "  rw-data: "
176                          << static_cast<void *>(Alloc.getLocalAddress())
177                          << " -> " << format("0x%016x", NextRWDataAddr)
178                          << "\n");
179             Alloc.setRemoteAddress(NextRWDataAddr);
180             NextRWDataAddr += Alloc.getSize();
181           }
182         }
183         Unfinalized.push_back(std::move(ObjAllocs));
184       }
185       Unmapped.clear();
186     }
187
188     bool finalizeMemory(std::string *ErrMsg = nullptr) override {
189       DEBUG(dbgs() << "Allocator " << Id << " finalizing:\n");
190
191       for (auto &ObjAllocs : Unfinalized) {
192
193         for (auto &Alloc : ObjAllocs.CodeAllocs) {
194           DEBUG(dbgs() << "  copying code: "
195                        << static_cast<void *>(Alloc.getLocalAddress()) << " -> "
196                        << format("0x%016x", Alloc.getRemoteAddress()) << " ("
197                        << Alloc.getSize() << " bytes)\n");
198           Client.writeMem(Alloc.getRemoteAddress(), Alloc.getLocalAddress(),
199                           Alloc.getSize());
200         }
201
202         if (ObjAllocs.RemoteCodeAddr) {
203           DEBUG(dbgs() << "  setting R-X permissions on code block: "
204                        << format("0x%016x", ObjAllocs.RemoteCodeAddr) << "\n");
205           Client.setProtections(Id, ObjAllocs.RemoteCodeAddr,
206                                 sys::Memory::MF_READ | sys::Memory::MF_EXEC);
207         }
208
209         for (auto &Alloc : ObjAllocs.RODataAllocs) {
210           DEBUG(dbgs() << "  copying ro-data: "
211                        << static_cast<void *>(Alloc.getLocalAddress()) << " -> "
212                        << format("0x%016x", Alloc.getRemoteAddress()) << " ("
213                        << Alloc.getSize() << " bytes)\n");
214           Client.writeMem(Alloc.getRemoteAddress(), Alloc.getLocalAddress(),
215                           Alloc.getSize());
216         }
217
218         if (ObjAllocs.RemoteRODataAddr) {
219           DEBUG(dbgs() << "  setting R-- permissions on ro-data block: "
220                        << format("0x%016x", ObjAllocs.RemoteRODataAddr)
221                        << "\n");
222           Client.setProtections(Id, ObjAllocs.RemoteRODataAddr,
223                                 sys::Memory::MF_READ);
224         }
225
226         for (auto &Alloc : ObjAllocs.RWDataAllocs) {
227           DEBUG(dbgs() << "  copying rw-data: "
228                        << static_cast<void *>(Alloc.getLocalAddress()) << " -> "
229                        << format("0x%016x", Alloc.getRemoteAddress()) << " ("
230                        << Alloc.getSize() << " bytes)\n");
231           Client.writeMem(Alloc.getRemoteAddress(), Alloc.getLocalAddress(),
232                           Alloc.getSize());
233         }
234
235         if (ObjAllocs.RemoteRWDataAddr) {
236           DEBUG(dbgs() << "  setting RW- permissions on rw-data block: "
237                        << format("0x%016x", ObjAllocs.RemoteRWDataAddr)
238                        << "\n");
239           Client.setProtections(Id, ObjAllocs.RemoteRWDataAddr,
240                                 sys::Memory::MF_READ | sys::Memory::MF_WRITE);
241         }
242       }
243       Unfinalized.clear();
244
245       return false;
246     }
247
248   private:
249     class Alloc {
250     public:
251       Alloc(uint64_t Size, unsigned Align)
252           : Size(Size), Align(Align), Contents(new char[Size + Align - 1]),
253             RemoteAddr(0) {}
254
255       uint64_t getSize() const { return Size; }
256
257       unsigned getAlign() const { return Align; }
258
259       char *getLocalAddress() const {
260         uintptr_t LocalAddr = reinterpret_cast<uintptr_t>(Contents.get());
261         LocalAddr = RoundUpToAlignment(LocalAddr, Align);
262         return reinterpret_cast<char *>(LocalAddr);
263       }
264
265       void setRemoteAddress(TargetAddress RemoteAddr) {
266         this->RemoteAddr = RemoteAddr;
267       }
268
269       TargetAddress getRemoteAddress() const { return RemoteAddr; }
270
271     private:
272       uint64_t Size;
273       unsigned Align;
274       std::unique_ptr<char[]> Contents;
275       TargetAddress RemoteAddr;
276     };
277
278     struct ObjectAllocs {
279       ObjectAllocs()
280           : RemoteCodeAddr(0), RemoteRODataAddr(0), RemoteRWDataAddr(0) {}
281       TargetAddress RemoteCodeAddr;
282       TargetAddress RemoteRODataAddr;
283       TargetAddress RemoteRWDataAddr;
284       std::vector<Alloc> CodeAllocs, RODataAllocs, RWDataAllocs;
285     };
286
287     OrcRemoteTargetClient &Client;
288     ResourceIdMgr::ResourceId Id;
289     std::vector<ObjectAllocs> Unmapped;
290     std::vector<ObjectAllocs> Unfinalized;
291   };
292
293   /// Remote indirect stubs manager.
294   class RCIndirectStubsManager : public IndirectStubsManager {
295   public:
296     RCIndirectStubsManager(OrcRemoteTargetClient &Remote,
297                            ResourceIdMgr::ResourceId Id)
298         : Remote(Remote), Id(Id) {}
299
300     ~RCIndirectStubsManager() { Remote.destroyIndirectStubsManager(Id); }
301
302     std::error_code createStub(StringRef StubName, TargetAddress StubAddr,
303                                JITSymbolFlags StubFlags) override {
304       if (auto EC = reserveStubs(1))
305         return EC;
306
307       return createStubInternal(StubName, StubAddr, StubFlags);
308     }
309
310     std::error_code createStubs(const StubInitsMap &StubInits) override {
311       if (auto EC = reserveStubs(StubInits.size()))
312         return EC;
313
314       for (auto &Entry : StubInits)
315         if (auto EC = createStubInternal(Entry.first(), Entry.second.first,
316                                          Entry.second.second))
317           return EC;
318
319       return std::error_code();
320     }
321
322     JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override {
323       auto I = StubIndexes.find(Name);
324       if (I == StubIndexes.end())
325         return nullptr;
326       auto Key = I->second.first;
327       auto Flags = I->second.second;
328       auto StubSymbol = JITSymbol(getStubAddr(Key), Flags);
329       if (ExportedStubsOnly && !StubSymbol.isExported())
330         return nullptr;
331       return StubSymbol;
332     }
333
334     JITSymbol findPointer(StringRef Name) override {
335       auto I = StubIndexes.find(Name);
336       if (I == StubIndexes.end())
337         return nullptr;
338       auto Key = I->second.first;
339       auto Flags = I->second.second;
340       return JITSymbol(getPtrAddr(Key), Flags);
341     }
342
343     std::error_code updatePointer(StringRef Name,
344                                   TargetAddress NewAddr) override {
345       auto I = StubIndexes.find(Name);
346       assert(I != StubIndexes.end() && "No stub pointer for symbol");
347       auto Key = I->second.first;
348       return Remote.writePointer(getPtrAddr(Key), NewAddr);
349     }
350
351   private:
352     struct RemoteIndirectStubsInfo {
353       RemoteIndirectStubsInfo(TargetAddress StubBase, TargetAddress PtrBase,
354                               unsigned NumStubs)
355           : StubBase(StubBase), PtrBase(PtrBase), NumStubs(NumStubs) {}
356       TargetAddress StubBase;
357       TargetAddress PtrBase;
358       unsigned NumStubs;
359     };
360
361     OrcRemoteTargetClient &Remote;
362     ResourceIdMgr::ResourceId Id;
363     std::vector<RemoteIndirectStubsInfo> RemoteIndirectStubsInfos;
364     typedef std::pair<uint16_t, uint16_t> StubKey;
365     std::vector<StubKey> FreeStubs;
366     StringMap<std::pair<StubKey, JITSymbolFlags>> StubIndexes;
367
368     std::error_code reserveStubs(unsigned NumStubs) {
369       if (NumStubs <= FreeStubs.size())
370         return std::error_code();
371
372       unsigned NewStubsRequired = NumStubs - FreeStubs.size();
373       TargetAddress StubBase;
374       TargetAddress PtrBase;
375       unsigned NumStubsEmitted;
376
377       Remote.emitIndirectStubs(StubBase, PtrBase, NumStubsEmitted, Id,
378                                NewStubsRequired);
379
380       unsigned NewBlockId = RemoteIndirectStubsInfos.size();
381       RemoteIndirectStubsInfos.push_back(
382           RemoteIndirectStubsInfo(StubBase, PtrBase, NumStubsEmitted));
383
384       for (unsigned I = 0; I < NumStubsEmitted; ++I)
385         FreeStubs.push_back(std::make_pair(NewBlockId, I));
386
387       return std::error_code();
388     }
389
390     std::error_code createStubInternal(StringRef StubName,
391                                        TargetAddress InitAddr,
392                                        JITSymbolFlags StubFlags) {
393       auto Key = FreeStubs.back();
394       FreeStubs.pop_back();
395       StubIndexes[StubName] = std::make_pair(Key, StubFlags);
396       return Remote.writePointer(getPtrAddr(Key), InitAddr);
397     }
398
399     TargetAddress getStubAddr(StubKey K) {
400       assert(RemoteIndirectStubsInfos[K.first].StubBase != 0 &&
401              "Missing stub address");
402       return RemoteIndirectStubsInfos[K.first].StubBase +
403              K.second * Remote.getIndirectStubSize();
404     }
405
406     TargetAddress getPtrAddr(StubKey K) {
407       assert(RemoteIndirectStubsInfos[K.first].PtrBase != 0 &&
408              "Missing pointer address");
409       return RemoteIndirectStubsInfos[K.first].PtrBase +
410              K.second * Remote.getPointerSize();
411     }
412   };
413
414   /// Remote compile callback manager.
415   class RCCompileCallbackManager : public JITCompileCallbackManager {
416   public:
417     RCCompileCallbackManager(TargetAddress ErrorHandlerAddress,
418                              OrcRemoteTargetClient &Remote)
419         : JITCompileCallbackManager(ErrorHandlerAddress), Remote(Remote) {
420       assert(!Remote.CompileCallback && "Compile callback already set");
421       Remote.CompileCallback = [this](TargetAddress TrampolineAddr) {
422         return executeCompileCallback(TrampolineAddr);
423       };
424       Remote.emitResolverBlock();
425     }
426
427   private:
428     void grow() {
429       TargetAddress BlockAddr = 0;
430       uint32_t NumTrampolines = 0;
431       auto EC = Remote.emitTrampolineBlock(BlockAddr, NumTrampolines);
432       assert(!EC && "Failed to create trampolines");
433
434       uint32_t TrampolineSize = Remote.getTrampolineSize();
435       for (unsigned I = 0; I < NumTrampolines; ++I)
436         this->AvailableTrampolines.push_back(BlockAddr + (I * TrampolineSize));
437     }
438
439     OrcRemoteTargetClient &Remote;
440   };
441
442   /// Create an OrcRemoteTargetClient.
443   /// Channel is the ChannelT instance to communicate on. It is assumed that
444   /// the channel is ready to be read from and written to.
445   static ErrorOr<OrcRemoteTargetClient> Create(ChannelT &Channel) {
446     std::error_code EC;
447     OrcRemoteTargetClient H(Channel, EC);
448     if (EC)
449       return EC;
450     return H;
451   }
452
453   /// Call the int(void) function at the given address in the target and return
454   /// its result.
455   std::error_code callIntVoid(int &Result, TargetAddress Addr) {
456     DEBUG(dbgs() << "Calling int(*)(void) " << format("0x%016x", Addr) << "\n");
457
458     if (auto EC = call<CallIntVoid>(Channel, Addr))
459       return EC;
460
461     unsigned NextProcId;
462     if (auto EC = listenForCompileRequests(NextProcId))
463       return EC;
464
465     if (NextProcId != CallIntVoidResponseId)
466       return orcError(OrcErrorCode::UnexpectedRPCCall);
467
468     return handle<CallIntVoidResponse>(Channel, [&](int R) {
469       Result = R;
470       DEBUG(dbgs() << "Result: " << R << "\n");
471       return std::error_code();
472     });
473   }
474
475   /// Call the int(int, char*[]) function at the given address in the target and
476   /// return its result.
477   std::error_code callMain(int &Result, TargetAddress Addr,
478                            const std::vector<std::string> &Args) {
479     DEBUG(dbgs() << "Calling int(*)(int, char*[]) " << format("0x%016x", Addr)
480                  << "\n");
481
482     if (auto EC = call<CallMain>(Channel, Addr, Args))
483       return EC;
484
485     unsigned NextProcId;
486     if (auto EC = listenForCompileRequests(NextProcId))
487       return EC;
488
489     if (NextProcId != CallMainResponseId)
490       return orcError(OrcErrorCode::UnexpectedRPCCall);
491
492     return handle<CallMainResponse>(Channel, [&](int R) {
493       Result = R;
494       DEBUG(dbgs() << "Result: " << R << "\n");
495       return std::error_code();
496     });
497   }
498
499   /// Call the void() function at the given address in the target and wait for
500   /// it to finish.
501   std::error_code callVoidVoid(TargetAddress Addr) {
502     DEBUG(dbgs() << "Calling void(*)(void) " << format("0x%016x", Addr)
503                  << "\n");
504
505     if (auto EC = call<CallVoidVoid>(Channel, Addr))
506       return EC;
507
508     unsigned NextProcId;
509     if (auto EC = listenForCompileRequests(NextProcId))
510       return EC;
511
512     if (NextProcId != CallVoidVoidResponseId)
513       return orcError(OrcErrorCode::UnexpectedRPCCall);
514
515     return handle<CallVoidVoidResponse>(Channel, doNothing);
516   }
517
518   /// Create an RCMemoryManager which will allocate its memory on the remote
519   /// target.
520   std::error_code
521   createRemoteMemoryManager(std::unique_ptr<RCMemoryManager> &MM) {
522     assert(!MM && "MemoryManager should be null before creation.");
523
524     auto Id = AllocatorIds.getNext();
525     if (auto EC = call<CreateRemoteAllocator>(Channel, Id))
526       return EC;
527     MM = llvm::make_unique<RCMemoryManager>(*this, Id);
528     return std::error_code();
529   }
530
531   /// Create an RCIndirectStubsManager that will allocate stubs on the remote
532   /// target.
533   std::error_code
534   createIndirectStubsManager(std::unique_ptr<RCIndirectStubsManager> &I) {
535     assert(!I && "Indirect stubs manager should be null before creation.");
536     auto Id = IndirectStubOwnerIds.getNext();
537     if (auto EC = call<CreateIndirectStubsOwner>(Channel, Id))
538       return EC;
539     I = llvm::make_unique<RCIndirectStubsManager>(*this, Id);
540     return std::error_code();
541   }
542
543   /// Search for symbols in the remote process. Note: This should be used by
544   /// symbol resolvers *after* they've searched the local symbol table in the
545   /// JIT stack.
546   std::error_code getSymbolAddress(TargetAddress &Addr, StringRef Name) {
547     // Check for an 'out-of-band' error, e.g. from an MM destructor.
548     if (ExistingError)
549       return ExistingError;
550
551     // Request remote symbol address.
552     if (auto EC = call<GetSymbolAddress>(Channel, Name))
553       return EC;
554
555     return expect<GetSymbolAddressResponse>(Channel, [&](TargetAddress &A) {
556       Addr = A;
557       DEBUG(dbgs() << "Remote address lookup " << Name << " = "
558                    << format("0x%016x", Addr) << "\n");
559       return std::error_code();
560     });
561   }
562
563   /// Get the triple for the remote target.
564   const std::string &getTargetTriple() const { return RemoteTargetTriple; }
565
566   std::error_code terminateSession() { return call<TerminateSession>(Channel); }
567
568 private:
569   OrcRemoteTargetClient(ChannelT &Channel, std::error_code &EC)
570       : Channel(Channel), RemotePointerSize(0), RemotePageSize(0),
571         RemoteTrampolineSize(0), RemoteIndirectStubSize(0) {
572     if ((EC = call<GetRemoteInfo>(Channel)))
573       return;
574
575     EC = expect<GetRemoteInfoResponse>(
576         Channel, readArgs(RemoteTargetTriple, RemotePointerSize, RemotePageSize,
577                           RemoteTrampolineSize, RemoteIndirectStubSize));
578   }
579
580   void destroyRemoteAllocator(ResourceIdMgr::ResourceId Id) {
581     if (auto EC = call<DestroyRemoteAllocator>(Channel, Id)) {
582       // FIXME: This will be triggered by a removeModuleSet call: Propagate
583       //        error return up through that.
584       llvm_unreachable("Failed to destroy remote allocator.");
585       AllocatorIds.release(Id);
586     }
587   }
588
589   std::error_code destroyIndirectStubsManager(ResourceIdMgr::ResourceId Id) {
590     IndirectStubOwnerIds.release(Id);
591     return call<DestroyIndirectStubsOwner>(Channel, Id);
592   }
593
594   std::error_code emitIndirectStubs(TargetAddress &StubBase,
595                                     TargetAddress &PtrBase,
596                                     uint32_t &NumStubsEmitted,
597                                     ResourceIdMgr::ResourceId Id,
598                                     uint32_t NumStubsRequired) {
599     if (auto EC = call<EmitIndirectStubs>(Channel, Id, NumStubsRequired))
600       return EC;
601
602     return expect<EmitIndirectStubsResponse>(
603         Channel, readArgs(StubBase, PtrBase, NumStubsEmitted));
604   }
605
606   std::error_code emitResolverBlock() {
607     // Check for an 'out-of-band' error, e.g. from an MM destructor.
608     if (ExistingError)
609       return ExistingError;
610
611     return call<EmitResolverBlock>(Channel);
612   }
613
614   std::error_code emitTrampolineBlock(TargetAddress &BlockAddr,
615                                       uint32_t &NumTrampolines) {
616     // Check for an 'out-of-band' error, e.g. from an MM destructor.
617     if (ExistingError)
618       return ExistingError;
619
620     if (auto EC = call<EmitTrampolineBlock>(Channel))
621       return EC;
622
623     return expect<EmitTrampolineBlockResponse>(
624         Channel, [&](TargetAddress BAddr, uint32_t NTrampolines) {
625           BlockAddr = BAddr;
626           NumTrampolines = NTrampolines;
627           return std::error_code();
628         });
629   }
630
631   uint32_t getIndirectStubSize() const { return RemoteIndirectStubSize; }
632   uint32_t getPageSize() const { return RemotePageSize; }
633   uint32_t getPointerSize() const { return RemotePointerSize; }
634
635   uint32_t getTrampolineSize() const { return RemoteTrampolineSize; }
636
637   std::error_code listenForCompileRequests(uint32_t &NextId) {
638     // Check for an 'out-of-band' error, e.g. from an MM destructor.
639     if (ExistingError)
640       return ExistingError;
641
642     if (auto EC = getNextProcId(Channel, NextId))
643       return EC;
644
645     while (NextId == RequestCompileId) {
646       TargetAddress TrampolineAddr = 0;
647       if (auto EC = handle<RequestCompile>(Channel, readArgs(TrampolineAddr)))
648         return EC;
649
650       TargetAddress ImplAddr = CompileCallback(TrampolineAddr);
651       if (auto EC = call<RequestCompileResponse>(Channel, ImplAddr))
652         return EC;
653
654       if (auto EC = getNextProcId(Channel, NextId))
655         return EC;
656     }
657
658     return std::error_code();
659   }
660
661   std::error_code readMem(char *Dst, TargetAddress Src, uint64_t Size) {
662     // Check for an 'out-of-band' error, e.g. from an MM destructor.
663     if (ExistingError)
664       return ExistingError;
665
666     if (auto EC = call<ReadMem>(Channel, Src, Size))
667       return EC;
668
669     if (auto EC = expect<ReadMemResponse>(
670             Channel, [&]() { return Channel.readBytes(Dst, Size); }))
671       return EC;
672
673     return std::error_code();
674   }
675
676   std::error_code reserveMem(TargetAddress &RemoteAddr,
677                              ResourceIdMgr::ResourceId Id, uint64_t Size,
678                              uint32_t Align) {
679
680     // Check for an 'out-of-band' error, e.g. from an MM destructor.
681     if (ExistingError)
682       return ExistingError;
683
684     if (auto EC = call<ReserveMem>(Channel, Id, Size, Align))
685       return EC;
686
687     if (auto EC = expect<ReserveMemResponse>(Channel, [&](TargetAddress Addr) {
688           RemoteAddr = Addr;
689           return std::error_code();
690         }))
691       return EC;
692
693     return std::error_code();
694   }
695
696   std::error_code setProtections(ResourceIdMgr::ResourceId Id,
697                                  TargetAddress RemoteSegAddr,
698                                  unsigned ProtFlags) {
699     return call<SetProtections>(Channel, Id, RemoteSegAddr, ProtFlags);
700   }
701
702   std::error_code writeMem(TargetAddress Addr, const char *Src, uint64_t Size) {
703     // Check for an 'out-of-band' error, e.g. from an MM destructor.
704     if (ExistingError)
705       return ExistingError;
706
707     // Make the send call.
708     if (auto EC = call<WriteMem>(Channel, Addr, Size))
709       return EC;
710
711     // Follow this up with the section contents.
712     if (auto EC = Channel.appendBytes(Src, Size))
713       return EC;
714
715     return Channel.send();
716   }
717
718   std::error_code writePointer(TargetAddress Addr, TargetAddress PtrVal) {
719     // Check for an 'out-of-band' error, e.g. from an MM destructor.
720     if (ExistingError)
721       return ExistingError;
722
723     return call<WritePtr>(Channel, Addr, PtrVal);
724   }
725
726   static std::error_code doNothing() { return std::error_code(); }
727
728   ChannelT &Channel;
729   std::error_code ExistingError;
730   std::string RemoteTargetTriple;
731   uint32_t RemotePointerSize;
732   uint32_t RemotePageSize;
733   uint32_t RemoteTrampolineSize;
734   uint32_t RemoteIndirectStubSize;
735   ResourceIdMgr AllocatorIds, IndirectStubOwnerIds;
736   std::function<TargetAddress(TargetAddress)> CompileCallback;
737 };
738
739 } // end namespace remote
740 } // end namespace orc
741 } // end namespace llvm
742
743 #undef DEBUG_TYPE
744
745 #endif