LLVM  5.0.0
OrcRemoteTargetClient.h
Go to the documentation of this file.
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 RawByteChannel with an
12 // OrcRemoteTargetServer 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 "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Error.h"
30 #include "llvm/Support/Format.h"
32 #include "llvm/Support/Memory.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <cstdint>
37 #include <memory>
38 #include <string>
39 #include <tuple>
40 #include <utility>
41 #include <vector>
42 
43 #define DEBUG_TYPE "orc-remote"
44 
45 namespace llvm {
46 namespace orc {
47 namespace remote {
48 
49 /// This class provides utilities (including memory manager, indirect stubs
50 /// manager, and compile callback manager types) that support remote JITing
51 /// in ORC.
52 ///
53 /// Each of the utility classes talks to a JIT server (an instance of the
54 /// OrcRemoteTargetServer class) via an RPC system (see RPCUtils.h) to carry out
55 /// its actions.
56 template <typename ChannelT>
58 public:
59  /// Remote memory manager.
61  public:
63  : Client(Client), Id(Id) {
64  DEBUG(dbgs() << "Created remote allocator " << Id << "\n");
65  }
66 
67  RCMemoryManager(const RCMemoryManager &) = delete;
68  RCMemoryManager &operator=(const RCMemoryManager &) = delete;
69  RCMemoryManager(RCMemoryManager &&) = default;
71 
72  ~RCMemoryManager() override {
73  Client.destroyRemoteAllocator(Id);
74  DEBUG(dbgs() << "Destroyed remote allocator " << Id << "\n");
75  }
76 
77  uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
78  unsigned SectionID,
79  StringRef SectionName) override {
80  Unmapped.back().CodeAllocs.emplace_back(Size, Alignment);
81  uint8_t *Alloc = reinterpret_cast<uint8_t *>(
82  Unmapped.back().CodeAllocs.back().getLocalAddress());
83  DEBUG(dbgs() << "Allocator " << Id << " allocated code for "
84  << SectionName << ": " << Alloc << " (" << Size
85  << " bytes, alignment " << Alignment << ")\n");
86  return Alloc;
87  }
88 
89  uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
90  unsigned SectionID, StringRef SectionName,
91  bool IsReadOnly) override {
92  if (IsReadOnly) {
93  Unmapped.back().RODataAllocs.emplace_back(Size, Alignment);
94  uint8_t *Alloc = reinterpret_cast<uint8_t *>(
95  Unmapped.back().RODataAllocs.back().getLocalAddress());
96  DEBUG(dbgs() << "Allocator " << Id << " allocated ro-data for "
97  << SectionName << ": " << Alloc << " (" << Size
98  << " bytes, alignment " << Alignment << ")\n");
99  return Alloc;
100  } // else...
101 
102  Unmapped.back().RWDataAllocs.emplace_back(Size, Alignment);
103  uint8_t *Alloc = reinterpret_cast<uint8_t *>(
104  Unmapped.back().RWDataAllocs.back().getLocalAddress());
105  DEBUG(dbgs() << "Allocator " << Id << " allocated rw-data for "
106  << SectionName << ": " << Alloc << " (" << Size
107  << " bytes, alignment " << Alignment << ")\n");
108  return Alloc;
109  }
110 
111  void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
112  uintptr_t RODataSize, uint32_t RODataAlign,
113  uintptr_t RWDataSize,
114  uint32_t RWDataAlign) override {
115  Unmapped.push_back(ObjectAllocs());
116 
117  DEBUG(dbgs() << "Allocator " << Id << " reserved:\n");
118 
119  if (CodeSize != 0) {
120  if (auto AddrOrErr = Client.reserveMem(Id, CodeSize, CodeAlign))
121  Unmapped.back().RemoteCodeAddr = *AddrOrErr;
122  else {
123  // FIXME; Add error to poll.
124  assert(!AddrOrErr.takeError() && "Failed reserving remote memory.");
125  }
126 
127  DEBUG(dbgs() << " code: "
128  << format("0x%016x", Unmapped.back().RemoteCodeAddr)
129  << " (" << CodeSize << " bytes, alignment " << CodeAlign
130  << ")\n");
131  }
132 
133  if (RODataSize != 0) {
134  if (auto AddrOrErr = Client.reserveMem(Id, RODataSize, RODataAlign))
135  Unmapped.back().RemoteRODataAddr = *AddrOrErr;
136  else {
137  // FIXME; Add error to poll.
138  assert(!AddrOrErr.takeError() && "Failed reserving remote memory.");
139  }
140 
141  DEBUG(dbgs() << " ro-data: "
142  << format("0x%016x", Unmapped.back().RemoteRODataAddr)
143  << " (" << RODataSize << " bytes, alignment "
144  << RODataAlign << ")\n");
145  }
146 
147  if (RWDataSize != 0) {
148  if (auto AddrOrErr = Client.reserveMem(Id, RWDataSize, RWDataAlign))
149  Unmapped.back().RemoteRWDataAddr = *AddrOrErr;
150  else {
151  // FIXME; Add error to poll.
152  assert(!AddrOrErr.takeError() && "Failed reserving remote memory.");
153  }
154 
155  DEBUG(dbgs() << " rw-data: "
156  << format("0x%016x", Unmapped.back().RemoteRWDataAddr)
157  << " (" << RWDataSize << " bytes, alignment "
158  << RWDataAlign << ")\n");
159  }
160  }
161 
162  bool needsToReserveAllocationSpace() override { return true; }
163 
164  void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
165  size_t Size) override {
166  UnfinalizedEHFrames.push_back({LoadAddr, Size});
167  }
168 
169  void deregisterEHFrames() override {
170  for (auto &Frame : RegisteredEHFrames) {
171  auto Err = Client.deregisterEHFrames(Frame.Addr, Frame.Size);
172  // FIXME: Add error poll.
173  assert(!Err && "Failed to register remote EH frames.");
174  (void)Err;
175  }
176  }
177 
179  const object::ObjectFile &Obj) override {
180  DEBUG(dbgs() << "Allocator " << Id << " applied mappings:\n");
181  for (auto &ObjAllocs : Unmapped) {
182  {
183  JITTargetAddress NextCodeAddr = ObjAllocs.RemoteCodeAddr;
184  for (auto &Alloc : ObjAllocs.CodeAllocs) {
185  NextCodeAddr = alignTo(NextCodeAddr, Alloc.getAlign());
186  Dyld.mapSectionAddress(Alloc.getLocalAddress(), NextCodeAddr);
187  DEBUG(dbgs() << " code: "
188  << static_cast<void *>(Alloc.getLocalAddress())
189  << " -> " << format("0x%016x", NextCodeAddr) << "\n");
190  Alloc.setRemoteAddress(NextCodeAddr);
191  NextCodeAddr += Alloc.getSize();
192  }
193  }
194  {
195  JITTargetAddress NextRODataAddr = ObjAllocs.RemoteRODataAddr;
196  for (auto &Alloc : ObjAllocs.RODataAllocs) {
197  NextRODataAddr = alignTo(NextRODataAddr, Alloc.getAlign());
198  Dyld.mapSectionAddress(Alloc.getLocalAddress(), NextRODataAddr);
199  DEBUG(dbgs() << " ro-data: "
200  << static_cast<void *>(Alloc.getLocalAddress())
201  << " -> " << format("0x%016x", NextRODataAddr)
202  << "\n");
203  Alloc.setRemoteAddress(NextRODataAddr);
204  NextRODataAddr += Alloc.getSize();
205  }
206  }
207  {
208  JITTargetAddress NextRWDataAddr = ObjAllocs.RemoteRWDataAddr;
209  for (auto &Alloc : ObjAllocs.RWDataAllocs) {
210  NextRWDataAddr = alignTo(NextRWDataAddr, Alloc.getAlign());
211  Dyld.mapSectionAddress(Alloc.getLocalAddress(), NextRWDataAddr);
212  DEBUG(dbgs() << " rw-data: "
213  << static_cast<void *>(Alloc.getLocalAddress())
214  << " -> " << format("0x%016x", NextRWDataAddr)
215  << "\n");
216  Alloc.setRemoteAddress(NextRWDataAddr);
217  NextRWDataAddr += Alloc.getSize();
218  }
219  }
220  Unfinalized.push_back(std::move(ObjAllocs));
221  }
222  Unmapped.clear();
223  }
224 
225  bool finalizeMemory(std::string *ErrMsg = nullptr) override {
226  DEBUG(dbgs() << "Allocator " << Id << " finalizing:\n");
227 
228  for (auto &ObjAllocs : Unfinalized) {
229  for (auto &Alloc : ObjAllocs.CodeAllocs) {
230  DEBUG(dbgs() << " copying code: "
231  << static_cast<void *>(Alloc.getLocalAddress()) << " -> "
232  << format("0x%016x", Alloc.getRemoteAddress()) << " ("
233  << Alloc.getSize() << " bytes)\n");
234  if (auto Err =
235  Client.writeMem(Alloc.getRemoteAddress(),
236  Alloc.getLocalAddress(), Alloc.getSize())) {
237  // FIXME: Replace this once finalizeMemory can return an Error.
238  handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
239  if (ErrMsg) {
240  raw_string_ostream ErrOut(*ErrMsg);
241  EIB.log(ErrOut);
242  }
243  });
244  return true;
245  }
246  }
247 
248  if (ObjAllocs.RemoteCodeAddr) {
249  DEBUG(dbgs() << " setting R-X permissions on code block: "
250  << format("0x%016x", ObjAllocs.RemoteCodeAddr) << "\n");
251  if (auto Err = Client.setProtections(Id, ObjAllocs.RemoteCodeAddr,
254  // FIXME: Replace this once finalizeMemory can return an Error.
255  handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
256  if (ErrMsg) {
257  raw_string_ostream ErrOut(*ErrMsg);
258  EIB.log(ErrOut);
259  }
260  });
261  return true;
262  }
263  }
264 
265  for (auto &Alloc : ObjAllocs.RODataAllocs) {
266  DEBUG(dbgs() << " copying ro-data: "
267  << static_cast<void *>(Alloc.getLocalAddress()) << " -> "
268  << format("0x%016x", Alloc.getRemoteAddress()) << " ("
269  << Alloc.getSize() << " bytes)\n");
270  if (auto Err =
271  Client.writeMem(Alloc.getRemoteAddress(),
272  Alloc.getLocalAddress(), Alloc.getSize())) {
273  // FIXME: Replace this once finalizeMemory can return an Error.
274  handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
275  if (ErrMsg) {
276  raw_string_ostream ErrOut(*ErrMsg);
277  EIB.log(ErrOut);
278  }
279  });
280  return true;
281  }
282  }
283 
284  if (ObjAllocs.RemoteRODataAddr) {
285  DEBUG(dbgs() << " setting R-- permissions on ro-data block: "
286  << format("0x%016x", ObjAllocs.RemoteRODataAddr)
287  << "\n");
288  if (auto Err = Client.setProtections(Id, ObjAllocs.RemoteRODataAddr,
290  // FIXME: Replace this once finalizeMemory can return an Error.
291  handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
292  if (ErrMsg) {
293  raw_string_ostream ErrOut(*ErrMsg);
294  EIB.log(ErrOut);
295  }
296  });
297  return false;
298  }
299  }
300 
301  for (auto &Alloc : ObjAllocs.RWDataAllocs) {
302  DEBUG(dbgs() << " copying rw-data: "
303  << static_cast<void *>(Alloc.getLocalAddress()) << " -> "
304  << format("0x%016x", Alloc.getRemoteAddress()) << " ("
305  << Alloc.getSize() << " bytes)\n");
306  if (auto Err =
307  Client.writeMem(Alloc.getRemoteAddress(),
308  Alloc.getLocalAddress(), Alloc.getSize())) {
309  // FIXME: Replace this once finalizeMemory can return an Error.
310  handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
311  if (ErrMsg) {
312  raw_string_ostream ErrOut(*ErrMsg);
313  EIB.log(ErrOut);
314  }
315  });
316  return false;
317  }
318  }
319 
320  if (ObjAllocs.RemoteRWDataAddr) {
321  DEBUG(dbgs() << " setting RW- permissions on rw-data block: "
322  << format("0x%016x", ObjAllocs.RemoteRWDataAddr)
323  << "\n");
324  if (auto Err = Client.setProtections(Id, ObjAllocs.RemoteRWDataAddr,
327  // FIXME: Replace this once finalizeMemory can return an Error.
328  handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
329  if (ErrMsg) {
330  raw_string_ostream ErrOut(*ErrMsg);
331  EIB.log(ErrOut);
332  }
333  });
334  return false;
335  }
336  }
337  }
338  Unfinalized.clear();
339 
340  for (auto &EHFrame : UnfinalizedEHFrames) {
341  if (auto Err = Client.registerEHFrames(EHFrame.Addr, EHFrame.Size)) {
342  // FIXME: Replace this once finalizeMemory can return an Error.
343  handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
344  if (ErrMsg) {
345  raw_string_ostream ErrOut(*ErrMsg);
346  EIB.log(ErrOut);
347  }
348  });
349  return false;
350  }
351  }
352  RegisteredEHFrames = std::move(UnfinalizedEHFrames);
353  UnfinalizedEHFrames = {};
354 
355  return false;
356  }
357 
358  private:
359  class Alloc {
360  public:
361  Alloc(uint64_t Size, unsigned Align)
362  : Size(Size), Align(Align), Contents(new char[Size + Align - 1]) {}
363 
364  Alloc(const Alloc &) = delete;
365  Alloc &operator=(const Alloc &) = delete;
366  Alloc(Alloc &&) = default;
367  Alloc &operator=(Alloc &&) = default;
368 
369  uint64_t getSize() const { return Size; }
370 
371  unsigned getAlign() const { return Align; }
372 
373  char *getLocalAddress() const {
374  uintptr_t LocalAddr = reinterpret_cast<uintptr_t>(Contents.get());
375  LocalAddr = alignTo(LocalAddr, Align);
376  return reinterpret_cast<char *>(LocalAddr);
377  }
378 
379  void setRemoteAddress(JITTargetAddress RemoteAddr) {
380  this->RemoteAddr = RemoteAddr;
381  }
382 
383  JITTargetAddress getRemoteAddress() const { return RemoteAddr; }
384 
385  private:
386  uint64_t Size;
387  unsigned Align;
388  std::unique_ptr<char[]> Contents;
389  JITTargetAddress RemoteAddr = 0;
390  };
391 
392  struct ObjectAllocs {
393  ObjectAllocs() = default;
394  ObjectAllocs(const ObjectAllocs &) = delete;
395  ObjectAllocs &operator=(const ObjectAllocs &) = delete;
396  ObjectAllocs(ObjectAllocs &&) = default;
397  ObjectAllocs &operator=(ObjectAllocs &&) = default;
398 
399  JITTargetAddress RemoteCodeAddr = 0;
400  JITTargetAddress RemoteRODataAddr = 0;
401  JITTargetAddress RemoteRWDataAddr = 0;
402  std::vector<Alloc> CodeAllocs, RODataAllocs, RWDataAllocs;
403  };
404 
405  OrcRemoteTargetClient &Client;
407  std::vector<ObjectAllocs> Unmapped;
408  std::vector<ObjectAllocs> Unfinalized;
409 
410  struct EHFrame {
411  JITTargetAddress Addr;
412  uint64_t Size;
413  };
414  std::vector<EHFrame> UnfinalizedEHFrames;
415  std::vector<EHFrame> RegisteredEHFrames;
416  };
417 
418  /// Remote indirect stubs manager.
420  public:
423  : Remote(Remote), Id(Id) {}
424 
426  if (auto Err = Remote.destroyIndirectStubsManager(Id)) {
427  // FIXME: Thread this error back to clients.
428  consumeError(std::move(Err));
429  }
430  }
431 
433  JITSymbolFlags StubFlags) override {
434  if (auto Err = reserveStubs(1))
435  return Err;
436 
437  return createStubInternal(StubName, StubAddr, StubFlags);
438  }
439 
440  Error createStubs(const StubInitsMap &StubInits) override {
441  if (auto Err = reserveStubs(StubInits.size()))
442  return Err;
443 
444  for (auto &Entry : StubInits)
445  if (auto Err = createStubInternal(Entry.first(), Entry.second.first,
446  Entry.second.second))
447  return Err;
448 
449  return Error::success();
450  }
451 
452  JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override {
453  auto I = StubIndexes.find(Name);
454  if (I == StubIndexes.end())
455  return nullptr;
456  auto Key = I->second.first;
457  auto Flags = I->second.second;
458  auto StubSymbol = JITSymbol(getStubAddr(Key), Flags);
459  if (ExportedStubsOnly && !StubSymbol.getFlags().isExported())
460  return nullptr;
461  return StubSymbol;
462  }
463 
465  auto I = StubIndexes.find(Name);
466  if (I == StubIndexes.end())
467  return nullptr;
468  auto Key = I->second.first;
469  auto Flags = I->second.second;
470  return JITSymbol(getPtrAddr(Key), Flags);
471  }
472 
474  auto I = StubIndexes.find(Name);
475  assert(I != StubIndexes.end() && "No stub pointer for symbol");
476  auto Key = I->second.first;
477  return Remote.writePointer(getPtrAddr(Key), NewAddr);
478  }
479 
480  private:
481  struct RemoteIndirectStubsInfo {
482  JITTargetAddress StubBase;
483  JITTargetAddress PtrBase;
484  unsigned NumStubs;
485  };
486 
487  OrcRemoteTargetClient &Remote;
489  std::vector<RemoteIndirectStubsInfo> RemoteIndirectStubsInfos;
490  using StubKey = std::pair<uint16_t, uint16_t>;
491  std::vector<StubKey> FreeStubs;
493 
494  Error reserveStubs(unsigned NumStubs) {
495  if (NumStubs <= FreeStubs.size())
496  return Error::success();
497 
498  unsigned NewStubsRequired = NumStubs - FreeStubs.size();
499  JITTargetAddress StubBase;
500  JITTargetAddress PtrBase;
501  unsigned NumStubsEmitted;
502 
503  if (auto StubInfoOrErr = Remote.emitIndirectStubs(Id, NewStubsRequired))
504  std::tie(StubBase, PtrBase, NumStubsEmitted) = *StubInfoOrErr;
505  else
506  return StubInfoOrErr.takeError();
507 
508  unsigned NewBlockId = RemoteIndirectStubsInfos.size();
509  RemoteIndirectStubsInfos.push_back({StubBase, PtrBase, NumStubsEmitted});
510 
511  for (unsigned I = 0; I < NumStubsEmitted; ++I)
512  FreeStubs.push_back(std::make_pair(NewBlockId, I));
513 
514  return Error::success();
515  }
516 
517  Error createStubInternal(StringRef StubName, JITTargetAddress InitAddr,
518  JITSymbolFlags StubFlags) {
519  auto Key = FreeStubs.back();
520  FreeStubs.pop_back();
521  StubIndexes[StubName] = std::make_pair(Key, StubFlags);
522  return Remote.writePointer(getPtrAddr(Key), InitAddr);
523  }
524 
525  JITTargetAddress getStubAddr(StubKey K) {
526  assert(RemoteIndirectStubsInfos[K.first].StubBase != 0 &&
527  "Missing stub address");
528  return RemoteIndirectStubsInfos[K.first].StubBase +
529  K.second * Remote.getIndirectStubSize();
530  }
531 
532  JITTargetAddress getPtrAddr(StubKey K) {
533  assert(RemoteIndirectStubsInfos[K.first].PtrBase != 0 &&
534  "Missing pointer address");
535  return RemoteIndirectStubsInfos[K.first].PtrBase +
536  K.second * Remote.getPointerSize();
537  }
538  };
539 
540  /// Remote compile callback manager.
542  public:
544  OrcRemoteTargetClient &Remote)
545  : JITCompileCallbackManager(ErrorHandlerAddress), Remote(Remote) {}
546 
547  private:
548  void grow() override {
549  JITTargetAddress BlockAddr = 0;
550  uint32_t NumTrampolines = 0;
551  if (auto TrampolineInfoOrErr = Remote.emitTrampolineBlock())
552  std::tie(BlockAddr, NumTrampolines) = *TrampolineInfoOrErr;
553  else {
554  // FIXME: Return error.
555  llvm_unreachable("Failed to create trampolines");
556  }
557 
558  uint32_t TrampolineSize = Remote.getTrampolineSize();
559  for (unsigned I = 0; I < NumTrampolines; ++I)
560  this->AvailableTrampolines.push_back(BlockAddr + (I * TrampolineSize));
561  }
562 
563  OrcRemoteTargetClient &Remote;
564  };
565 
566  /// Create an OrcRemoteTargetClient.
567  /// Channel is the ChannelT instance to communicate on. It is assumed that
568  /// the channel is ready to be read from and written to.
570  Create(ChannelT &Channel) {
571  Error Err = Error::success();
572  std::unique_ptr<OrcRemoteTargetClient> Client(
573  new OrcRemoteTargetClient(Channel, Err));
574  if (Err)
575  return std::move(Err);
576  return std::move(Client);
577  }
578 
579  /// Call the int(void) function at the given address in the target and return
580  /// its result.
582  DEBUG(dbgs() << "Calling int(*)(void) " << format("0x%016x", Addr) << "\n");
583  return callB<CallIntVoid>(Addr);
584  }
585 
586  /// Call the int(int, char*[]) function at the given address in the target and
587  /// return its result.
589  const std::vector<std::string> &Args) {
590  DEBUG(dbgs() << "Calling int(*)(int, char*[]) " << format("0x%016x", Addr)
591  << "\n");
592  return callB<CallMain>(Addr, Args);
593  }
594 
595  /// Call the void() function at the given address in the target and wait for
596  /// it to finish.
598  DEBUG(dbgs() << "Calling void(*)(void) " << format("0x%016x", Addr)
599  << "\n");
600  return callB<CallVoidVoid>(Addr);
601  }
602 
603  /// Create an RCMemoryManager which will allocate its memory on the remote
604  /// target.
605  Error createRemoteMemoryManager(std::unique_ptr<RCMemoryManager> &MM) {
606  assert(!MM && "MemoryManager should be null before creation.");
607 
608  auto Id = AllocatorIds.getNext();
609  if (auto Err = callB<CreateRemoteAllocator>(Id))
610  return Err;
611  MM = llvm::make_unique<RCMemoryManager>(*this, Id);
612  return Error::success();
613  }
614 
615  /// Create an RCIndirectStubsManager that will allocate stubs on the remote
616  /// target.
617  Error createIndirectStubsManager(std::unique_ptr<RCIndirectStubsManager> &I) {
618  assert(!I && "Indirect stubs manager should be null before creation.");
619  auto Id = IndirectStubOwnerIds.getNext();
620  if (auto Err = callB<CreateIndirectStubsOwner>(Id))
621  return Err;
622  I = llvm::make_unique<RCIndirectStubsManager>(*this, Id);
623  return Error::success();
624  }
625 
628  // Check for an 'out-of-band' error, e.g. from an MM destructor.
629  if (ExistingError)
630  return std::move(ExistingError);
631 
632  // Emit the resolver block on the JIT server.
633  if (auto Err = callB<EmitResolverBlock>())
634  return std::move(Err);
635 
636  // Create the callback manager.
637  CallbackManager.emplace(ErrorHandlerAddress, *this);
638  RCCompileCallbackManager &Mgr = *CallbackManager;
639  return Mgr;
640  }
641 
642  /// Search for symbols in the remote process. Note: This should be used by
643  /// symbol resolvers *after* they've searched the local symbol table in the
644  /// JIT stack.
646  // Check for an 'out-of-band' error, e.g. from an MM destructor.
647  if (ExistingError)
648  return std::move(ExistingError);
649 
650  return callB<GetSymbolAddress>(Name);
651  }
652 
653  /// Get the triple for the remote target.
654  const std::string &getTargetTriple() const { return RemoteTargetTriple; }
655 
656  Error terminateSession() { return callB<TerminateSession>(); }
657 
658 private:
659  OrcRemoteTargetClient(ChannelT &Channel, Error &Err)
660  : OrcRemoteTargetRPCAPI(Channel) {
661  ErrorAsOutParameter EAO(&Err);
662 
663  addHandler<RequestCompile>(
664  [this](JITTargetAddress Addr) -> JITTargetAddress {
665  if (CallbackManager)
666  return CallbackManager->executeCompileCallback(Addr);
667  return 0;
668  });
669 
670  if (auto RIOrErr = callB<GetRemoteInfo>()) {
671  std::tie(RemoteTargetTriple, RemotePointerSize, RemotePageSize,
672  RemoteTrampolineSize, RemoteIndirectStubSize) = *RIOrErr;
673  Err = Error::success();
674  } else {
675  Err = joinErrors(RIOrErr.takeError(), std::move(ExistingError));
676  }
677  }
678 
679  Error deregisterEHFrames(JITTargetAddress Addr, uint32_t Size) {
680  return callB<RegisterEHFrames>(Addr, Size);
681  }
682 
683  void destroyRemoteAllocator(ResourceIdMgr::ResourceId Id) {
684  if (auto Err = callB<DestroyRemoteAllocator>(Id)) {
685  // FIXME: This will be triggered by a removeModuleSet call: Propagate
686  // error return up through that.
687  llvm_unreachable("Failed to destroy remote allocator.");
688  AllocatorIds.release(Id);
689  }
690  }
691 
692  Error destroyIndirectStubsManager(ResourceIdMgr::ResourceId Id) {
693  IndirectStubOwnerIds.release(Id);
694  return callB<DestroyIndirectStubsOwner>(Id);
695  }
696 
697  Expected<std::tuple<JITTargetAddress, JITTargetAddress, uint32_t>>
698  emitIndirectStubs(ResourceIdMgr::ResourceId Id, uint32_t NumStubsRequired) {
699  return callB<EmitIndirectStubs>(Id, NumStubsRequired);
700  }
701 
702  Expected<std::tuple<JITTargetAddress, uint32_t>> emitTrampolineBlock() {
703  // Check for an 'out-of-band' error, e.g. from an MM destructor.
704  if (ExistingError)
705  return std::move(ExistingError);
706 
707  return callB<EmitTrampolineBlock>();
708  }
709 
710  uint32_t getIndirectStubSize() const { return RemoteIndirectStubSize; }
711  uint32_t getPageSize() const { return RemotePageSize; }
712  uint32_t getPointerSize() const { return RemotePointerSize; }
713 
714  uint32_t getTrampolineSize() const { return RemoteTrampolineSize; }
715 
716  Expected<std::vector<char>> readMem(char *Dst, JITTargetAddress Src,
717  uint64_t Size) {
718  // Check for an 'out-of-band' error, e.g. from an MM destructor.
719  if (ExistingError)
720  return std::move(ExistingError);
721 
722  return callB<ReadMem>(Src, Size);
723  }
724 
725  Error registerEHFrames(JITTargetAddress &RAddr, uint32_t Size) {
726  return callB<RegisterEHFrames>(RAddr, Size);
727  }
728 
729  Expected<JITTargetAddress> reserveMem(ResourceIdMgr::ResourceId Id,
730  uint64_t Size, uint32_t Align) {
731  // Check for an 'out-of-band' error, e.g. from an MM destructor.
732  if (ExistingError)
733  return std::move(ExistingError);
734 
735  return callB<ReserveMem>(Id, Size, Align);
736  }
737 
738  Error setProtections(ResourceIdMgr::ResourceId Id,
739  JITTargetAddress RemoteSegAddr, unsigned ProtFlags) {
740  return callB<SetProtections>(Id, RemoteSegAddr, ProtFlags);
741  }
742 
743  Error writeMem(JITTargetAddress Addr, const char *Src, uint64_t Size) {
744  // Check for an 'out-of-band' error, e.g. from an MM destructor.
745  if (ExistingError)
746  return std::move(ExistingError);
747 
748  return callB<WriteMem>(DirectBufferWriter(Src, Addr, Size));
749  }
750 
751  Error writePointer(JITTargetAddress Addr, JITTargetAddress PtrVal) {
752  // Check for an 'out-of-band' error, e.g. from an MM destructor.
753  if (ExistingError)
754  return std::move(ExistingError);
755 
756  return callB<WritePtr>(Addr, PtrVal);
757  }
758 
759  static Error doNothing() { return Error::success(); }
760 
761  Error ExistingError = Error::success();
762  std::string RemoteTargetTriple;
763  uint32_t RemotePointerSize = 0;
764  uint32_t RemotePageSize = 0;
765  uint32_t RemoteTrampolineSize = 0;
766  uint32_t RemoteIndirectStubSize = 0;
767  ResourceIdMgr AllocatorIds, IndirectStubOwnerIds;
768  Optional<RCCompileCallbackManager> CallbackManager;
769 };
770 
771 } // end namespace remote
772 } // end namespace orc
773 } // end namespace llvm
774 
775 #undef DEBUG_TYPE
776 
777 #endif // LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETCLIENT_H
bool finalizeMemory(std::string *ErrMsg=nullptr) override
This method is called when object loading is complete and section page permissions can be applied...
Base class for managing collections of named indirect stubs.
Represents a symbol in the JIT.
Definition: JITSymbol.h:122
bool getAlign(const Function &F, unsigned index, unsigned &align)
This class is the base class for all object file types.
Definition: ObjectFile.h:189
Expected< RCCompileCallbackManager & > enableCompileCallbacks(JITTargetAddress ErrorHandlerAddress)
Error callVoidVoid(JITTargetAddress Addr)
Call the void() function at the given address in the target and wait for it to finish.
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
RCIndirectStubsManager(OrcRemoteTargetClient &Remote, ResourceIdMgr::ResourceId Id)
void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign, uintptr_t RODataSize, uint32_t RODataAlign, uintptr_t RWDataSize, uint32_t RWDataAlign) override
Inform the memory manager about the total amount of memory required to allocate all sections to be lo...
void notifyObjectLoaded(RuntimeDyld &Dyld, const object::ObjectFile &Obj) override
This method is called after an object has been loaded into memory but before relocations are applied ...
Base class for error info classes.
Definition: Error.h:47
Expected< int > callIntVoid(JITTargetAddress Addr)
Call the int(void) function at the given address in the target and return its result.
Target-independent base class for compile callback management.
RCMemoryManager & operator=(const RCMemoryManager &)=delete
Expected< JITTargetAddress > getSymbolAddress(StringRef Name)
Search for symbols in the remote process.
virtual void log(raw_ostream &OS) const =0
Print an error message to an output stream.
JITSymbol findPointer(StringRef Name) override
Find the implementation-pointer for the stub.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
JITSymbol findStub(StringRef Name, bool ExportedStubsOnly) override
Find the stub with the given name.
RCCompileCallbackManager(JITTargetAddress ErrorHandlerAddress, OrcRemoteTargetClient &Remote)
uint64_t JITTargetAddress
Represents an address in the target process's address space.
Definition: JITSymbol.h:37
Expected< int > callMain(JITTargetAddress Addr, const std::vector< std::string > &Args)
Call the int(int, char*[]) function at the given address in the target and return its result...
void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override
Register the EH frames with the runtime so that c++ exceptions work.
std::vector< JITTargetAddress > AvailableTrampolines
const char * Name
format_object< Ts...> format(const char *Fmt, const Ts &...Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
Error createStubs(const StubInitsMap &StubInits) override
Create StubInits.size() stubs with the given names, target addresses, and flags.
std::string ErrMsg
Error createStub(StringRef StubName, JITTargetAddress StubAddr, JITSymbolFlags StubFlags) override
Create a single stub with the given name, target address and flags.
RCMemoryManager(OrcRemoteTargetClient &Client, ResourceIdMgr::ResourceId Id)
uint8_t * allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly) override
Allocate a memory block of (at least) the given size suitable for data.
Error createRemoteMemoryManager(std::unique_ptr< RCMemoryManager > &MM)
Create an RCMemoryManager which will allocate its memory on the remote target.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
unsigned size() const
Definition: StringMap.h:111
This class provides utilities (including memory manager, indirect stubs manager, and compile callback...
Flags for symbols in the JIT.
Definition: JITSymbol.h:40
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
Definition: Error.h:555
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:593
static ErrorSuccess success()
Create a success value.
Definition: Error.h:311
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:220
Error createIndirectStubsManager(std::unique_ptr< RCIndirectStubsManager > &I)
Create an RCIndirectStubsManager that will allocate stubs on the remote target.
Helper for Errors used as out-parameters.
Definition: Error.h:621
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:406
#define I(x, y, z)
Definition: MD5.cpp:58
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
static Expected< std::unique_ptr< OrcRemoteTargetClient > > Create(ChannelT &Channel)
Create an OrcRemoteTargetClient.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
uint8_t * allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) override
Allocate a memory block of (at least) the given size suitable for executable code.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:463
Error updatePointer(StringRef Name, JITTargetAddress NewAddr) override
Change the value of the implementation pointer for the stub.
bool needsToReserveAllocationSpace() override
Override to return true to enable the reserveAllocationSpace callback.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
BumpPtrAllocator Alloc
const char SectionName[]
Definition: AMDGPUPTNote.h:24
#define DEBUG(X)
Definition: Debug.h:118
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress)
Map a section to its target address space value.
const std::string & getTargetTriple() const
Get the triple for the remote target.