LLVM  5.0.0
OrcRemoteTargetServer.h
Go to the documentation of this file.
1 //===- OrcRemoteTargetServer.h - Orc Remote-target Server -------*- 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 OrcRemoteTargetServer class. It can be used to build a
11 // JIT server that can execute code sent from an OrcRemoteTargetClient.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETSERVER_H
16 #define LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETSERVER_H
17 
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/Host.h"
25 #include "llvm/Support/Memory.h"
26 #include "llvm/Support/Process.h"
28 #include <algorithm>
29 #include <cassert>
30 #include <cstddef>
31 #include <cstdint>
32 #include <functional>
33 #include <map>
34 #include <memory>
35 #include <string>
36 #include <system_error>
37 #include <tuple>
38 #include <type_traits>
39 #include <vector>
40 
41 #define DEBUG_TYPE "orc-remote"
42 
43 namespace llvm {
44 namespace orc {
45 namespace remote {
46 
47 template <typename ChannelT, typename TargetT>
49 public:
50  using SymbolLookupFtor =
51  std::function<JITTargetAddress(const std::string &Name)>;
52 
54  std::function<void(uint8_t *Addr, uint32_t Size)>;
55 
56  OrcRemoteTargetServer(ChannelT &Channel, SymbolLookupFtor SymbolLookup,
57  EHFrameRegistrationFtor EHFramesRegister,
58  EHFrameRegistrationFtor EHFramesDeregister)
59  : OrcRemoteTargetRPCAPI(Channel), SymbolLookup(std::move(SymbolLookup)),
60  EHFramesRegister(std::move(EHFramesRegister)),
61  EHFramesDeregister(std::move(EHFramesDeregister)) {
62  using ThisT = typename std::remove_reference<decltype(*this)>::type;
63  addHandler<CallIntVoid>(*this, &ThisT::handleCallIntVoid);
64  addHandler<CallMain>(*this, &ThisT::handleCallMain);
65  addHandler<CallVoidVoid>(*this, &ThisT::handleCallVoidVoid);
66  addHandler<CreateRemoteAllocator>(*this,
67  &ThisT::handleCreateRemoteAllocator);
68  addHandler<CreateIndirectStubsOwner>(
69  *this, &ThisT::handleCreateIndirectStubsOwner);
70  addHandler<DeregisterEHFrames>(*this, &ThisT::handleDeregisterEHFrames);
71  addHandler<DestroyRemoteAllocator>(*this,
72  &ThisT::handleDestroyRemoteAllocator);
73  addHandler<DestroyIndirectStubsOwner>(
74  *this, &ThisT::handleDestroyIndirectStubsOwner);
75  addHandler<EmitIndirectStubs>(*this, &ThisT::handleEmitIndirectStubs);
76  addHandler<EmitResolverBlock>(*this, &ThisT::handleEmitResolverBlock);
77  addHandler<EmitTrampolineBlock>(*this, &ThisT::handleEmitTrampolineBlock);
78  addHandler<GetSymbolAddress>(*this, &ThisT::handleGetSymbolAddress);
79  addHandler<GetRemoteInfo>(*this, &ThisT::handleGetRemoteInfo);
80  addHandler<ReadMem>(*this, &ThisT::handleReadMem);
81  addHandler<RegisterEHFrames>(*this, &ThisT::handleRegisterEHFrames);
82  addHandler<ReserveMem>(*this, &ThisT::handleReserveMem);
83  addHandler<SetProtections>(*this, &ThisT::handleSetProtections);
84  addHandler<TerminateSession>(*this, &ThisT::handleTerminateSession);
85  addHandler<WriteMem>(*this, &ThisT::handleWriteMem);
86  addHandler<WritePtr>(*this, &ThisT::handleWritePtr);
87  }
88 
89  // FIXME: Remove move/copy ops once MSVC supports synthesizing move ops.
92 
95 
97  return callB<RequestCompile>(TrampolineAddr);
98  }
99 
100  bool receivedTerminate() const { return TerminateFlag; }
101 
102 private:
103  struct Allocator {
104  Allocator() = default;
105  Allocator(Allocator &&Other) : Allocs(std::move(Other.Allocs)) {}
106 
107  Allocator &operator=(Allocator &&Other) {
108  Allocs = std::move(Other.Allocs);
109  return *this;
110  }
111 
112  ~Allocator() {
113  for (auto &Alloc : Allocs)
115  }
116 
117  Error allocate(void *&Addr, size_t Size, uint32_t Align) {
118  std::error_code EC;
119  sys::MemoryBlock MB = sys::Memory::allocateMappedMemory(
120  Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);
121  if (EC)
122  return errorCodeToError(EC);
123 
124  Addr = MB.base();
125  assert(Allocs.find(MB.base()) == Allocs.end() && "Duplicate alloc");
126  Allocs[MB.base()] = std::move(MB);
127  return Error::success();
128  }
129 
130  Error setProtections(void *block, unsigned Flags) {
131  auto I = Allocs.find(block);
132  if (I == Allocs.end())
134  return errorCodeToError(
135  sys::Memory::protectMappedMemory(I->second, Flags));
136  }
137 
138  private:
139  std::map<void *, sys::MemoryBlock> Allocs;
140  };
141 
142  static Error doNothing() { return Error::success(); }
143 
144  static JITTargetAddress reenter(void *JITTargetAddr, void *TrampolineAddr) {
145  auto T = static_cast<OrcRemoteTargetServer *>(JITTargetAddr);
146  auto AddrOrErr = T->requestCompile(static_cast<JITTargetAddress>(
147  reinterpret_cast<uintptr_t>(TrampolineAddr)));
148  // FIXME: Allow customizable failure substitution functions.
149  assert(AddrOrErr && "Compile request failed");
150  return *AddrOrErr;
151  }
152 
153  Expected<int32_t> handleCallIntVoid(JITTargetAddress Addr) {
154  using IntVoidFnTy = int (*)();
155 
156  IntVoidFnTy Fn =
157  reinterpret_cast<IntVoidFnTy>(static_cast<uintptr_t>(Addr));
158 
159  DEBUG(dbgs() << " Calling " << format("0x%016x", Addr) << "\n");
160  int Result = Fn();
161  DEBUG(dbgs() << " Result = " << Result << "\n");
162 
163  return Result;
164  }
165 
166  Expected<int32_t> handleCallMain(JITTargetAddress Addr,
167  std::vector<std::string> Args) {
168  using MainFnTy = int (*)(int, const char *[]);
169 
170  MainFnTy Fn = reinterpret_cast<MainFnTy>(static_cast<uintptr_t>(Addr));
171  int ArgC = Args.size() + 1;
172  int Idx = 1;
173  std::unique_ptr<const char *[]> ArgV(new const char *[ArgC + 1]);
174  ArgV[0] = "<jit process>";
175  for (auto &Arg : Args)
176  ArgV[Idx++] = Arg.c_str();
177  ArgV[ArgC] = 0;
178  DEBUG(
179  for (int Idx = 0; Idx < ArgC; ++Idx) {
180  llvm::dbgs() << "Arg " << Idx << ": " << ArgV[Idx] << "\n";
181  }
182  );
183 
184  DEBUG(dbgs() << " Calling " << format("0x%016x", Addr) << "\n");
185  int Result = Fn(ArgC, ArgV.get());
186  DEBUG(dbgs() << " Result = " << Result << "\n");
187 
188  return Result;
189  }
190 
191  Error handleCallVoidVoid(JITTargetAddress Addr) {
192  using VoidVoidFnTy = void (*)();
193 
194  VoidVoidFnTy Fn =
195  reinterpret_cast<VoidVoidFnTy>(static_cast<uintptr_t>(Addr));
196 
197  DEBUG(dbgs() << " Calling " << format("0x%016x", Addr) << "\n");
198  Fn();
199  DEBUG(dbgs() << " Complete.\n");
200 
201  return Error::success();
202  }
203 
204  Error handleCreateRemoteAllocator(ResourceIdMgr::ResourceId Id) {
205  auto I = Allocators.find(Id);
206  if (I != Allocators.end())
207  return errorCodeToError(
209  DEBUG(dbgs() << " Created allocator " << Id << "\n");
210  Allocators[Id] = Allocator();
211  return Error::success();
212  }
213 
214  Error handleCreateIndirectStubsOwner(ResourceIdMgr::ResourceId Id) {
215  auto I = IndirectStubsOwners.find(Id);
216  if (I != IndirectStubsOwners.end())
217  return errorCodeToError(
219  DEBUG(dbgs() << " Create indirect stubs owner " << Id << "\n");
220  IndirectStubsOwners[Id] = ISBlockOwnerList();
221  return Error::success();
222  }
223 
224  Error handleDeregisterEHFrames(JITTargetAddress TAddr, uint32_t Size) {
225  uint8_t *Addr = reinterpret_cast<uint8_t *>(static_cast<uintptr_t>(TAddr));
226  DEBUG(dbgs() << " Registering EH frames at " << format("0x%016x", TAddr)
227  << ", Size = " << Size << " bytes\n");
228  EHFramesDeregister(Addr, Size);
229  return Error::success();
230  }
231 
232  Error handleDestroyRemoteAllocator(ResourceIdMgr::ResourceId Id) {
233  auto I = Allocators.find(Id);
234  if (I == Allocators.end())
235  return errorCodeToError(
237  Allocators.erase(I);
238  DEBUG(dbgs() << " Destroyed allocator " << Id << "\n");
239  return Error::success();
240  }
241 
242  Error handleDestroyIndirectStubsOwner(ResourceIdMgr::ResourceId Id) {
243  auto I = IndirectStubsOwners.find(Id);
244  if (I == IndirectStubsOwners.end())
245  return errorCodeToError(
247  IndirectStubsOwners.erase(I);
248  return Error::success();
249  }
250 
251  Expected<std::tuple<JITTargetAddress, JITTargetAddress, uint32_t>>
252  handleEmitIndirectStubs(ResourceIdMgr::ResourceId Id,
253  uint32_t NumStubsRequired) {
254  DEBUG(dbgs() << " ISMgr " << Id << " request " << NumStubsRequired
255  << " stubs.\n");
256 
257  auto StubOwnerItr = IndirectStubsOwners.find(Id);
258  if (StubOwnerItr == IndirectStubsOwners.end())
259  return errorCodeToError(
261 
262  typename TargetT::IndirectStubsInfo IS;
263  if (auto Err =
264  TargetT::emitIndirectStubsBlock(IS, NumStubsRequired, nullptr))
265  return std::move(Err);
266 
267  JITTargetAddress StubsBase = static_cast<JITTargetAddress>(
268  reinterpret_cast<uintptr_t>(IS.getStub(0)));
269  JITTargetAddress PtrsBase = static_cast<JITTargetAddress>(
270  reinterpret_cast<uintptr_t>(IS.getPtr(0)));
271  uint32_t NumStubsEmitted = IS.getNumStubs();
272 
273  auto &BlockList = StubOwnerItr->second;
274  BlockList.push_back(std::move(IS));
275 
276  return std::make_tuple(StubsBase, PtrsBase, NumStubsEmitted);
277  }
278 
279  Error handleEmitResolverBlock() {
280  std::error_code EC;
281  ResolverBlock = sys::OwningMemoryBlock(sys::Memory::allocateMappedMemory(
282  TargetT::ResolverCodeSize, nullptr,
284  if (EC)
285  return errorCodeToError(EC);
286 
287  TargetT::writeResolverCode(static_cast<uint8_t *>(ResolverBlock.base()),
288  &reenter, this);
289 
291  ResolverBlock.getMemoryBlock(),
293  }
294 
295  Expected<std::tuple<JITTargetAddress, uint32_t>> handleEmitTrampolineBlock() {
296  std::error_code EC;
297  auto TrampolineBlock =
298  sys::OwningMemoryBlock(sys::Memory::allocateMappedMemory(
299  sys::Process::getPageSize(), nullptr,
301  if (EC)
302  return errorCodeToError(EC);
303 
304  uint32_t NumTrampolines =
305  (sys::Process::getPageSize() - TargetT::PointerSize) /
306  TargetT::TrampolineSize;
307 
308  uint8_t *TrampolineMem = static_cast<uint8_t *>(TrampolineBlock.base());
309  TargetT::writeTrampolines(TrampolineMem, ResolverBlock.base(),
310  NumTrampolines);
311 
312  EC = sys::Memory::protectMappedMemory(TrampolineBlock.getMemoryBlock(),
315 
316  TrampolineBlocks.push_back(std::move(TrampolineBlock));
317 
318  auto TrampolineBaseAddr = static_cast<JITTargetAddress>(
319  reinterpret_cast<uintptr_t>(TrampolineMem));
320 
321  return std::make_tuple(TrampolineBaseAddr, NumTrampolines);
322  }
323 
324  Expected<JITTargetAddress> handleGetSymbolAddress(const std::string &Name) {
325  JITTargetAddress Addr = SymbolLookup(Name);
326  DEBUG(dbgs() << " Symbol '" << Name << "' = " << format("0x%016x", Addr)
327  << "\n");
328  return Addr;
329  }
330 
331  Expected<std::tuple<std::string, uint32_t, uint32_t, uint32_t, uint32_t>>
332  handleGetRemoteInfo() {
333  std::string ProcessTriple = sys::getProcessTriple();
334  uint32_t PointerSize = TargetT::PointerSize;
336  uint32_t TrampolineSize = TargetT::TrampolineSize;
337  uint32_t IndirectStubSize = TargetT::IndirectStubsInfo::StubSize;
338  DEBUG(dbgs() << " Remote info:\n"
339  << " triple = '" << ProcessTriple << "'\n"
340  << " pointer size = " << PointerSize << "\n"
341  << " page size = " << PageSize << "\n"
342  << " trampoline size = " << TrampolineSize << "\n"
343  << " indirect stub size = " << IndirectStubSize << "\n");
344  return std::make_tuple(ProcessTriple, PointerSize, PageSize, TrampolineSize,
345  IndirectStubSize);
346  }
347 
348  Expected<std::vector<uint8_t>> handleReadMem(JITTargetAddress RSrc,
349  uint64_t Size) {
350  uint8_t *Src = reinterpret_cast<uint8_t *>(static_cast<uintptr_t>(RSrc));
351 
352  DEBUG(dbgs() << " Reading " << Size << " bytes from "
353  << format("0x%016x", RSrc) << "\n");
354 
355  std::vector<uint8_t> Buffer;
356  Buffer.resize(Size);
357  for (uint8_t *P = Src; Size != 0; --Size)
358  Buffer.push_back(*P++);
359 
360  return Buffer;
361  }
362 
363  Error handleRegisterEHFrames(JITTargetAddress TAddr, uint32_t Size) {
364  uint8_t *Addr = reinterpret_cast<uint8_t *>(static_cast<uintptr_t>(TAddr));
365  DEBUG(dbgs() << " Registering EH frames at " << format("0x%016x", TAddr)
366  << ", Size = " << Size << " bytes\n");
367  EHFramesRegister(Addr, Size);
368  return Error::success();
369  }
370 
371  Expected<JITTargetAddress> handleReserveMem(ResourceIdMgr::ResourceId Id,
372  uint64_t Size, uint32_t Align) {
373  auto I = Allocators.find(Id);
374  if (I == Allocators.end())
375  return errorCodeToError(
377  auto &Allocator = I->second;
378  void *LocalAllocAddr = nullptr;
379  if (auto Err = Allocator.allocate(LocalAllocAddr, Size, Align))
380  return std::move(Err);
381 
382  DEBUG(dbgs() << " Allocator " << Id << " reserved " << LocalAllocAddr
383  << " (" << Size << " bytes, alignment " << Align << ")\n");
384 
385  JITTargetAddress AllocAddr = static_cast<JITTargetAddress>(
386  reinterpret_cast<uintptr_t>(LocalAllocAddr));
387 
388  return AllocAddr;
389  }
390 
391  Error handleSetProtections(ResourceIdMgr::ResourceId Id,
392  JITTargetAddress Addr, uint32_t Flags) {
393  auto I = Allocators.find(Id);
394  if (I == Allocators.end())
395  return errorCodeToError(
397  auto &Allocator = I->second;
398  void *LocalAddr = reinterpret_cast<void *>(static_cast<uintptr_t>(Addr));
399  DEBUG(dbgs() << " Allocator " << Id << " set permissions on " << LocalAddr
400  << " to " << (Flags & sys::Memory::MF_READ ? 'R' : '-')
401  << (Flags & sys::Memory::MF_WRITE ? 'W' : '-')
402  << (Flags & sys::Memory::MF_EXEC ? 'X' : '-') << "\n");
403  return Allocator.setProtections(LocalAddr, Flags);
404  }
405 
406  Error handleTerminateSession() {
407  TerminateFlag = true;
408  return Error::success();
409  }
410 
411  Error handleWriteMem(DirectBufferWriter DBW) {
412  DEBUG(dbgs() << " Writing " << DBW.getSize() << " bytes to "
413  << format("0x%016x", DBW.getDst()) << "\n");
414  return Error::success();
415  }
416 
417  Error handleWritePtr(JITTargetAddress Addr, JITTargetAddress PtrVal) {
418  DEBUG(dbgs() << " Writing pointer *" << format("0x%016x", Addr) << " = "
419  << format("0x%016x", PtrVal) << "\n");
420  uintptr_t *Ptr =
421  reinterpret_cast<uintptr_t *>(static_cast<uintptr_t>(Addr));
422  *Ptr = static_cast<uintptr_t>(PtrVal);
423  return Error::success();
424  }
425 
426  SymbolLookupFtor SymbolLookup;
427  EHFrameRegistrationFtor EHFramesRegister, EHFramesDeregister;
428  std::map<ResourceIdMgr::ResourceId, Allocator> Allocators;
429  using ISBlockOwnerList = std::vector<typename TargetT::IndirectStubsInfo>;
430  std::map<ResourceIdMgr::ResourceId, ISBlockOwnerList> IndirectStubsOwners;
431  sys::OwningMemoryBlock ResolverBlock;
432  std::vector<sys::OwningMemoryBlock> TrampolineBlocks;
433  bool TerminateFlag = false;
434 };
435 
436 } // end namespace remote
437 } // end namespace orc
438 } // end namespace llvm
439 
440 #undef DEBUG_TYPE
441 
442 #endif // LLVM_EXECUTIONENGINE_ORC_ORCREMOTETARGETSERVER_H
std::function< JITTargetAddress(const std::string &Name)> SymbolLookupFtor
OrcRemoteTargetServer & operator=(const OrcRemoteTargetServer &)=delete
static std::error_code releaseMappedMemory(MemoryBlock &Block)
This method releases a block of memory that was allocated with the allocateMappedMemory method...
static MemoryBlock allocateMappedMemory(size_t NumBytes, const MemoryBlock *const NearBlock, unsigned Flags, std::error_code &EC)
This method allocates a block of memory that is suitable for loading dynamically generated code (e...
std::error_code orcError(OrcErrorCode ErrCode)
Definition: OrcError.cpp:70
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:663
static cl::opt< int > PageSize("imp-null-check-page-size", cl::desc("The page size of the target in bytes"), cl::init(4096))
std::function< void(uint8_t *Addr, uint32_t Size)> EHFrameRegistrationFtor
uint64_t JITTargetAddress
Represents an address in the target process's address space.
Definition: JITSymbol.h:37
const char * Name
MemoryBlock getMemoryBlock() const
Definition: Memory.h:178
format_object< Ts...> format(const char *Fmt, const Ts &...Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
#define P(N)
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:78
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
OrcRemoteTargetServer(ChannelT &Channel, SymbolLookupFtor SymbolLookup, EHFrameRegistrationFtor EHFramesRegister, EHFrameRegistrationFtor EHFramesDeregister)
std::string getProcessTriple()
getProcessTriple() - Return an appropriate target triple for generating code to be loaded into the cu...
Definition: Host.cpp:1487
static unsigned getPageSize()
Basic Register Allocator
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
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
Provides a library for accessing information about this process and other processes on the operating ...
void * base() const
Definition: Memory.h:176
#define I(x, y, z)
Definition: MD5.cpp:58
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
BumpPtrAllocator Alloc
#define DEBUG(X)
Definition: Debug.h:118
int * Ptr
Expected< JITTargetAddress > requestCompile(JITTargetAddress TrampolineAddr)
static std::error_code protectMappedMemory(const MemoryBlock &Block, unsigned Flags)
This method sets the protection flags for a block of memory to the state specified by /p Flags...