diff --git a/src/coreclr/vm/threadsuspend.cpp b/src/coreclr/vm/threadsuspend.cpp index 61dbae0ca95603..d73329268db63c 100644 --- a/src/coreclr/vm/threadsuspend.cpp +++ b/src/coreclr/vm/threadsuspend.cpp @@ -1983,9 +1983,14 @@ CONTEXT* AllocateOSContextHelper(BYTE** contextBuffer) pfnInitializeContext2(NULL, context, NULL, &contextSize, xStateCompactionMask) : InitializeContext(NULL, context, NULL, &contextSize); - // The following assert is valid, but gets triggered in some Win7 runs with no impact on functionality. - // commenting this out to reduce noise, as long as Win7 is supported. - // _ASSERTE(!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER); + // Spec mentions that we may get a different error (it was observed on Windows7). + // In such case the contextSize is undefined. + if (success || GetLastError() != ERROR_INSUFFICIENT_BUFFER) + { + STRESS_LOG2(LF_SYNC, LL_INFO1000, "AllocateOSContextHelper: Unexpected result from InitializeContext (success: %d, error: %d).\n", + success, GetLastError()); + return NULL; + } // So now allocate a buffer of that size and call InitializeContext again BYTE* buffer = new (nothrow)BYTE[contextSize]; @@ -2896,9 +2901,15 @@ BOOL Thread::RedirectThreadAtHandledJITCase(PFN_REDIRECTTARGET pTgt) if (!pCtx) { pCtx = m_pSavedRedirectContext = ThreadStore::GrabOSContext(&m_pOSContextBuffer); - _ASSERTE(GetSavedRedirectContext() != NULL); } + // We may not have a preallocated context. Could be short on memory when we tried to preallocate. + // We cannot allocate here since we have a thread stopped in a random place, possibly holding locks + // that we would need while allocating. + // Other ways and attempts at suspending may yet succeed, but this redirection cannot continue. + if (!pCtx) + return (FALSE); + ////////////////////////////////////// // Get and save the thread's context BOOL bRes = true;