Esempio n. 1
0
File: heap_dbg.c Progetto: Gd58/MCF
__MCF_HeapDbgBlockInfo *__MCF_CRT_HeapDbgValidateBlock(unsigned char **ppRaw, unsigned char *pContents, const void *pRetAddr){
	unsigned char *const pRaw = pContents - GUARD_BAND_SIZE;
	*ppRaw = pRaw;

	__MCF_HeapDbgBlockInfo *const pBlockInfo = (__MCF_HeapDbgBlockInfo *)MCF_AvlFind(&g_pavlBlocks, (intptr_t)pContents, &BlockInfoComparatorNodeKey);
	if(!pBlockInfo){
		MCF_CRT_BailF(L"__MCF_CRT_HeapDbgValidate() 失败:传入的指针无效。\n调用返回地址:%p", pRetAddr);
	}
	const size_t uSize = pBlockInfo->__uSize;

	void *const *ppGuard1 = (void *const *)pContents;
	void *const *ppGuard2 = (void *const *)(pContents + uSize);
	for(unsigned i = 0; i < GUARD_BAND_SIZE; i += sizeof(void *)){
		--ppGuard1;

		void *pTemp1, *pTemp2;
		__builtin_memcpy(&pTemp1, ppGuard1, sizeof(void *));
		__builtin_memcpy(&pTemp2, ppGuard2, sizeof(void *));
		if((DecodePointer(pTemp1) != ppGuard2) || (DecodePointer(pTemp2) != ppGuard1)){
			MCF_CRT_BailF(L"__MCF_CRT_HeapDbgValidate() 失败:侦测到堆损坏。\n调用返回地址:%p", pRetAddr);
		}

		++ppGuard2;
	}

	return pBlockInfo;
}
Esempio n. 2
0
HRESULT
ServerAddDOMFastPathHelper(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t scriptContextRoot,
    /* [in] */ intptr_t funcInfoAddr,
    /* [in] */ int helper)
{
    AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));

    ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer((void*)scriptContextRoot);

    if (scriptContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (!ServerContextManager::IsScriptContextAlive(scriptContextInfo))
    {
        Assert(false);
        return E_ACCESSDENIED;
    }

    AutoReleaseContext<ServerScriptContext> autoScriptContext(scriptContextInfo);
    return ServerCallWrapper(scriptContextInfo, [&]()->HRESULT
    {
        scriptContextInfo->AddToDOMFastPathHelperMap(funcInfoAddr, (IR::JnHelperMethod)helper);
        return S_OK;
    });
}
Esempio n. 3
0
HRESULT
ServerAddModuleRecordInfo(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t scriptContextInfoAddress,
    /* [in] */ unsigned int moduleId,
    /* [in] */ intptr_t localExportSlotsAddr)
{
    AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));

    ServerScriptContext * serverScriptContext = (ServerScriptContext*)DecodePointer((void*)scriptContextInfoAddress);
    if (serverScriptContext == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (!ServerContextManager::IsScriptContextAlive(serverScriptContext))
    {
        Assert(false);
        return E_ACCESSDENIED;
    }

    AutoReleaseContext<ServerScriptContext> autoScriptContext(serverScriptContext);
    return ServerCallWrapper(serverScriptContext, [&]()->HRESULT
    {
        serverScriptContext->AddModuleRecordInfo(moduleId, localExportSlotsAddr);
        return S_OK;
    });

}
Esempio n. 4
0
HRESULT
ServerCloseScriptContext(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t scriptContextRoot)
{
    ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer((void*)scriptContextRoot);

    if (scriptContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (ServerContextManager::IsScriptContextAlive(scriptContextInfo))
    {
        AutoReleaseContext<ServerScriptContext> autoScriptContext(scriptContextInfo);

#ifdef PROFILE_EXEC
        auto profiler = scriptContextInfo->GetCodeGenProfiler();
        if (profiler && profiler->IsInitialized())
        {
            profiler->ProfilePrint(Js::Configuration::Global.flags.Profile.GetFirstPhase());
        }
#endif

        scriptContextInfo->Close();
        ServerContextManager::UnRegisterScriptContext(scriptContextInfo);
    }

    return S_OK;
}
Esempio n. 5
0
HRESULT 
ServerSetWellKnownHostTypeId(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t threadContextRoot,
    /* [in] */ int typeId)
{
    ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer((void*)threadContextRoot);

    if (threadContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (!ServerContextManager::IsThreadContextAlive(threadContextInfo))
    {
        Assert(false);
        return E_ACCESSDENIED;
    }

    AutoReleaseContext<ServerThreadContext> autoThreadContext(threadContextInfo);
    threadContextInfo->SetWellKnownHostTypeId((Js::TypeId)typeId);

    return S_OK;
}
static int __cdecl _CrtAllocHook_managed_thunk
(
    int allocType,
    void *userData,
    size_t size,
    int blockType,
    long requestNumber,
    const unsigned char *filename,
    int lineNumber
)
{
    // Avoid thread-sync issues
    _CRT_ALLOC_HOOK_M pfnAllocHookManaged= (_CRT_ALLOC_HOOK_M) DecodePointer(__pfnAllocHookManaged);

    if (pfnAllocHookManaged != NULL)
    {
        return (*pfnAllocHookManaged)(allocType, userData, size, blockType, requestNumber, filename, lineNumber);
    }
    else
    {
        // we want to return 1 (TRUE) here
        // because if we return 0 (FALSE) it will call _CrtDbgReport()
        return 1;
    }
}
Esempio n. 7
0
HRESULT
ServerFreeAllocation(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t threadContextInfo,
    /* [in] */ intptr_t address)
{
    AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));
    ServerThreadContext * context = (ServerThreadContext*)DecodePointer((void*)threadContextInfo);

    if (context == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (!ServerContextManager::IsThreadContextAlive(context))
    {
        Assert(false);
        return E_ACCESSDENIED;
    }

    return ServerCallWrapper(context, [&]()->HRESULT 
    {
        AutoReleaseContext<ServerThreadContext> autoThreadContext(context);
        context->SetValidCallTargetForCFG((PVOID)address, false);
        context->GetCodeGenAllocators()->emitBufferManager.FreeAllocation((void*)address);
        return S_OK;
    });
}
static void __cdecl CrtDoForAllClientObjects_thunk(void *pData, void *pContext)
{
    _PHEAP_m pFunc = (_PHEAP_m) DecodePointer(__pfnHeapfunc);

    if (pFunc)
    {
        pFunc(pData, pContext);
    }
}
/***
*int _callnewh - call the appropriate new handler
*
*Purpose:
*       Call the appropriate new handler.
*
*Entry:
*       None
*
*Return:
*       1 for success
*       0 for failure
*       may throw bad_alloc
*
*******************************************************************************/
extern "C" int __cdecl _callnewh(size_t size)
{
        {
            _PNH pnh = (_PNH) DecodePointer(_pnhHeap);

            if ( (pnh == NULL) || ((*pnh)(size) == 0) )
                return 0;
        }
        return 1;
}
Esempio n. 10
0
File: heap_dbg.c Progetto: Gd58/MCF
void __MCF_CRT_HeapDbgValidateBlockBasic(unsigned char **ppRaw, unsigned char *pContents, const void *pRetAddr){
	unsigned char *const pRaw = pContents - GUARD_BAND_SIZE;
	*ppRaw = pRaw;

	const size_t uSize = __MCF_CRT_ReallyGetUsableSize(pRaw) - GUARD_BAND_SIZE * 2;

	void *const *ppGuard1 = (void *const *)pContents;
	void *const *ppGuard2 = (void *const *)(pContents + uSize);
	for(unsigned i = 0; i < GUARD_BAND_SIZE; i += sizeof(void *)){
		--ppGuard1;

		void *pTemp1, *pTemp2;
		__builtin_memcpy(&pTemp1, ppGuard1, sizeof(void *));
		__builtin_memcpy(&pTemp2, ppGuard2, sizeof(void *));
		if((DecodePointer(pTemp1) != ppGuard2) || (DecodePointer(pTemp2) != ppGuard1)){
			MCF_CRT_BailF(L"__MCF_CRT_HeapDbgValidate() 失败:侦测到堆损坏。\n调用返回地址:%p", pRetAddr);
		}

		++ppGuard2;
	}
}
/***
*int _matherr(struct _exception *except) - handle math errors
*
*Purpose:
*   Permits the user customize fp error handling by redefining this function.
*
*   The default matherr does nothing and returns 0
*
*Entry:
*
*Exit:
*
*Exceptions:
*******************************************************************************/
extern "C" int __cdecl _matherr(struct _exception *pexcept)
{

    /*
     * If user has supplied a _matherr implementation, pass control to
     * it and let it handle the error.
     */
    _HANDLE_MATH_ERROR_M pmatherr = (_HANDLE_MATH_ERROR_M) DecodePointer(pusermatherr);
    if ( pmatherr != NULL )
            return pmatherr(pexcept);

    return 0;
}
static void __cdecl _CrtDumpClient_managed_thunk
(
    void *userPortion,
    size_t blockSize
)
{
    // Avoid thread-sync issues
    _CRT_DUMP_CLIENT_M pfnDumpClientManaged = (_CRT_DUMP_CLIENT_M) DecodePointer(__pfnDumpClientManaged);

    if (pfnDumpClientManaged != NULL)
    {
        (*pfnDumpClientManaged)(userPortion, blockSize);
    }
}
static int __cdecl _CrtReportHook_managed_thunk(int i, char *pCh, int *pInt)
{
    // Avoid thread-sync issues
    _CRT_REPORT_HOOK_M pfnReportHookManaged = (_CRT_REPORT_HOOK_M) DecodePointer(__pfnReportHookManaged);

    if (pfnReportHookManaged != NULL)
    {
        return (*pfnReportHookManaged)(i, pCh, pInt);
    }
    else
    {
        return 0;
    }
}
Esempio n. 14
0
static SECStatus DecodeImplicit(void* dest,
                     const SEC_ASN1Template* templateEntry,
                     SECItem* src, PLArenaPool* arena)
{
    if (templateEntry->kind & SEC_ASN1_POINTER)
    {
        return DecodePointer((void*)((char*)dest ),
                             templateEntry, src, arena, PR_FALSE);
    }
    else
    {
        return DecodeInline((void*)((char*)dest ),
                             templateEntry, src, arena, PR_FALSE);
    }
}
Esempio n. 15
0
/***
*_PNH _set_new_handler(_PNH pnh) - set the new handler
*
*Purpose:
*       _set_new_handler is different from the ANSI C++ working standard definition
*       of set_new_handler.  Therefore it has a leading underscore in its name.
*
*Entry:
*       Pointer to the new handler to be installed.
*
*Return:
*       Previous new handler
*
*******************************************************************************/
_PNH __cdecl _set_new_handler(
        _PNH pnh
        )
{
        _PNH pnhOld;

        /* lock the heap */
        _mlock(_HEAP_LOCK);

        pnhOld = (_PNH) DecodePointer(_pnhHeap);
        _pnhHeap = (_PNH) EncodePointer(pnh);

        /* unlock the heap */
        _munlock(_HEAP_LOCK);

        return(pnhOld);
}
Esempio n. 16
0
HRESULT
ServerIsNativeAddr(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t threadContextInfo,
    /* [in] */ intptr_t address,
    /* [out] */ __RPC__out boolean * result)
{
    ServerThreadContext * context = (ServerThreadContext*)DecodePointer((void*)threadContextInfo);

    if (context == nullptr)
    {
        *result = false;
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (!ServerContextManager::IsThreadContextAlive(context))
    {
        *result = false;
        Assert(false);
        return E_ACCESSDENIED;
    }

    AutoReleaseContext<ServerThreadContext> autoThreadContext(context);
    return ServerCallWrapper(context, [&]()->HRESULT
    {
        PreReservedVirtualAllocWrapper *preReservedVirtualAllocWrapper = context->GetPreReservedVirtualAllocator();
        if (preReservedVirtualAllocWrapper->IsInRange((void*)address))
        {
            *result = true;
        }
        else if (!context->IsAllJITCodeInPreReservedRegion())
        {
            CustomHeap::CodePageAllocators::AutoLock autoLock(context->GetCodePageAllocators());
            *result = context->GetCodePageAllocators()->IsInNonPreReservedPageAllocator((void*)address);
        }
        else
        {
            *result = false;
        }

        return S_OK;
    });
}
Esempio n. 17
0
HRESULT
ServerInitializeScriptContext(
    /* [in] */ handle_t binding,
    /* [in] */ __RPC__in ScriptContextDataIDL * scriptContextData,
    /* [in] */ intptr_t threadContextInfoAddress,
    /* [out] */ __RPC__out intptr_t * scriptContextInfoAddress)
{
    AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));

    ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer((void*)threadContextInfoAddress);

    if (threadContextInfo == nullptr)
    {
        Assert(false);
        *scriptContextInfoAddress = 0;
        return RPC_S_INVALID_ARG;
    }

    if (!ServerContextManager::IsThreadContextAlive(threadContextInfo))
    {
        Assert(false);
        *scriptContextInfoAddress = 0;
        return E_ACCESSDENIED;
    }

    return ServerCallWrapper(threadContextInfo, [&]()->HRESULT
    {
        ServerScriptContext * contextInfo = HeapNew(ServerScriptContext, scriptContextData, threadContextInfo);

        ServerContextManager::RegisterScriptContext(contextInfo);

        *scriptContextInfoAddress = (intptr_t)EncodePointer(contextInfo);

#if !FLOATVAR
        // TODO: should move this to ServerInitializeThreadContext, also for the fields in IDL
        XProcNumberPageSegmentImpl::Initialize(contextInfo->IsRecyclerVerifyEnabled(), contextInfo->GetRecyclerVerifyPad());
#endif
        return S_OK;
    });
}
Esempio n. 18
0
HRESULT
ServerCleanupScriptContext(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t scriptContextRoot)
{
    ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer((void*)scriptContextRoot);

    if (scriptContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (ServerContextManager::IsScriptContextAlive(scriptContextInfo))
    {
        AutoReleaseContext<ServerScriptContext> autoScriptContext(scriptContextInfo);        
        scriptContextInfo->Close();
        ServerContextManager::UnRegisterScriptContext(scriptContextInfo);
    }

    return S_OK;
}
Esempio n. 19
0
HRESULT
ServerCleanupThreadContext(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t threadContextRoot)
{
    AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));

    ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer((void*)threadContextRoot);
    if (threadContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (ServerContextManager::IsThreadContextAlive(threadContextInfo))
    {
        AutoReleaseContext<ServerThreadContext> autoThreadContext(threadContextInfo);
        threadContextInfo->Close();
        ServerContextManager::UnRegisterThreadContext(threadContextInfo);
    }
    return S_OK;
}
Esempio n. 20
0
HRESULT
ServerUpdatePropertyRecordMap(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t threadContextInfoAddress,
    /* [in] */ __RPC__in UpdatedPropertysIDL * updatedProps)
{
    AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));

    ServerThreadContext * threadContextInfo = (ServerThreadContext*)DecodePointer((void*)threadContextInfoAddress);

    if (threadContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (!ServerContextManager::IsThreadContextAlive(threadContextInfo))
    {
        Assert(false);
        return E_ACCESSDENIED;
    }

    AutoReleaseContext<ServerThreadContext> autoThreadContext(threadContextInfo);
    return ServerCallWrapper(threadContextInfo, [&]()->HRESULT
    {
        for (uint i = 0; i < updatedProps->reclaimedPropertyCount; ++i)
        {
            threadContextInfo->RemoveFromPropertyMap((Js::PropertyId)updatedProps->reclaimedPropertyIdArray[i]);
        }

        for (uint i = 0; i < updatedProps->newRecordCount; ++i)
        {
            threadContextInfo->AddToPropertyMap((Js::PropertyRecord *)updatedProps->newRecordArray[i]);
        }

        return S_OK;
    });
}
/***
*_CRT_REPORT_HOOK_M _CrtSetReportHook() - set client report hook
*
*Purpose:
*       set client report hook
*
*Entry:
*       _CRT_REPORT_HOOK_M pfnNewHook - new report hook
*
*Exit:
*       return previous hook
*
*Exceptions:
*
*******************************************************************************/
_MRTIMP _CRT_REPORT_HOOK_M __cdecl _CrtSetReportHook(
        _CRT_REPORT_HOOK_M pfnNewHook
        )
{
    if(_atexit_m_appdomain(_CrtReportHook_managed_cleanup)!=0)
    {
        return NULL;
    }

    _CRT_REPORT_HOOK_M pfnOldHook = (_CRT_REPORT_HOOK_M) DecodePointer(__pfnReportHookManaged);
    if (pfnNewHook)
    {
        __pfnReportHookManaged = (_CRT_REPORT_HOOK_M) EncodePointer(pfnNewHook);
        _CrtSetReportHook((_CRT_REPORT_HOOK)_CrtReportHook_managed_thunk);
    }
    else
    {
        _CRT_REPORT_HOOK_M enull = (_CRT_REPORT_HOOK_M) EncodePointer(NULL)();
        __pfnReportHookManaged = enull;
        _CrtSetReportHook((_CRT_REPORT_HOOK)NULL);
    }
    return pfnOldHook;
}
Esempio n. 22
0
static SECStatus DecodeExplicit(void* dest,
                     const SEC_ASN1Template* templateEntry,
                     SECItem* src, PLArenaPool* arena)
{
    SECStatus rv = SECSuccess;
    SECItem subItem;
    SECItem constructed = *src;

    rv = GetItem(&constructed, &subItem, PR_FALSE);

    if (SECSuccess == rv)
    {
        if (templateEntry->kind & SEC_ASN1_POINTER)
        {
            rv = DecodePointer(dest, templateEntry, &subItem, arena, PR_TRUE);
        }
        else
        {
            rv = DecodeInline(dest, templateEntry, &subItem, arena, PR_TRUE);
        }
    }

    return rv;
}
/***
*_CRT_DUMP_CLIENT_M _CrtSetDumpClient() - set client dump hook
*
*Purpose:
*       set client dump hook
*
*Entry:
*       _CRT_DUMP_CLIENT_M pfnNewHook - new dump hook
*
*Exit:
*       return previous hook
*
*Exceptions:
*
*******************************************************************************/
_MRTIMP _CRT_DUMP_CLIENT_M __cdecl _CrtSetDumpClient
(
    _CRT_DUMP_CLIENT_M pfnNewHook
)
{
    if(_atexit_m_appdomain(_CrtDumpClient_managed_cleanup)!=0)
    {
        return NULL;
    }

    _CRT_DUMP_CLIENT_M pfnOldHook = (_CRT_DUMP_CLIENT_M) DecodePointer(__pfnDumpClientManaged);
    if (pfnNewHook)
    {
        __pfnDumpClientManaged = (_CRT_DUMP_CLIENT_M) EncodePointer(pfnNewHook);
        _CrtSetDumpClient((_CRT_DUMP_CLIENT)_CrtDumpClient_managed_thunk);
    }
    else
    {
        _CRT_DUMP_CLIENT_M enull = (_CRT_DUMP_CLIENT_M) EncodePointer(NULL)();
        __pfnDumpClientManaged = enull;
        _CrtSetDumpClient((_CRT_DUMP_CLIENT)NULL);
    }
    return pfnOldHook;
}
Esempio n. 24
0
HRESULT
ServerSetIsPRNGSeeded(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t scriptContextInfoAddress,
    /* [in] */ boolean value)
{
    ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer((void*)scriptContextInfoAddress);

    if (scriptContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (!ServerContextManager::IsScriptContextAlive(scriptContextInfo))
    {
        Assert(false);
        return E_ACCESSDENIED;
    }

    AutoReleaseContext<ServerScriptContext> autoScriptContext(scriptContextInfo);
    scriptContextInfo->SetIsPRNGSeeded(value != FALSE);
    return S_OK;
}
Esempio n. 25
0
    ////////////////////////////////////////////////////////////////////////////
    //
    //  GetSortGetHandle()
    //
    //  Get the SortGetHandle() function for the proper dll version.
    //
    ////////////////////////////////////////////////////////////////////////////
    SORTGETHANDLE GetSortGetHandle(__in DWORD dwVersion)
    {
        if(dwVersion == SORT_VERSION_DEFAULT)
        {
            // If we haven't tried to load the module/proc before do so now
            if (g_hSortDefault == (HMODULE)-1)
            {
                LoadSortDllAndPublish(SORT_DEFAULT_DLL_NAME, SORT_VERSION_DEFAULT, &g_pDefaultGetHandle, &g_pDefaultCloseHandle, &g_hSortDefault);
            }

            // This check is necessary because the LoadSortDllAndPublish call may have failed since some platforms
            // won't have nlssorting.dll (e.g. Windows 8 and above).
            if (g_hSortDefault != (HMODULE)-1) 
            {
                return (SORTGETHANDLE)DecodePointer(g_pDefaultGetHandle);
            }
        }

        HMODULE* pHSortModule; 
        SORTGETHANDLE*   ppGetHandle;
        SORTCLOSEHANDLE* ppCloseHandle;

        if(dwVersion == SORT_VERSION_V4)
        {
            ppGetHandle = &g_pV4GetHandle;
            ppCloseHandle = &g_pV4CloseHandle;
            pHSortModule = &g_hSortCompatV4;
        } 
        else if(dwVersion == SORT_VERSION_WHIDBEY) 
        {
            ppGetHandle = &g_pV2GetHandle;
            ppCloseHandle = &g_pV2CloseHandle;
            pHSortModule = &g_hSortCompatV2;
        }
        else
        {
            // Unsupported sorting version.
            return NULL;
        }

        if(*pHSortModule == (HMODULE) -1)
        {
            // get module name - the module name should be "Sort"+dwVersion.ToString("x8")+".dll"
            WCHAR moduleName[] = W("Sort00000000.dll");
            // replace the "00000000" with the hexadecimal of dwVersion
            LPCWSTR hex = W("0123456789abcdef");
            WCHAR* p = &moduleName[4+8]; // position at end of number part of dll name

            unsigned int value = dwVersion;

            while (value != 0 && p != moduleName) {
                int digit = value & 0xF;
                *--p = hex[digit];
                value >>= 4;
            }

            if(!LoadSortDllAndPublish(&moduleName[0], dwVersion, ppGetHandle, ppCloseHandle, pHSortModule)) 
            {
                // We failed to load a versioned sort dll, try to fall back to the current version.
                // If we haven't tried to load the module/proc before do so now
                if (g_hSortDefault == (HMODULE)-1)
                {
                    LoadSortDllAndPublish(SORT_DEFAULT_DLL_NAME, SORT_VERSION_DEFAULT, &g_pDefaultGetHandle, &g_pDefaultCloseHandle, &g_hSortDefault);
                }

                *pHSortModule = g_hSortDefault;
                *ppCloseHandle = g_pDefaultCloseHandle;
                *ppGetHandle = g_pDefaultGetHandle;
            }           
        }
Esempio n. 26
0
/*********************************************************************
 *  _decode_pointer (MSVCR90.@)
 *
 * cdecl version of DecodePointer
 *
 */
void * CDECL MSVCR90_decode_pointer(void * ptr)
{
    return DecodePointer(ptr);
}
Esempio n. 27
0
HRESULT
ServerRemoteCodeGen(
    /* [in] */ handle_t binding,
    /* [in] */ intptr_t scriptContextInfoAddress,
    /* [in] */ __RPC__in CodeGenWorkItemIDL *workItemData,
    /* [out] */ __RPC__out JITOutputIDL *jitData)
{
    AUTO_NESTED_HANDLED_EXCEPTION_TYPE(static_cast<ExceptionType>(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));
    LARGE_INTEGER start_time = { 0 };
    if (PHASE_TRACE1(Js::BackEndPhase))
    {
        QueryPerformanceCounter(&start_time);
    }
    memset(jitData, 0, sizeof(JITOutputIDL));

    ServerScriptContext * scriptContextInfo = (ServerScriptContext*)DecodePointer((void*)scriptContextInfoAddress);

    if (scriptContextInfo == nullptr)
    {
        Assert(false);
        return RPC_S_INVALID_ARG;
    }

    if (!ServerContextManager::IsScriptContextAlive(scriptContextInfo))
    {
        Assert(false);
        return E_ACCESSDENIED;
    }

    AutoReleaseContext<ServerScriptContext> autoScriptContext(scriptContextInfo);

    return ServerCallWrapper(scriptContextInfo, [&]() ->HRESULT
    {
        scriptContextInfo->UpdateGlobalObjectThisAddr(workItemData->globalThisAddr);
        ServerThreadContext * threadContextInfo = scriptContextInfo->GetThreadContext();

        NoRecoverMemoryJitArenaAllocator jitArena(L"JITArena", threadContextInfo->GetPageAllocator(), Js::Throw::OutOfMemory);
        JITTimeWorkItem * jitWorkItem = Anew(&jitArena, JITTimeWorkItem, workItemData);

        if (PHASE_VERBOSE_TRACE_RAW(Js::BackEndPhase, jitWorkItem->GetJITTimeInfo()->GetSourceContextId(), jitWorkItem->GetJITTimeInfo()->GetLocalFunctionId()))
        {
            LARGE_INTEGER freq;
            LARGE_INTEGER end_time;
            QueryPerformanceCounter(&end_time);
            QueryPerformanceFrequency(&freq);

            Output::Print(
                L"BackendMarshalIn - function: %s time:%8.6f mSec\r\n",
                jitWorkItem->GetJITFunctionBody()->GetDisplayName(),
                (((double)((end_time.QuadPart - workItemData->startTime)* (double)1000.0 / (double)freq.QuadPart))) / (1));
            Output::Flush();
        }

        auto profiler = scriptContextInfo->GetCodeGenProfiler();
#ifdef PROFILE_EXEC
        if (profiler && !profiler->IsInitialized())
        {
            profiler->Initialize(threadContextInfo->GetPageAllocator(), nullptr);
        }
#endif
        if (jitWorkItem->GetWorkItemData()->xProcNumberPageSegment)
        {
            jitData->numberPageSegments = (XProcNumberPageSegment*)midl_user_allocate(sizeof(XProcNumberPageSegment));
            if (!jitData->numberPageSegments)
            {
                return E_OUTOFMEMORY;
            }
            __analysis_assume(jitData->numberPageSegments);

            memcpy_s(jitData->numberPageSegments, sizeof(XProcNumberPageSegment), jitWorkItem->GetWorkItemData()->xProcNumberPageSegment, sizeof(XProcNumberPageSegment));
        }

        Func::Codegen(
            &jitArena,
            jitWorkItem,
            threadContextInfo,
            scriptContextInfo,
            jitData,
            nullptr,
            nullptr,
            jitWorkItem->GetPolymorphicInlineCacheInfo(),
            threadContextInfo->GetCodeGenAllocators(),
#if !FLOATVAR
            nullptr, // number allocator
#endif
            profiler,
            true);


#ifdef PROFILE_EXEC
        if (profiler && profiler->IsInitialized())
        {
            profiler->ProfilePrint(Js::Configuration::Global.flags.Profile.GetFirstPhase());
        }
#endif

        if (PHASE_VERBOSE_TRACE_RAW(Js::BackEndPhase, jitWorkItem->GetJITTimeInfo()->GetSourceContextId(), jitWorkItem->GetJITTimeInfo()->GetLocalFunctionId()))
        {
            LARGE_INTEGER freq;
            LARGE_INTEGER end_time;
            QueryPerformanceCounter(&end_time);
            QueryPerformanceFrequency(&freq);

            Output::Print(
                L"EndBackEndInner - function: %s time:%8.6f mSec\r\n",
                jitWorkItem->GetJITFunctionBody()->GetDisplayName(),
                (((double)((end_time.QuadPart - start_time.QuadPart)* (double)1000.0 / (double)freq.QuadPart))) / (1));
            Output::Flush();

        }
        LARGE_INTEGER out_time = { 0 };
        if (PHASE_TRACE1(Js::BackEndPhase))
        {
            QueryPerformanceCounter(&out_time);
            jitData->startTime = out_time.QuadPart;
        }

        return S_OK;
    });
}
Esempio n. 28
0
static SECStatus DecodeItem(void* dest,
                     const SEC_ASN1Template* templateEntry,
                     SECItem* src, PLArenaPool* arena, PRBool checkTag)
{
    SECStatus rv = SECSuccess;
    SECItem temp;
    SECItem mark;
    PRBool pop = PR_FALSE;
    PRBool decode = PR_TRUE;
    PRBool save = PR_FALSE;
    unsigned long kind;
    PRBool match = PR_TRUE;
    PRBool optional = PR_FALSE;

    PR_ASSERT(src && dest && templateEntry && arena);
#if 0
    if (!src || !dest || !templateEntry || !arena)
    {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        rv = SECFailure;
    }
#endif

    if (SECSuccess == rv)
    {
        /* do the template validation */
        kind = templateEntry->kind;
        optional = (0 != (kind & SEC_ASN1_OPTIONAL));
        if (!kind)
        {
            PORT_SetError(SEC_ERROR_BAD_TEMPLATE);
            rv = SECFailure;
        }
    }

    if (SECSuccess == rv)
    {
#ifdef DEBUG
        if (kind & SEC_ASN1_DEBUG_BREAK)
        {
            /* when debugging the decoder or a template that fails to
            decode, put SEC_ASN1_DEBUG in the component that gives you
            trouble. The decoder will then get to this block and assert.
            If you want to debug the rest of the code, you can set a
            breakpoint and set dontassert to PR_TRUE, which will let
            you skip over the assert and continue the debugging session
            past it. */
            PRBool dontassert = PR_FALSE;
            PR_ASSERT(dontassert); /* set bkpoint here & set dontassert*/
        }
#endif

        if ((kind & SEC_ASN1_SKIP) ||
            (kind & SEC_ASN1_SAVE))
        {
            /* if skipping or saving this component, don't decode it */
            decode = PR_FALSE;
        }
    
        if (kind & (SEC_ASN1_SAVE | SEC_ASN1_OPTIONAL))
        {
            /* if saving this component, or if it is optional, we may not want to
               move past it, so save the position in case we have to rewind */
            mark = *src;
            if (kind & SEC_ASN1_SAVE)
            {
                save = PR_TRUE;
                if (0 == (kind & SEC_ASN1_SKIP))
                {
                    /* we will for sure have to rewind when saving this
                       component and not skipping it. This is true for all
                       legacy uses of SEC_ASN1_SAVE where the following entry
                       in the template would causes the same component to be
                       processed again */
                    pop = PR_TRUE;
                }
            }
        }

        rv = GetItem(src, &temp, PR_TRUE);
    }

    if (SECSuccess == rv)
    {
        /* now check if the component matches what we expect in the template */

        if (PR_TRUE == checkTag)

        {
            rv = MatchComponentType(templateEntry, &temp, &match, dest);
        }

        if ( (SECSuccess == rv) && (PR_TRUE != match) )
        {
            if (kind & SEC_ASN1_OPTIONAL)
            {

                /* the optional component is missing. This is not fatal. */
                /* Rewind, don't decode, and don't save */
                pop = PR_TRUE;
                decode = PR_FALSE;
                save = PR_FALSE;
            }
            else
            {
                /* a required component is missing. abort */
                PORT_SetError(SEC_ERROR_BAD_DER);
                rv = SECFailure;
            }
        }
    }

    if ((SECSuccess == rv) && (PR_TRUE == decode))
    {
        /* the order of processing here is is the tricky part */
        /* we start with our special cases */
        /* first, check the component class */
        if (kind & SEC_ASN1_INLINE)
        {
            /* decode inline template */
            rv = DecodeInline(dest, templateEntry, &temp , arena, PR_TRUE);
        }

        else
        if (kind & SEC_ASN1_EXPLICIT)
        {
            rv = DecodeExplicit(dest, templateEntry, &temp, arena);
        }
        else
        if ( (SEC_ASN1_UNIVERSAL != (kind & SEC_ASN1_CLASS_MASK)) &&

              (!(kind & SEC_ASN1_EXPLICIT)))
        {

            /* decode implicitly tagged components */
            rv = DecodeImplicit(dest, templateEntry, &temp , arena);
        }
        else
        if (kind & SEC_ASN1_POINTER)
        {
            rv = DecodePointer(dest, templateEntry, &temp, arena, PR_TRUE);
        }
        else
        if (kind & SEC_ASN1_CHOICE)
        {
            rv = DecodeChoice(dest, templateEntry, &temp, arena);
        }
        else
        if (kind & SEC_ASN1_ANY)
        {
            /* catch-all ANY type, don't decode */
            save = PR_TRUE;
            if (kind & SEC_ASN1_INNER)
            {
                /* skip the tag and length */
                SECItem newtemp = temp;
                rv = GetItem(&newtemp, &temp, PR_FALSE);
            }
        }
        else
        if (kind & SEC_ASN1_GROUP)
        {
            if ( (SEC_ASN1_SEQUENCE == (kind & SEC_ASN1_TAGNUM_MASK)) ||
                 (SEC_ASN1_SET == (kind & SEC_ASN1_TAGNUM_MASK)) )
            {
                rv = DecodeGroup(dest, templateEntry, &temp , arena);
            }
            else
            {
                /* a group can only be a SET OF or SEQUENCE OF */
                PORT_SetError(SEC_ERROR_BAD_TEMPLATE);
                rv = SECFailure;
            }
        }
        else
        if (SEC_ASN1_SEQUENCE == (kind & SEC_ASN1_TAGNUM_MASK))
        {
            /* plain SEQUENCE */
            rv = DecodeSequence(dest, templateEntry, &temp , arena);
        }
        else
        {
            /* handle all other types as "save" */
            /* we should only get here for primitive universal types */
            SECItem newtemp = temp;
            rv = GetItem(&newtemp, &temp, PR_FALSE);
            save = PR_TRUE;
            if ((SECSuccess == rv) &&
                SEC_ASN1_UNIVERSAL == (kind & SEC_ASN1_CLASS_MASK))
            {
                unsigned long tagnum = kind & SEC_ASN1_TAGNUM_MASK;
                if ( temp.len == 0 && (tagnum == SEC_ASN1_BOOLEAN ||
                                       tagnum == SEC_ASN1_INTEGER ||
                                       tagnum == SEC_ASN1_BIT_STRING ||
                                       tagnum == SEC_ASN1_OBJECT_ID ||
                                       tagnum == SEC_ASN1_ENUMERATED ||
                                       tagnum == SEC_ASN1_UTC_TIME ||
                                       tagnum == SEC_ASN1_GENERALIZED_TIME) )
                {
                    /* these types MUST have at least one content octet */
                    PORT_SetError(SEC_ERROR_BAD_DER);
                    rv = SECFailure;
                }
                else
                switch (tagnum)
                {
                /* special cases of primitive types */
                case SEC_ASN1_INTEGER:
                    {
                        /* remove leading zeroes if the caller requested
                           siUnsignedInteger
                           This is to allow RSA key operations to work */
                        SECItem* destItem = (SECItem*) ((char*)dest +
                                            templateEntry->offset);
                        if (destItem && (siUnsignedInteger == destItem->type))
                        {
                            while (temp.len > 1 && temp.data[0] == 0)
                            {              /* leading 0 */
                                temp.data++;
                                temp.len--;
                            }
                        }
                        break;
                    }

                case SEC_ASN1_BIT_STRING:
                    {
                        /* change the length in the SECItem to be the number
                           of bits */
                        temp.len = (temp.len-1)*8 - (temp.data[0] & 0x7);
                        temp.data++;
                        break;
                    }

                default:
                    {
                        break;
                    }
                }
            }
        }
    }

    if ((SECSuccess == rv) && (PR_TRUE == save))
    {
        SECItem* destItem = (SECItem*) ((char*)dest + templateEntry->offset);
        if (destItem)
        {
            /* we leave the type alone in the destination SECItem.
               If part of the destination was allocated by the decoder, in
               cases of POINTER, SET OF and SEQUENCE OF, then type is set to
               siBuffer due to the use of PORT_ArenaZAlloc*/
            destItem->data = temp.len ? temp.data : NULL;
            destItem->len = temp.len;
        }
        else
        {
            PORT_SetError(SEC_ERROR_INVALID_ARGS);
            rv = SECFailure;
        }
    }

    if (PR_TRUE == pop)
    {
        /* we don't want to move ahead, so restore the position */
        *src = mark;
    }
    return rv;
}
Esempio n. 29
0
void *_decode_pointer(void *ptr)
{
	return DecodePointer(ptr);
}
Esempio n. 30
0
errno_t __cdecl rand_s
(
    unsigned int *_RandomValue
)
{
    PGENRANDOM pfnRtlGenRandom = (PGENRANDOM) DecodePointer(g_pfnRtlGenRandom);
    _VALIDATE_RETURN_ERRCODE( _RandomValue != NULL, EINVAL );
    *_RandomValue = 0; // Review : better value to initialize it to?

    if ( pfnRtlGenRandom == NULL )
    {
        PGENRANDOM encoded;
        void* enull;
#ifdef _CORESYS
#define RAND_DLL L"cryptbase.dll"
#else  /* _CORESYS */
#define RAND_DLL L"ADVAPI32.DLL"
#endif  /* _CORESYS */
        // advapi32.dll/cryptbase.dll is unloaded when the App exits.
        HMODULE hRandDll = LoadLibraryExW(RAND_DLL, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
#ifndef _CORESYS
        if (!hRandDll && GetLastError() == ERROR_INVALID_PARAMETER)
        {
            // LOAD_LIBRARY_SEARCH_SYSTEM32 is not supported on this platfrom,
            // try one more time using default options
            hRandDll = LoadLibraryExW(RAND_DLL, NULL, 0);
        }
#endif  /* _CORESYS */
        if (!hRandDll)
        {
            _VALIDATE_RETURN_ERRCODE(("rand_s is not available on this platform", 0), EINVAL);
        }

        pfnRtlGenRandom = ( PGENRANDOM ) GetProcAddress( hRandDll, _TO_STR( RtlGenRandom ) );
        if ( pfnRtlGenRandom == NULL )
        {
            _VALIDATE_RETURN_ERRCODE(("rand_s is not available on this platform", 0), _get_errno_from_oserr(GetLastError()));
        }
        encoded = (PGENRANDOM) EncodePointer(pfnRtlGenRandom);
        enull = EncodePointer(NULL);
#ifdef _M_IX86
        if ( (void*)(LONG_PTR)InterlockedExchange(
                ( LONG* )&g_pfnRtlGenRandom,
                ( LONG )( LONG_PTR )encoded)
            != enull )
#else  /* _M_IX86 */
        if ( InterlockedExchangePointer(
                ( void** )&g_pfnRtlGenRandom,
                ( void* )encoded)
            != enull )
#endif  /* _M_IX86 */
        {
            /* A different thread has already loaded advapi32.dll/cryptbase.dll. */
            FreeLibrary( hRandDll );
        }
    }

    if ( !(*pfnRtlGenRandom)( _RandomValue, ( ULONG )sizeof( unsigned int ) ) )
    {
        errno = ENOMEM;
        return errno;
    }
    return 0;
}