Click here to Skip to main content
12,399,799 members (45,501 online)
Click here to Skip to main content
Articles » Languages » MSIL » General » Downloads

Stats

27.7K views
816 downloads
39 bookmarked
Posted

ILRewriting for beginners

, 27 Sep 2012 Ms-PL
Runtime IL-Rewriting can be used to add behavior such as logging to applications, or redirect calls from one API to another. This article and accompanying source code explains how to substitute a method call at runtime.
ILRewriting_demo
ILRewriteProfiler.dll
InterceptApp.exe
InterceptLib.dll
SampleApp1.exe
ILRewriting_src
ILEmitTest
Properties
ILRewriteProfiler
exports.def
ILRewriteProfiler.vcxproj.filters
ILRewriteProfiler.vcxproj.user
InterceptApp
app.aps
app.ico
InterceptApp.vcxproj.filters
InterceptApp.vcxproj.user
InterceptLib
InterceptLib.snk
Properties
SampleApp1
Properties
SampleApp1.snk
// ----------------------------------------------------------------------------------------------
// Copyright (c) Mattias H�gstr�m.
// ----------------------------------------------------------------------------------------------
// This source code is subject to terms and conditions of the Microsoft Public License. A 
// copy of the license can be found in the License.html file at the root of this distribution. 
// If you cannot locate the Microsoft Public License, please send an email to 
// dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
// by the terms of the Microsoft Public License.
// ----------------------------------------------------------------------------------------------
// You must not remove this notice, or any other, from this software.
// ----------------------------------------------------------------------------------------------

#include "stdafx.h"

#include "ILRewriteHelper.h"
#include "ILRewriter.h"
#include "NullILRewriter.h"
#include "FunctionInfo.h"
//#include "TinyILWriter.h"
//#include "FatILWriter.h"
#include "DummyILRewriter.h"
#include "ProfilerLoggers.h"
#include <cor.h>
#include <corhlpr.h>
#include <sstream>
#include <map>


ILRewriteHelper::ILRewriteHelper()
{
   m_info = nullptr;
   m_systemObjectTypeDef = mdTypeDefNil;
   m_systemDateTimeTypeDef = mdTypeDefNil;
   m_mscorlibModuleID = 0;
}

ILRewriteHelper::ILRewriteHelper(ICorProfilerInfo* info)
{
   m_info = info;
   m_systemObjectTypeDef = mdTypeDefNil;
   m_systemDateTimeTypeDef = mdTypeDefNil;
   m_mscorlibModuleID = 0;
}

ILRewriteHelper::~ILRewriteHelper()
{
   m_info = nullptr;
}

void ILRewriteHelper::SetCorProfilerInfo(ICorProfilerInfo* info)
{
   m_info = info;
}

bool ILRewriteHelper::IsTiny(LPCBYTE methodBytes)
{
   const void* pek = methodBytes;
   const COR_ILMETHOD_TINY* objPek = static_cast<const COR_ILMETHOD_TINY*>(pek);
   return objPek->IsTiny();
}

bool ILRewriteHelper::OptionalCheck(HRESULT hr)
{
   switch (hr)
   {
   case S_OK:
   case S_FALSE:
   case META_S_DUPLICATE:
      return true;
   default:
      return false;
   }
}

void ILRewriteHelper::Check(HRESULT hr)
{
   switch (hr)
   {
   case S_OK:
   case S_FALSE:
      return;
   case META_S_DUPLICATE:
      //case 0x00131197:
      return;
   default:
      __debugbreak();
   }
}

ILRewriter* ILRewriteHelper::CreateILRewriter(PreludeILRewriter* preludeILRewriter, FunctionInfo* functionInfo)
{
   if (functionInfo == nullptr)
      return new NullILRewriter();
   if (functionInfo->GetFunctionID() == 0)
      return new NullILRewriter();

   LPCBYTE oldMethodBytes;
   ULONG oldMethodSize;

   Check(m_info->GetILFunctionBody(functionInfo->GetModuleID(), functionInfo->GetToken(), &oldMethodBytes, &oldMethodSize));

   g_debugLogger << functionInfo->GetFunctionName() << std::endl;
   
   return new DummyILRewriter(m_info, functionInfo, oldMethodBytes, oldMethodSize);

   //return new NullILRewriter();
   //if(IsTiny(oldMethodBytes))
   //{	
   //   g_debugLogger << " Tiny Header";

   //   if(oldMethodSize > (MAX_TINY_FORMAT_SIZE - preludeILRewriter->GetPreludeSize()))
   //   {	
   //      g_debugLogger << " Converted to fat header" << std::endl;
   //   }
   //    return new TinyILWriter(m_info, functionInfo, preludeILRewriter, oldMethodBytes, oldMethodSize);
   //}
   //else
   //{
   //   g_debugLogger << " Fat Header" << std::endl;
   //   return new FatILWriter(m_info, functionInfo, preludeILRewriter, oldMethodBytes, oldMethodSize);
   //}
}

const int MAX_LENGTH = 1024;

FunctionInfo* ILRewriteHelper::CreateFunctionInfo(FunctionID functionID)
{
   ClassID classID = 0;
   ModuleID moduleID = 0;
   mdToken tkMethod = 0;

   Check(m_info->GetFunctionInfo(functionID, &classID, &moduleID, &tkMethod));

   WCHAR moduleName[MAX_LENGTH];
   AssemblyID assemblyID;		
   Check(m_info->GetModuleInfo(moduleID, NULL, MAX_LENGTH, 0, moduleName, &assemblyID));

   WCHAR assemblyName[MAX_LENGTH];
   Check(m_info->GetAssemblyInfo(assemblyID, MAX_LENGTH, 0, assemblyName, NULL, NULL));

   if(wcscmp(assemblyName, L"InterceptLib") == 0 ||
      wcscmp(assemblyName, L"mscorlib") == 0 ||
      wcscmp(assemblyName, L"System") == 0)
   {
      return FunctionInfo::GetNullObject();
   }

   IMetaDataImport* metaDataImport = NULL;
   mdToken token = NULL;
   Check(m_info->GetTokenAndMetaDataFromFunction(functionID, IID_IMetaDataImport, (LPUNKNOWN *) &metaDataImport, &token));

   mdTypeDef classTypeDef;
   WCHAR functionName[MAX_LENGTH];
   WCHAR className[MAX_LENGTH];
   PCCOR_SIGNATURE signatureBlob;
   ULONG signatureBlobLength;
   DWORD methodAttributes = 0;
   Check(metaDataImport->GetMethodProps(token, &classTypeDef, functionName, MAX_LENGTH, 0, &methodAttributes, &signatureBlob, &signatureBlobLength, NULL, NULL));
   Check(metaDataImport->GetTypeDefProps(classTypeDef, className, MAX_LENGTH, 0, NULL, NULL));
   metaDataImport->Release();

   FunctionInfo* result = new FunctionInfo(functionID, classID, moduleID, tkMethod, functionName, className, assemblyName);	
   return result;
}

 void* ILRewriteHelper::AllocateNewMethodBody(ICorProfilerInfo* info, ModuleID moduleId, ULONG newMethodSize)
 {
    IMethodMalloc* methodMalloc = NULL;
    Check(info->GetILFunctionBodyAllocator(moduleId, &methodMalloc));
    void *result = methodMalloc->Alloc(newMethodSize);

    ZeroMemory(result, newMethodSize);
    //memset((BYTE*)result+newMethodSize, 0xFEEDBEEF, 100);
    methodMalloc->Release();
    return result;
 }

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

Share

About the Author

Mattias Högström
Architect Visma Software AB
Sweden Sweden
Mattias works at Visma, a leading Nordic ERP solution provider. He has good knowledge in C++/.Net development, test tool development, and debugging. His great passion is memory dump analysis. He likes giving talks and courses.

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 27 Sep 2012
Article Copyright 2012 by Mattias Högström
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid