VirtualAllocWrapper.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 "CommonMemoryPch.h"
  6. /*
  7. * class VirtualAllocWrapper
  8. */
  9. VirtualAllocWrapper VirtualAllocWrapper::Instance; // single instance
  10. LPVOID VirtualAllocWrapper::AllocPages(LPVOID lpAddress, size_t pageCount, DWORD allocationType, DWORD protectFlags, bool isCustomHeapAllocation)
  11. {
  12. if (pageCount > AutoSystemInfo::MaxPageCount)
  13. {
  14. return nullptr;
  15. }
  16. size_t dwSize = pageCount * AutoSystemInfo::PageSize;
  17. LPVOID address = nullptr;
  18. #if defined(ENABLE_JIT_CLAMP)
  19. bool makeExecutable;
  20. if ((isCustomHeapAllocation) ||
  21. (protectFlags & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE)))
  22. {
  23. makeExecutable = true;
  24. }
  25. else
  26. {
  27. makeExecutable = false;
  28. }
  29. AutoEnableDynamicCodeGen enableCodeGen(makeExecutable);
  30. #endif
  31. #if defined(_CONTROL_FLOW_GUARD)
  32. DWORD oldProtectFlags = 0;
  33. if (AutoSystemInfo::Data.IsCFGEnabled() && isCustomHeapAllocation)
  34. {
  35. //We do the allocation in two steps - CFG Bitmap in kernel will be created only on allocation with EXECUTE flag.
  36. //We again call VirtualProtect to set to the requested protectFlags.
  37. DWORD allocProtectFlags = 0;
  38. if (AutoSystemInfo::Data.IsCFGEnabled())
  39. {
  40. allocProtectFlags = PAGE_EXECUTE_RW_TARGETS_INVALID;
  41. }
  42. else
  43. {
  44. allocProtectFlags = PAGE_EXECUTE_READWRITE;
  45. }
  46. address = VirtualAlloc(lpAddress, dwSize, allocationType, allocProtectFlags);
  47. if (address == nullptr)
  48. {
  49. MemoryOperationLastError::RecordLastError();
  50. return nullptr;
  51. }
  52. else if ((allocationType & MEM_COMMIT) == MEM_COMMIT) // The access protection value can be set only on committed pages.
  53. {
  54. BOOL result = VirtualProtect(address, dwSize, protectFlags, &oldProtectFlags);
  55. if (result == FALSE)
  56. {
  57. CustomHeap_BadPageState_unrecoverable_error((ULONG_PTR)this);
  58. }
  59. }
  60. }
  61. else
  62. #endif
  63. {
  64. address = VirtualAlloc(lpAddress, dwSize, allocationType, protectFlags);
  65. if (address == nullptr)
  66. {
  67. MemoryOperationLastError::RecordLastError();
  68. return nullptr;
  69. }
  70. }
  71. return address;
  72. }
  73. BOOL VirtualAllocWrapper::Free(LPVOID lpAddress, size_t dwSize, DWORD dwFreeType)
  74. {
  75. AnalysisAssert(dwFreeType == MEM_RELEASE || dwFreeType == MEM_DECOMMIT);
  76. size_t bytes = (dwFreeType == MEM_RELEASE)? 0 : dwSize;
  77. #pragma warning(suppress: 28160) // Calling VirtualFreeEx without the MEM_RELEASE flag frees memory but not address descriptors (VADs)
  78. BOOL ret = VirtualFree(lpAddress, bytes, dwFreeType);
  79. return ret;
  80. }
  81. #if ENABLE_NATIVE_CODEGEN
  82. /*
  83. * class PreReservedVirtualAllocWrapper
  84. */
  85. #if !TARGET_64 && _CONTROL_FLOW_GUARD
  86. uint PreReservedVirtualAllocWrapper::numPreReservedSegment = 0;
  87. #endif
  88. PreReservedVirtualAllocWrapper::PreReservedVirtualAllocWrapper() :
  89. preReservedStartAddress(nullptr),
  90. cs(4000)
  91. {
  92. freeSegments.SetAll();
  93. }
  94. PreReservedVirtualAllocWrapper::~PreReservedVirtualAllocWrapper()
  95. {
  96. if (IsPreReservedRegionPresent())
  97. {
  98. BOOL success = VirtualFree(preReservedStartAddress, 0, MEM_RELEASE);
  99. PreReservedHeapTrace(_u("MEM_RELEASE the PreReservedSegment. Start Address: 0x%p, Size: 0x%x * 0x%x bytes"), preReservedStartAddress, PreReservedAllocationSegmentCount,
  100. AutoSystemInfo::Data.GetAllocationGranularityPageSize());
  101. if (!success)
  102. {
  103. // OOP JIT TODO: check if we need to cleanup the context related to this content process
  104. }
  105. #if !TARGET_64 && _CONTROL_FLOW_GUARD
  106. Assert(numPreReservedSegment > 0);
  107. InterlockedDecrement(&PreReservedVirtualAllocWrapper::numPreReservedSegment);
  108. #endif
  109. }
  110. }
  111. bool
  112. PreReservedVirtualAllocWrapper::IsPreReservedRegionPresent()
  113. {
  114. return preReservedStartAddress != nullptr;
  115. }
  116. bool
  117. PreReservedVirtualAllocWrapper::IsInRange(void * address)
  118. {
  119. if (!this->IsPreReservedRegionPresent())
  120. {
  121. return false;
  122. }
  123. bool isInRange = IsInRange(GetPreReservedStartAddress(), address);
  124. #if DBG
  125. if (isInRange)
  126. {
  127. //Check if the region is in MEM_COMMIT state.
  128. MEMORY_BASIC_INFORMATION memBasicInfo;
  129. size_t bytes = VirtualQuery(address, &memBasicInfo, sizeof(memBasicInfo));
  130. if (bytes == 0)
  131. {
  132. return false;
  133. }
  134. AssertMsg(memBasicInfo.State == MEM_COMMIT, "Memory not committed? Checking for uncommitted address region?");
  135. }
  136. #endif
  137. return isInRange;
  138. }
  139. /* static */
  140. bool
  141. PreReservedVirtualAllocWrapper::IsInRange(void * regionStart, void * address)
  142. {
  143. if (!regionStart)
  144. {
  145. return false;
  146. }
  147. if (address >= regionStart && address < GetPreReservedEndAddress(regionStart))
  148. {
  149. return true;
  150. }
  151. return false;
  152. }
  153. LPVOID
  154. PreReservedVirtualAllocWrapper::GetPreReservedStartAddress()
  155. {
  156. return preReservedStartAddress;
  157. }
  158. LPVOID
  159. PreReservedVirtualAllocWrapper::GetPreReservedEndAddress()
  160. {
  161. Assert(IsPreReservedRegionPresent());
  162. return GetPreReservedEndAddress(preReservedStartAddress);
  163. }
  164. /* static */
  165. LPVOID
  166. PreReservedVirtualAllocWrapper::GetPreReservedEndAddress(void * regionStart)
  167. {
  168. return (char*)regionStart + (PreReservedAllocationSegmentCount * AutoSystemInfo::Data.GetAllocationGranularityPageCount() * AutoSystemInfo::PageSize);
  169. }
  170. LPVOID PreReservedVirtualAllocWrapper::EnsurePreReservedRegion()
  171. {
  172. LPVOID startAddress = preReservedStartAddress;
  173. if (startAddress != nullptr)
  174. {
  175. return startAddress;
  176. }
  177. {
  178. AutoCriticalSection autocs(&this->cs);
  179. return EnsurePreReservedRegionInternal();
  180. }
  181. }
  182. LPVOID PreReservedVirtualAllocWrapper::EnsurePreReservedRegionInternal()
  183. {
  184. LPVOID startAddress = preReservedStartAddress;
  185. if (startAddress != nullptr)
  186. {
  187. return startAddress;
  188. }
  189. //PreReserve a (bigger) segment
  190. size_t bytes = PreReservedAllocationSegmentCount * AutoSystemInfo::Data.GetAllocationGranularityPageSize();
  191. if (PHASE_FORCE1(Js::PreReservedHeapAllocPhase))
  192. {
  193. //This code is used where CFG is not available, but still PreReserve optimization for CFG can be tested
  194. startAddress = VirtualAlloc(NULL, bytes, MEM_RESERVE, PAGE_READWRITE);
  195. PreReservedHeapTrace(_u("Reserving PreReservedSegment For the first time(CFG Non-Enabled). Address: 0x%p\n"), preReservedStartAddress);
  196. preReservedStartAddress = startAddress;
  197. return startAddress;
  198. }
  199. #if defined(_CONTROL_FLOW_GUARD)
  200. bool supportPreReservedRegion = true;
  201. #if !TARGET_64
  202. #if _M_IX86
  203. // We want to restrict the number of prereserved segment for 32-bit process so that we don't use up the address space
  204. // Note: numPreReservedSegment is for the whole process, and access and update to it is not protected by a global lock.
  205. // So we may allocate more than the maximum some of the time if multiple thread check it simutaniously and allocate pass the limit.
  206. // It doesn't affect functionally, and it should be OK if we exceed.
  207. if (PreReservedVirtualAllocWrapper::numPreReservedSegment > PreReservedVirtualAllocWrapper::MaxPreReserveSegment)
  208. {
  209. supportPreReservedRegion = false;
  210. }
  211. #else
  212. // TODO: fast check for prereserved segment is not implementated in ARM yet, so it is only enabled for x86
  213. supportPreReservedRegion = false;
  214. #endif // _M_IX86
  215. #endif
  216. if (AutoSystemInfo::Data.IsCFGEnabled() && supportPreReservedRegion)
  217. {
  218. startAddress = VirtualAlloc(NULL, bytes, MEM_RESERVE, PAGE_READWRITE);
  219. PreReservedHeapTrace(_u("Reserving PreReservedSegment For the first time(CFG Enabled). Address: 0x%p\n"), preReservedStartAddress);
  220. preReservedStartAddress = startAddress;
  221. #if !TARGET_64
  222. if (startAddress)
  223. {
  224. InterlockedIncrement(&PreReservedVirtualAllocWrapper::numPreReservedSegment);
  225. }
  226. #endif
  227. }
  228. #endif
  229. return startAddress;
  230. }
  231. /*
  232. * LPVOID PreReservedVirtualAllocWrapper::Alloc
  233. * - Reserves only one big memory region.
  234. * - Returns an Allocated memory region within this preReserved region with the specified protectFlags.
  235. * - Tracks the committed pages
  236. */
  237. LPVOID PreReservedVirtualAllocWrapper::AllocPages(LPVOID lpAddress, size_t pageCount, DWORD allocationType, DWORD protectFlags, bool isCustomHeapAllocation)
  238. {
  239. if (pageCount > AutoSystemInfo::MaxPageCount)
  240. {
  241. return nullptr;
  242. }
  243. size_t dwSize = pageCount * AutoSystemInfo::PageSize;
  244. AssertMsg(isCustomHeapAllocation, "PreReservation used for allocations other than CustomHeap?");
  245. Assert(dwSize != 0);
  246. {
  247. AutoCriticalSection autocs(&this->cs);
  248. //Return nullptr, if no space to Reserve
  249. if (EnsurePreReservedRegionInternal() == nullptr)
  250. {
  251. PreReservedHeapTrace(_u("No space to pre-reserve memory with %d pages. Returning NULL\n"), PreReservedAllocationSegmentCount * AutoSystemInfo::Data.GetAllocationGranularityPageCount());
  252. return nullptr;
  253. }
  254. char * addressToReserve = nullptr;
  255. uint freeSegmentsBVIndex = BVInvalidIndex;
  256. size_t requestedNumOfSegments = dwSize / (AutoSystemInfo::Data.GetAllocationGranularityPageSize());
  257. Assert(requestedNumOfSegments <= MAXUINT32);
  258. if (lpAddress == nullptr)
  259. {
  260. Assert(requestedNumOfSegments != 0);
  261. AssertMsg(dwSize % AutoSystemInfo::Data.GetAllocationGranularityPageSize() == 0, "dwSize should be aligned with Allocation Granularity");
  262. do
  263. {
  264. freeSegmentsBVIndex = freeSegments.GetNextBit(freeSegmentsBVIndex + 1);
  265. //Return nullptr, if we don't have free/decommit pages to allocate
  266. if ((freeSegments.Length() - freeSegmentsBVIndex < requestedNumOfSegments) ||
  267. freeSegmentsBVIndex == BVInvalidIndex)
  268. {
  269. PreReservedHeapTrace(_u("No more space to commit in PreReserved Memory region.\n"));
  270. return nullptr;
  271. }
  272. } while (!freeSegments.TestRange(freeSegmentsBVIndex, static_cast<uint>(requestedNumOfSegments)));
  273. uint offset = freeSegmentsBVIndex * AutoSystemInfo::Data.GetAllocationGranularityPageSize();
  274. addressToReserve = (char*) preReservedStartAddress + offset;
  275. //Check if the region is not already in MEM_COMMIT state.
  276. MEMORY_BASIC_INFORMATION memBasicInfo;
  277. size_t bytes = VirtualQuery(addressToReserve, &memBasicInfo, sizeof(memBasicInfo));
  278. if (bytes == 0)
  279. {
  280. MemoryOperationLastError::RecordLastError();
  281. }
  282. if (bytes == 0
  283. || memBasicInfo.RegionSize < requestedNumOfSegments * AutoSystemInfo::Data.GetAllocationGranularityPageSize()
  284. || memBasicInfo.State == MEM_COMMIT)
  285. {
  286. CustomHeap_BadPageState_unrecoverable_error((ULONG_PTR)this);
  287. }
  288. }
  289. else
  290. {
  291. //Check If the lpAddress is within the range of the preReserved Memory Region
  292. Assert(((char*) lpAddress) >= (char*) preReservedStartAddress || ((char*) lpAddress + dwSize) < GetPreReservedEndAddress());
  293. addressToReserve = (char*) lpAddress;
  294. freeSegmentsBVIndex = (uint) ((addressToReserve - (char*) preReservedStartAddress) / AutoSystemInfo::Data.GetAllocationGranularityPageSize());
  295. #if DBG
  296. uint numOfSegments = (uint)ceil((double)dwSize / (double)AutoSystemInfo::Data.GetAllocationGranularityPageSize());
  297. Assert(numOfSegments != 0);
  298. Assert(freeSegmentsBVIndex + numOfSegments - 1 < freeSegments.Length());
  299. Assert(!freeSegments.TestRange(freeSegmentsBVIndex, numOfSegments));
  300. #endif
  301. }
  302. AssertMsg(freeSegmentsBVIndex < PreReservedAllocationSegmentCount, "Invalid BitVector index calculation?");
  303. AssertMsg(dwSize % AutoSystemInfo::PageSize == 0, "COMMIT is managed at AutoSystemInfo::PageSize granularity");
  304. char * allocatedAddress = nullptr;
  305. bool failedToProtectPages = false;
  306. if ((allocationType & MEM_COMMIT) != 0)
  307. {
  308. #if defined(ENABLE_JIT_CLAMP)
  309. AutoEnableDynamicCodeGen enableCodeGen;
  310. #endif
  311. #if defined(_CONTROL_FLOW_GUARD)
  312. if (AutoSystemInfo::Data.IsCFGEnabled())
  313. {
  314. DWORD oldProtect = 0;
  315. DWORD allocProtectFlags = 0;
  316. if (AutoSystemInfo::Data.IsCFGEnabled())
  317. {
  318. allocProtectFlags = PAGE_EXECUTE_RW_TARGETS_INVALID;
  319. }
  320. else
  321. {
  322. allocProtectFlags = PAGE_EXECUTE_READWRITE;
  323. }
  324. allocatedAddress = (char *)VirtualAlloc(addressToReserve, dwSize, MEM_COMMIT, allocProtectFlags);
  325. if (allocatedAddress != nullptr)
  326. {
  327. BOOL result = VirtualProtect(allocatedAddress, dwSize, protectFlags, &oldProtect);
  328. if (result == FALSE)
  329. {
  330. CustomHeap_BadPageState_unrecoverable_error((ULONG_PTR)this);
  331. }
  332. AssertMsg(oldProtect == (PAGE_EXECUTE_READWRITE), "CFG Bitmap gets allocated and bits will be set to invalid only upon passing these flags.");
  333. }
  334. else
  335. {
  336. MemoryOperationLastError::RecordLastError();
  337. }
  338. }
  339. else
  340. #endif
  341. {
  342. allocatedAddress = (char *)VirtualAlloc(addressToReserve, dwSize, MEM_COMMIT, protectFlags);
  343. if (allocatedAddress == nullptr)
  344. {
  345. MemoryOperationLastError::RecordLastError();
  346. }
  347. }
  348. }
  349. else
  350. {
  351. // Just return the uncommitted address if we didn't ask to commit it.
  352. allocatedAddress = addressToReserve;
  353. }
  354. // Keep track of the committed pages within the preReserved Memory Region
  355. if (lpAddress == nullptr && allocatedAddress != nullptr)
  356. {
  357. Assert(allocatedAddress == addressToReserve);
  358. Assert(requestedNumOfSegments != 0);
  359. freeSegments.ClearRange(freeSegmentsBVIndex, static_cast<uint>(requestedNumOfSegments));
  360. }
  361. PreReservedHeapTrace(_u("MEM_COMMIT: StartAddress: 0x%p of size: 0x%x * 0x%x bytes \n"), allocatedAddress, requestedNumOfSegments, AutoSystemInfo::Data.GetAllocationGranularityPageSize());
  362. if (failedToProtectPages)
  363. {
  364. return nullptr;
  365. }
  366. return allocatedAddress;
  367. }
  368. }
  369. /*
  370. * PreReservedVirtualAllocWrapper::Free
  371. * - Doesn't actually release the pages to the CPU.
  372. * - It Decommits the page (memory region within the preReserved Region)
  373. * - Update the tracking of the committed pages.
  374. */
  375. BOOL
  376. PreReservedVirtualAllocWrapper::Free(LPVOID lpAddress, size_t dwSize, DWORD dwFreeType)
  377. {
  378. {
  379. AutoCriticalSection autocs(&this->cs);
  380. if (dwSize == 0)
  381. {
  382. Assert(false);
  383. return FALSE;
  384. }
  385. if (preReservedStartAddress == nullptr)
  386. {
  387. Assert(false);
  388. return FALSE;
  389. }
  390. Assert(dwSize % AutoSystemInfo::PageSize == 0);
  391. #pragma warning(suppress: 6250)
  392. #pragma warning(suppress: 28160) // Calling VirtualFreeEx without the MEM_RELEASE flag frees memory but not address descriptors (VADs)
  393. BOOL success = VirtualFree(lpAddress, dwSize, MEM_DECOMMIT);
  394. size_t requestedNumOfSegments = dwSize / AutoSystemInfo::Data.GetAllocationGranularityPageSize();
  395. Assert(requestedNumOfSegments <= MAXUINT32);
  396. if (success)
  397. {
  398. PreReservedHeapTrace(_u("MEM_DECOMMIT: Address: 0x%p of size: 0x%x bytes\n"), lpAddress, dwSize);
  399. }
  400. if (success && (dwFreeType & MEM_RELEASE) != 0)
  401. {
  402. Assert((uintptr_t) lpAddress >= (uintptr_t) preReservedStartAddress);
  403. AssertMsg(((uintptr_t)lpAddress & (AutoSystemInfo::Data.GetAllocationGranularityPageCount() - 1)) == 0, "Not aligned with Allocation Granularity?");
  404. AssertMsg(dwSize % AutoSystemInfo::Data.GetAllocationGranularityPageSize() == 0, "Release size should match the allocation granularity size");
  405. Assert(requestedNumOfSegments != 0);
  406. BVIndex freeSegmentsBVIndex = (BVIndex) (((uintptr_t) lpAddress - (uintptr_t) preReservedStartAddress) / AutoSystemInfo::Data.GetAllocationGranularityPageSize());
  407. AssertMsg(freeSegmentsBVIndex < PreReservedAllocationSegmentCount, "Invalid Index ?");
  408. freeSegments.SetRange(freeSegmentsBVIndex, static_cast<uint>(requestedNumOfSegments));
  409. PreReservedHeapTrace(_u("MEM_RELEASE: Address: 0x%p of size: 0x%x * 0x%x bytes\n"), lpAddress, requestedNumOfSegments, AutoSystemInfo::Data.GetAllocationGranularityPageSize());
  410. }
  411. return success;
  412. }
  413. }
  414. #endif // ENABLE_NATIVE_CODEGEN
  415. #if defined(ENABLE_JIT_CLAMP)
  416. /*
  417. * class AutoEnableDynamicCodeGen
  418. */
  419. typedef
  420. BOOL
  421. (WINAPI *PGET_PROCESS_MITIGATION_POLICY_PROC)(
  422. _In_ HANDLE hProcess,
  423. _In_ PROCESS_MITIGATION_POLICY MitigationPolicy,
  424. _Out_ PVOID lpBuffer,
  425. _In_ SIZE_T dwLength
  426. );
  427. AutoEnableDynamicCodeGen::PSET_THREAD_INFORMATION_PROC AutoEnableDynamicCodeGen::SetThreadInformationProc = nullptr;
  428. AutoEnableDynamicCodeGen::PGET_THREAD_INFORMATION_PROC AutoEnableDynamicCodeGen::GetThreadInformationProc = nullptr;
  429. PROCESS_MITIGATION_DYNAMIC_CODE_POLICY AutoEnableDynamicCodeGen::processPolicy;
  430. CriticalSection AutoEnableDynamicCodeGen::processPolicyCS;
  431. volatile bool AutoEnableDynamicCodeGen::processPolicyObtained = false;
  432. AutoEnableDynamicCodeGen::AutoEnableDynamicCodeGen(bool enable) : enabled(false)
  433. {
  434. if (enable == false)
  435. {
  436. return;
  437. }
  438. //
  439. // Snap the dynamic code generation policy for this process so that we
  440. // don't need to resolve APIs and query it each time. We expect the policy
  441. // to have been established upfront.
  442. //
  443. if (processPolicyObtained == false)
  444. {
  445. AutoCriticalSection autocs(&processPolicyCS);
  446. if (processPolicyObtained == false)
  447. {
  448. PGET_PROCESS_MITIGATION_POLICY_PROC GetProcessMitigationPolicyProc = nullptr;
  449. HMODULE module = GetModuleHandleW(_u("api-ms-win-core-processthreads-l1-1-3.dll"));
  450. if (module != nullptr)
  451. {
  452. GetProcessMitigationPolicyProc = (PGET_PROCESS_MITIGATION_POLICY_PROC) GetProcAddress(module, "GetProcessMitigationPolicy");
  453. SetThreadInformationProc = (PSET_THREAD_INFORMATION_PROC) GetProcAddress(module, "SetThreadInformation");
  454. GetThreadInformationProc = (PGET_THREAD_INFORMATION_PROC) GetProcAddress(module, "GetThreadInformation");
  455. }
  456. if ((GetProcessMitigationPolicyProc == nullptr) ||
  457. (!GetProcessMitigationPolicyProc(GetCurrentProcess(), ProcessDynamicCodePolicy, (PPROCESS_MITIGATION_DYNAMIC_CODE_POLICY) &processPolicy, sizeof(processPolicy))))
  458. {
  459. processPolicy.ProhibitDynamicCode = 0;
  460. }
  461. processPolicyObtained = true;
  462. }
  463. }
  464. //
  465. // The process is not prohibiting dynamic code or does not allow threads
  466. // to opt out. In either case, return to the caller.
  467. //
  468. // N.B. It is OK that this policy is mutable at runtime. If a process
  469. // really does not allow thread opt-out, then the call below will fail
  470. // benignly.
  471. //
  472. if ((processPolicy.ProhibitDynamicCode == 0) || (processPolicy.AllowThreadOptOut == 0))
  473. {
  474. return;
  475. }
  476. if (SetThreadInformationProc == nullptr || GetThreadInformationProc == nullptr)
  477. {
  478. return;
  479. }
  480. //
  481. // If dynamic code is already allowed for this thread, then don't attempt to allow it again.
  482. //
  483. DWORD threadPolicy;
  484. if ((GetThreadInformationProc(GetCurrentThread(), ThreadDynamicCodePolicy, &threadPolicy, sizeof(DWORD))) &&
  485. (threadPolicy == THREAD_DYNAMIC_CODE_ALLOW))
  486. {
  487. return;
  488. }
  489. threadPolicy = THREAD_DYNAMIC_CODE_ALLOW;
  490. BOOL result = SetThreadInformationProc(GetCurrentThread(), ThreadDynamicCodePolicy, &threadPolicy, sizeof(DWORD));
  491. Assert(result);
  492. enabled = true;
  493. }
  494. AutoEnableDynamicCodeGen::~AutoEnableDynamicCodeGen()
  495. {
  496. if (enabled)
  497. {
  498. DWORD threadPolicy = 0;
  499. BOOL result = SetThreadInformationProc(GetCurrentThread(), ThreadDynamicCodePolicy, &threadPolicy, sizeof(DWORD));
  500. Assert(result);
  501. enabled = false;
  502. }
  503. }
  504. #endif // defined(ENABLE_JIT_CLAMP)