JITThunkEmitter.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "Backend.h"
  6. #if defined(ENABLE_NATIVE_CODEGEN) && defined(_CONTROL_FLOW_GUARD) && !defined(_M_ARM)
  7. template class JITThunkEmitter<VirtualAllocWrapper>;
  8. #if ENABLE_OOP_NATIVE_CODEGEN
  9. template class JITThunkEmitter<SectionAllocWrapper>;
  10. #endif
  11. #if _M_IX86 || _M_X64
  12. template <typename TAlloc>
  13. const BYTE JITThunkEmitter<TAlloc>::DirectJmp[] = {
  14. 0xE9, 0x00, 0x00, 0x00, 0x00, // JMP <relativeAddress>.32
  15. 0xCC, 0xCC, 0xCC,
  16. 0xCC, 0xCC, 0xCC, 0xCC,
  17. 0xCC, 0xCC, 0xCC, 0xCC
  18. };
  19. #endif
  20. #if _M_X64
  21. template <typename TAlloc>
  22. const BYTE JITThunkEmitter<TAlloc>::IndirectJmp[] = {
  23. 0x48, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // MOV RAX, <relativeAddress>.64
  24. 0x48, 0xFF, 0xE0, // JMP RAX
  25. 0xCC, 0xCC, 0xCC
  26. };
  27. #endif
  28. #if _M_ARM64
  29. template <typename TAlloc>
  30. const DWORD JITThunkEmitter<TAlloc>::DirectB[] = {
  31. 0x14000000 // B <relativeAddress>.26
  32. };
  33. template <typename TAlloc>
  34. const DWORD JITThunkEmitter<TAlloc>::IndirectBR[] = {
  35. 0xd2800000 | IndirectBRTempReg, // MOVZ x17, <absoluteAddress[16:0]>
  36. 0xf2a00000 | IndirectBRTempReg, // MOVK x17, <absoluteAddress[31:16]>, LSL #16
  37. 0xf2c00000 | IndirectBRTempReg, // MOVK x17, <absoluteAddress[47:32]>, LSL #32
  38. 0xd61f0000 | (IndirectBRTempReg<<5) // BR x17
  39. };
  40. #endif
  41. template <typename TAlloc>
  42. JITThunkEmitter<TAlloc>::JITThunkEmitter(ThreadContextInfo * threadContext, TAlloc * codeAllocator, HANDLE processHandle) :
  43. processHandle(processHandle),
  44. codeAllocator(codeAllocator),
  45. threadContext(threadContext),
  46. baseAddress(NULL),
  47. firstBitToCheck(0)
  48. {
  49. freeThunks.SetAll();
  50. }
  51. template <typename TAlloc>
  52. JITThunkEmitter<TAlloc>::~JITThunkEmitter()
  53. {
  54. if (baseAddress != NULL)
  55. {
  56. this->codeAllocator->Free((PVOID)baseAddress, TotalThunkSize, MEM_RELEASE);
  57. }
  58. }
  59. template <typename TAlloc> inline
  60. uintptr_t
  61. JITThunkEmitter<TAlloc>::CreateThunk(uintptr_t entryPoint)
  62. {
  63. AutoCriticalSection autoCs(&this->cs);
  64. if(EnsureInitialized() == NULL)
  65. {
  66. return NULL;
  67. }
  68. // find available thunk
  69. BVIndex thunkIndex = this->freeThunks.GetNextBit(this->firstBitToCheck);
  70. if (thunkIndex == BVInvalidIndex)
  71. {
  72. return NULL;
  73. }
  74. uintptr_t thunkAddress = GetThunkAddressFromIndex(thunkIndex);
  75. uintptr_t pageStartAddress = GetThunkPageStart(thunkAddress);
  76. char * localPageAddress = (char *)this->codeAllocator->AllocLocal((PVOID)pageStartAddress, AutoSystemInfo::PageSize);
  77. if (localPageAddress == nullptr)
  78. {
  79. return NULL;
  80. }
  81. if (IsThunkPageEmpty(pageStartAddress))
  82. {
  83. if (this->codeAllocator->AllocPages((PVOID)pageStartAddress, 1, MEM_COMMIT, PAGE_EXECUTE_READ, true) == nullptr)
  84. {
  85. this->codeAllocator->FreeLocal(localPageAddress);
  86. return NULL;
  87. }
  88. UnprotectPage(localPageAddress);
  89. memset(localPageAddress, 0xCC, AutoSystemInfo::PageSize);
  90. }
  91. else
  92. {
  93. UnprotectPage(localPageAddress);
  94. }
  95. EncodeJmp(localPageAddress, thunkAddress, entryPoint);
  96. ProtectPage(localPageAddress);
  97. this->codeAllocator->FreeLocal(localPageAddress);
  98. if (CONFIG_FLAG(OOPCFGRegistration))
  99. {
  100. #if ENABLE_OOP_NATIVE_CODEGEN
  101. if (JITManager::GetJITManager()->IsJITServer())
  102. {
  103. HANDLE fileHandle = nullptr;
  104. PVOID baseAddress = nullptr;
  105. bool found = this->codeAllocator->GetFileInfo((PVOID)thunkAddress, &fileHandle, &baseAddress);
  106. AssertOrFailFast(found);
  107. this->threadContext->SetValidCallTargetFile((PVOID)thunkAddress, fileHandle, baseAddress, true);
  108. }
  109. else
  110. #endif
  111. {
  112. this->threadContext->SetValidCallTargetForCFG((PVOID)thunkAddress);
  113. }
  114. }
  115. this->firstBitToCheck = (thunkIndex + 1 < JITThunkEmitter<TAlloc>::TotalThunkCount) ? thunkIndex + 1 : 0;
  116. this->freeThunks.Clear(thunkIndex);
  117. if (!FlushInstructionCache(this->processHandle, (PVOID)thunkAddress, ThunkSize))
  118. {
  119. return NULL;
  120. }
  121. return thunkAddress;
  122. }
  123. template <typename TAlloc> inline
  124. void
  125. JITThunkEmitter<TAlloc>::FreeThunk(uintptr_t thunkAddress)
  126. {
  127. AutoCriticalSection autoCs(&this->cs);
  128. BVIndex thunkIndex = GetThunkIndexFromAddress(thunkAddress);
  129. if (thunkIndex >= this->freeThunks.Length() || this->freeThunks.TestAndSet(thunkIndex))
  130. {
  131. Assert(UNREACHED);
  132. this->firstBitToCheck = 0;
  133. return;
  134. }
  135. if (thunkIndex < firstBitToCheck)
  136. {
  137. this->firstBitToCheck = thunkIndex;
  138. }
  139. if (CONFIG_FLAG(OOPCFGRegistration))
  140. {
  141. #if ENABLE_OOP_NATIVE_CODEGEN
  142. if (JITManager::GetJITManager()->IsJITServer())
  143. {
  144. HANDLE fileHandle = nullptr;
  145. PVOID baseAddress = nullptr;
  146. bool found = this->codeAllocator->GetFileInfo((PVOID)thunkAddress, &fileHandle, &baseAddress);
  147. AssertOrFailFast(found);
  148. this->threadContext->SetValidCallTargetFile((PVOID)thunkAddress, fileHandle, baseAddress, false);
  149. }
  150. else
  151. #endif
  152. {
  153. this->threadContext->SetValidCallTargetForCFG((PVOID)thunkAddress, false);
  154. }
  155. }
  156. uintptr_t pageStartAddress = GetThunkPageStart(thunkAddress);
  157. if (IsThunkPageEmpty(pageStartAddress))
  158. {
  159. this->codeAllocator->Free((PVOID)pageStartAddress, AutoSystemInfo::PageSize, MEM_DECOMMIT);
  160. }
  161. else
  162. {
  163. char * localAddress = (char *)this->codeAllocator->AllocLocal((PVOID)thunkAddress, ThunkSize);
  164. if (localAddress == nullptr)
  165. {
  166. return;
  167. }
  168. UnprotectPage(localAddress);
  169. memset(localAddress, 0xCC, ThunkSize);
  170. ProtectPage(localAddress);
  171. this->codeAllocator->FreeLocal(localAddress);
  172. }
  173. FlushInstructionCache(this->processHandle, (PVOID)thunkAddress, ThunkSize);
  174. }
  175. template <typename TAlloc> inline
  176. uintptr_t
  177. JITThunkEmitter<TAlloc>::EnsureInitialized()
  178. {
  179. if (this->baseAddress != NULL)
  180. {
  181. return this->baseAddress;
  182. }
  183. // only take a lock if we need to initialize
  184. {
  185. AutoCriticalSection autoCs(&this->cs);
  186. // check again because we did the first one outside of lock
  187. if (this->baseAddress == NULL)
  188. {
  189. this->baseAddress = (uintptr_t)this->codeAllocator->AllocPages(nullptr, PageCount, MEM_RESERVE, PAGE_EXECUTE_READ, true);
  190. }
  191. }
  192. return this->baseAddress;
  193. }
  194. template <typename TAlloc> inline
  195. bool
  196. JITThunkEmitter<TAlloc>::IsInThunk(uintptr_t address) const
  197. {
  198. return IsInThunk(this->baseAddress, address);
  199. }
  200. /* static */
  201. template <typename TAlloc> inline
  202. bool
  203. JITThunkEmitter<TAlloc>::IsInThunk(uintptr_t thunkBaseAddress, uintptr_t address)
  204. {
  205. bool isInThunk = address >= thunkBaseAddress && address < thunkBaseAddress + TotalThunkSize;
  206. Assert(!isInThunk || address % ThunkSize == 0);
  207. return isInThunk;
  208. }
  209. /* static */
  210. template <typename TAlloc> inline
  211. void
  212. JITThunkEmitter<TAlloc>::EncodeJmp(char * localPageAddress, uintptr_t thunkAddress, uintptr_t targetAddress)
  213. {
  214. char * localAddress = localPageAddress + thunkAddress % AutoSystemInfo::PageSize;
  215. #if _M_IX86 || _M_X64
  216. ptrdiff_t relativeAddress = targetAddress - thunkAddress - DirectJmpIPAdjustment;
  217. #if _M_X64
  218. if (relativeAddress > INT_MAX || relativeAddress < INT_MIN)
  219. {
  220. memcpy_s(localAddress, ThunkSize, IndirectJmp, ThunkSize);
  221. uintptr_t * jmpTarget = (uintptr_t*)(localAddress + IndirectJmpTargetOffset);
  222. *jmpTarget = targetAddress;
  223. }
  224. else
  225. #endif
  226. {
  227. memcpy_s(localAddress, ThunkSize, DirectJmp, ThunkSize);
  228. uintptr_t * jmpTarget = (uintptr_t*)(localAddress + DirectJmpTargetOffset);
  229. *jmpTarget = relativeAddress;
  230. }
  231. #elif _M_ARM64
  232. ptrdiff_t relativeAddress = (targetAddress - thunkAddress) / 4;
  233. if (relativeAddress >= (1 << 25) || relativeAddress < -(1 << 25))
  234. {
  235. Assert(targetAddress == (targetAddress & 0xffffffffffffull));
  236. memcpy_s(localAddress, ThunkSize, IndirectBR, ThunkSize);
  237. ((DWORD *)localAddress)[IndirectBRLo16Offset] |= ((targetAddress >> 0) & 0xffff) << 5;
  238. ((DWORD *)localAddress)[IndirectBRMid16Offset] |= ((targetAddress >> 16) & 0xffff) << 5;
  239. ((DWORD *)localAddress)[IndirectBRHi16Offset] |= ((targetAddress >> 32) & 0xffff) << 5;
  240. }
  241. else
  242. {
  243. memcpy_s(localAddress, ThunkSize, DirectB, ThunkSize);
  244. ((DWORD *)localAddress)[0] |= relativeAddress & 0x3ffffff;
  245. }
  246. #endif
  247. }
  248. template <typename TAlloc> inline
  249. bool
  250. JITThunkEmitter<TAlloc>::IsThunkPageEmpty(uintptr_t address) const
  251. {
  252. Assert(address == GetThunkPageStart(address));
  253. BVIndex pageStartIndex = GetThunkIndexFromAddress(address);
  254. Assert(pageStartIndex != BVInvalidIndex);
  255. BVStatic<ThunksPerPage> * pageBV = this->freeThunks.GetRange<ThunksPerPage>(pageStartIndex);
  256. return pageBV->IsAllSet();
  257. }
  258. template <> inline
  259. void
  260. JITThunkEmitter<VirtualAllocWrapper>::ProtectPage(void * address)
  261. {
  262. #if defined(ENABLE_JIT_CLAMP)
  263. AutoEnableDynamicCodeGen enableCodeGen(true);
  264. #endif
  265. DWORD oldProtect;
  266. BOOL result = VirtualProtectEx(this->processHandle, address, ThunkSize, PAGE_EXECUTE_READ, &oldProtect);
  267. AssertOrFailFast(result && oldProtect == PAGE_EXECUTE_READWRITE);
  268. }
  269. template <> inline
  270. void
  271. JITThunkEmitter<VirtualAllocWrapper>::UnprotectPage(void * address)
  272. {
  273. #if defined(ENABLE_JIT_CLAMP)
  274. AutoEnableDynamicCodeGen enableCodeGen(true);
  275. #endif
  276. DWORD oldProtect;
  277. BOOL result = VirtualProtectEx(this->processHandle, address, ThunkSize, PAGE_EXECUTE_READWRITE, &oldProtect);
  278. AssertOrFailFast(result && oldProtect == PAGE_EXECUTE_READ);
  279. }
  280. #if ENABLE_OOP_NATIVE_CODEGEN
  281. template <> inline
  282. void
  283. JITThunkEmitter<SectionAllocWrapper>::ProtectPage(void * address)
  284. {
  285. }
  286. template <> inline
  287. void
  288. JITThunkEmitter<SectionAllocWrapper>::UnprotectPage(void * address)
  289. {
  290. }
  291. #endif
  292. template <typename TAlloc> inline
  293. uintptr_t
  294. JITThunkEmitter<TAlloc>::GetThunkAddressFromIndex(BVIndex index) const
  295. {
  296. return this->baseAddress + index * ThunkSize;
  297. }
  298. template <typename TAlloc> inline
  299. BVIndex
  300. JITThunkEmitter<TAlloc>::GetThunkIndexFromAddress(uintptr_t thunkAddress) const
  301. {
  302. uintptr_t thunkIndex = (thunkAddress - this->baseAddress) / ThunkSize;
  303. #if TARGET_64
  304. if (thunkIndex > BVInvalidIndex)
  305. {
  306. thunkIndex = BVInvalidIndex;
  307. }
  308. #endif
  309. return (BVIndex)thunkIndex;
  310. }
  311. /* static */
  312. template <typename TAlloc> inline
  313. uintptr_t
  314. JITThunkEmitter<TAlloc>::GetThunkPageStart(uintptr_t address)
  315. {
  316. return address - address % AutoSystemInfo::PageSize;
  317. }
  318. #endif