VirtualAllocWrapper.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 (GlobalSecurityPolicy::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 (GlobalSecurityPolicy::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 (GlobalSecurityPolicy::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 (GlobalSecurityPolicy::IsCFGEnabled())
  313. {
  314. DWORD oldProtect = 0;
  315. DWORD allocProtectFlags = 0;
  316. allocProtectFlags = PAGE_EXECUTE_RW_TARGETS_INVALID;
  317. allocatedAddress = (char *)VirtualAlloc(addressToReserve, dwSize, MEM_COMMIT, allocProtectFlags);
  318. if (allocatedAddress != nullptr)
  319. {
  320. BOOL result = VirtualProtect(allocatedAddress, dwSize, protectFlags, &oldProtect);
  321. if (result == FALSE)
  322. {
  323. CustomHeap_BadPageState_unrecoverable_error((ULONG_PTR)this);
  324. }
  325. AssertMsg(oldProtect == (PAGE_EXECUTE_READWRITE), "CFG Bitmap gets allocated and bits will be set to invalid only upon passing these flags.");
  326. }
  327. else
  328. {
  329. MemoryOperationLastError::RecordLastError();
  330. }
  331. }
  332. else
  333. #endif
  334. {
  335. allocatedAddress = (char *)VirtualAlloc(addressToReserve, dwSize, MEM_COMMIT, protectFlags);
  336. if (allocatedAddress == nullptr)
  337. {
  338. MemoryOperationLastError::RecordLastError();
  339. }
  340. }
  341. }
  342. else
  343. {
  344. // Just return the uncommitted address if we didn't ask to commit it.
  345. allocatedAddress = addressToReserve;
  346. }
  347. // Keep track of the committed pages within the preReserved Memory Region
  348. if (lpAddress == nullptr && allocatedAddress != nullptr)
  349. {
  350. Assert(allocatedAddress == addressToReserve);
  351. Assert(requestedNumOfSegments != 0);
  352. freeSegments.ClearRange(freeSegmentsBVIndex, static_cast<uint>(requestedNumOfSegments));
  353. }
  354. PreReservedHeapTrace(_u("MEM_COMMIT: StartAddress: 0x%p of size: 0x%x * 0x%x bytes \n"), allocatedAddress, requestedNumOfSegments, AutoSystemInfo::Data.GetAllocationGranularityPageSize());
  355. if (failedToProtectPages)
  356. {
  357. return nullptr;
  358. }
  359. return allocatedAddress;
  360. }
  361. }
  362. /*
  363. * PreReservedVirtualAllocWrapper::Free
  364. * - Doesn't actually release the pages to the CPU.
  365. * - It Decommits the page (memory region within the preReserved Region)
  366. * - Update the tracking of the committed pages.
  367. */
  368. BOOL
  369. PreReservedVirtualAllocWrapper::Free(LPVOID lpAddress, size_t dwSize, DWORD dwFreeType)
  370. {
  371. {
  372. AutoCriticalSection autocs(&this->cs);
  373. if (dwSize == 0)
  374. {
  375. Assert(false);
  376. return FALSE;
  377. }
  378. if (preReservedStartAddress == nullptr)
  379. {
  380. Assert(false);
  381. return FALSE;
  382. }
  383. Assert(dwSize % AutoSystemInfo::PageSize == 0);
  384. #pragma warning(suppress: 6250)
  385. #pragma warning(suppress: 28160) // Calling VirtualFreeEx without the MEM_RELEASE flag frees memory but not address descriptors (VADs)
  386. BOOL success = VirtualFree(lpAddress, dwSize, MEM_DECOMMIT);
  387. size_t requestedNumOfSegments = dwSize / AutoSystemInfo::Data.GetAllocationGranularityPageSize();
  388. Assert(requestedNumOfSegments <= MAXUINT32);
  389. if (success)
  390. {
  391. PreReservedHeapTrace(_u("MEM_DECOMMIT: Address: 0x%p of size: 0x%x bytes\n"), lpAddress, dwSize);
  392. }
  393. if (success && (dwFreeType & MEM_RELEASE) != 0)
  394. {
  395. Assert((uintptr_t) lpAddress >= (uintptr_t) preReservedStartAddress);
  396. AssertMsg(((uintptr_t)lpAddress & (AutoSystemInfo::Data.GetAllocationGranularityPageCount() - 1)) == 0, "Not aligned with Allocation Granularity?");
  397. AssertMsg(dwSize % AutoSystemInfo::Data.GetAllocationGranularityPageSize() == 0, "Release size should match the allocation granularity size");
  398. Assert(requestedNumOfSegments != 0);
  399. BVIndex freeSegmentsBVIndex = (BVIndex) (((uintptr_t) lpAddress - (uintptr_t) preReservedStartAddress) / AutoSystemInfo::Data.GetAllocationGranularityPageSize());
  400. AssertMsg(freeSegmentsBVIndex < PreReservedAllocationSegmentCount, "Invalid Index ?");
  401. freeSegments.SetRange(freeSegmentsBVIndex, static_cast<uint>(requestedNumOfSegments));
  402. PreReservedHeapTrace(_u("MEM_RELEASE: Address: 0x%p of size: 0x%x * 0x%x bytes\n"), lpAddress, requestedNumOfSegments, AutoSystemInfo::Data.GetAllocationGranularityPageSize());
  403. }
  404. return success;
  405. }
  406. }
  407. #endif // ENABLE_NATIVE_CODEGEN
  408. #if defined(ENABLE_JIT_CLAMP)
  409. /*
  410. * class AutoEnableDynamicCodeGen
  411. */
  412. typedef
  413. BOOL
  414. (WINAPI *PGET_PROCESS_MITIGATION_POLICY_PROC)(
  415. _In_ HANDLE hProcess,
  416. _In_ PROCESS_MITIGATION_POLICY MitigationPolicy,
  417. _Out_ PVOID lpBuffer,
  418. _In_ SIZE_T dwLength
  419. );
  420. AutoEnableDynamicCodeGen::PSET_THREAD_INFORMATION_PROC AutoEnableDynamicCodeGen::SetThreadInformationProc = nullptr;
  421. AutoEnableDynamicCodeGen::PGET_THREAD_INFORMATION_PROC AutoEnableDynamicCodeGen::GetThreadInformationProc = nullptr;
  422. PROCESS_MITIGATION_DYNAMIC_CODE_POLICY AutoEnableDynamicCodeGen::processPolicy;
  423. CriticalSection AutoEnableDynamicCodeGen::processPolicyCS;
  424. volatile bool AutoEnableDynamicCodeGen::processPolicyObtained = false;
  425. AutoEnableDynamicCodeGen::AutoEnableDynamicCodeGen(bool enable) : enabled(false)
  426. {
  427. if (enable == false)
  428. {
  429. return;
  430. }
  431. //
  432. // Snap the dynamic code generation policy for this process so that we
  433. // don't need to resolve APIs and query it each time. We expect the policy
  434. // to have been established upfront.
  435. //
  436. if (processPolicyObtained == false)
  437. {
  438. AutoCriticalSection autocs(&processPolicyCS);
  439. if (processPolicyObtained == false)
  440. {
  441. PGET_PROCESS_MITIGATION_POLICY_PROC GetProcessMitigationPolicyProc = nullptr;
  442. HMODULE module = GetModuleHandleW(_u("api-ms-win-core-processthreads-l1-1-3.dll"));
  443. if (module != nullptr)
  444. {
  445. GetProcessMitigationPolicyProc = (PGET_PROCESS_MITIGATION_POLICY_PROC) GetProcAddress(module, "GetProcessMitigationPolicy");
  446. SetThreadInformationProc = (PSET_THREAD_INFORMATION_PROC) GetProcAddress(module, "SetThreadInformation");
  447. GetThreadInformationProc = (PGET_THREAD_INFORMATION_PROC) GetProcAddress(module, "GetThreadInformation");
  448. }
  449. if ((GetProcessMitigationPolicyProc == nullptr) ||
  450. (!GetProcessMitigationPolicyProc(GetCurrentProcess(), ProcessDynamicCodePolicy, (PPROCESS_MITIGATION_DYNAMIC_CODE_POLICY) &processPolicy, sizeof(processPolicy))))
  451. {
  452. processPolicy.ProhibitDynamicCode = 0;
  453. }
  454. processPolicyObtained = true;
  455. }
  456. }
  457. //
  458. // The process is not prohibiting dynamic code or does not allow threads
  459. // to opt out. In either case, return to the caller.
  460. //
  461. // N.B. It is OK that this policy is mutable at runtime. If a process
  462. // really does not allow thread opt-out, then the call below will fail
  463. // benignly.
  464. //
  465. if ((processPolicy.ProhibitDynamicCode == 0) || (processPolicy.AllowThreadOptOut == 0))
  466. {
  467. return;
  468. }
  469. if (SetThreadInformationProc == nullptr || GetThreadInformationProc == nullptr)
  470. {
  471. return;
  472. }
  473. //
  474. // If dynamic code is already allowed for this thread, then don't attempt to allow it again.
  475. //
  476. DWORD threadPolicy;
  477. if ((GetThreadInformationProc(GetCurrentThread(), ThreadDynamicCodePolicy, &threadPolicy, sizeof(DWORD))) &&
  478. (threadPolicy == THREAD_DYNAMIC_CODE_ALLOW))
  479. {
  480. return;
  481. }
  482. threadPolicy = THREAD_DYNAMIC_CODE_ALLOW;
  483. BOOL result = SetThreadInformationProc(GetCurrentThread(), ThreadDynamicCodePolicy, &threadPolicy, sizeof(DWORD));
  484. Assert(result);
  485. enabled = true;
  486. }
  487. AutoEnableDynamicCodeGen::~AutoEnableDynamicCodeGen()
  488. {
  489. if (enabled)
  490. {
  491. DWORD threadPolicy = 0;
  492. BOOL result = SetThreadInformationProc(GetCurrentThread(), ThreadDynamicCodePolicy, &threadPolicy, sizeof(DWORD));
  493. Assert(result);
  494. enabled = false;
  495. }
  496. }
  497. #endif // defined(ENABLE_JIT_CLAMP)