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