Click here to Skip to main content
15,892,537 members
Articles / Programming Languages / MSIL

ILRewriting for beginners

Rate me:
Please Sign up or sign in to vote.
4.56/5 (15 votes)
27 Sep 2012Ms-PL11 min read 62.3K   1.4K   46  
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.
// ----------------------------------------------------------------------------------------------
// 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 "ProfilerStarter.h"
#include <Windows.h>
#include <metahost.h>

#include <cor.h>
#include <corprof.h>

#include <list>
#include <string>
#include <iostream>
#include <string>
#include <sstream>
#include <tchar.h>
#include <strsafe.h>

#include "ClrHelper.h"

using namespace std;

static std::string ConvertStlString(std::wstring& text)
{    
   const std::string narrow(text.begin(), text.end());
   return narrow;
}

ProfilerStarter::ProfilerStarter()
{
   ZeroAll();
}

ProfilerStarter::~ProfilerStarter()
{
   ReleaseAll();
}

void ProfilerStarter::ReleaseAll()
{
   if (m_metahost != nullptr)
      m_metahost->Release();	
   if (m_runtimeInfo != nullptr)
      m_runtimeInfo->Release();
   if (m_clrProfiling != nullptr)
      m_clrProfiling->Release();
   ZeroAll();
}

void ProfilerStarter::ZeroAll()
{
   m_metahost = nullptr;
   m_clrProfiling = nullptr;
   m_runtimeInfo = nullptr;
   m_isAttached = false;
   m_processId = 0;
}	

HRESULT ProfilerStarter::Initialize()
{
   std::wstring version;
   if (!ClrHelper::GetV4RunTime(version))
      return E_FAIL;

   HRESULT hr = S_OK;
   do
   {
      hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID*)&m_metahost);
      if (hr != S_OK) break;
      hr = m_metahost->GetRuntime(version.c_str(), IID_ICLRRuntimeInfo, (LPVOID*)&m_runtimeInfo);
      if (hr != S_OK) break;
      hr = m_runtimeInfo->GetInterface(CLSID_CLRProfiling, IID_ICLRProfiling, (LPVOID *)&m_clrProfiling);
      if (hr != S_OK) break;
      return S_OK;
   } while (false);

   // We end up here only if we have errors
   ReleaseAll();
   return hr;
}	

DWORD ProfilerStarter::GetProcessId()
{
   return m_processId;
}

BOOL ProfilerStarter::StartProcess(const WCHAR* exePath)
{
   return StartProcess(exePath, NULL);
}

BOOL ProfilerStarter::StartProcess(const WCHAR* exePath, std::list<std::wstring>& environmentVars)
{	
   std::wstring envString;
   WCHAR separator[] = L"\0";
   for(std::list<std::wstring>::iterator iter = environmentVars.begin();iter != environmentVars.end();iter++)
   {
      std::wstring envText = *iter;
      envString += envText + std::wstring(separator, 1);
   }
   envString += std::wstring(separator, 1);
   WCHAR* envPtrTemp = const_cast<WCHAR*>(envString.c_str());
   LPVOID envPtr = reinterpret_cast<LPVOID>(envPtrTemp);
   return this->StartProcess(exePath, envPtr);
}

BOOL ProfilerStarter::StartProcess(const WCHAR* exePath, LPVOID environmentVars)
{

   STARTUPINFO si;
   PROCESS_INFORMATION pi;
   ZeroMemory( &si, sizeof(si) );
   si.cb = sizeof(si);
   ZeroMemory( &pi, sizeof(pi) );
   BOOL created = ::CreateProcessW(NULL // Application Name
      , const_cast<LPWSTR>(exePath) // CommandLine
      , NULL // Process Attributes
      , NULL // Thread Attributes
      , FALSE // Inherit Handles
      , CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT // Creation Flags
      , environmentVars // Environment
      , NULL // Current Directory
      , &si // Startup info
      , &pi);

   if (!created)
      return FALSE;
   m_processId = pi.dwProcessId;
   return m_processId != 0;
}

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)


Written By
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.

Comments and Discussions