Example #1
0
	HRESULT InjectedType::ReplaceMethodWith(const ModuleID moduleId, const mdToken functionToken, InstructionList &instructions, const mdSignature localVarSigTok, const unsigned minimumStackSize, ExceptionHandlerList &exceptions) const
	{
		IMAGE_COR_ILMETHOD* pMethodHeader = nullptr;
		ULONG iMethodSize = 0;
		GUARD_FAILURE_HRESULT(m_profilerInfo->GetILFunctionBody(moduleId, functionToken, (LPCBYTE*)&pMethodHeader, &iMethodSize));

		Method method(pMethodHeader);
		method.DeleteAllInstructions();
		method.AppendInstructions(instructions);
		method.SetMinimumStackSize(minimumStackSize);

		if (exceptions.size() > 0)
		{
			method.AddExceptionHandlers(exceptions);
		}

		ATL::CComPtr<IMethodMalloc> methodMalloc;
		GUARD_FAILURE_HRESULT(m_profilerInfo->GetILFunctionBodyAllocator(moduleId, &methodMalloc));

		IMAGE_COR_ILMETHOD* pNewMethod = static_cast<IMAGE_COR_ILMETHOD*>(methodMalloc->Alloc(method.GetMethodSize()));
		method.WriteMethod(pNewMethod);

		if (localVarSigTok != mdSignatureNil)
		{
			pNewMethod->Fat.Flags |= CorILMethod_InitLocals; // always added when local variables present: http://www.liranchen.com/2010/07/behind-locals-init-flag.html
			pNewMethod->Fat.LocalVarSigTok = localVarSigTok;
		}

		GUARD_FAILURE_HRESULT(m_profilerInfo->SetILFunctionBody(moduleId, functionToken, (LPCBYTE)pNewMethod));

		return S_OK;
	}