Click here to Skip to main content
15,879,326 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 61.9K   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.
// ----------------------------------------------------------------------------------------------

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace ILEmitTest
{
    class Program
    {
        public MethodBuilder BuildMethodStartTime(TypeBuilder type)
        {
            // Declaring method builder
            // Method attributes
            System.Reflection.MethodAttributes methodAttributes =
                System.Reflection.MethodAttributes.Public
                | System.Reflection.MethodAttributes.HideBySig
                | System.Reflection.MethodAttributes.Static;
            MethodBuilder method = type.DefineMethod("StartTime", methodAttributes);
            // Preparing Reflection instances
            ConstructorInfo ctor1 = typeof (DateTime).GetConstructor(
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                null,
                new Type[]
                    {
                        typeof (Int32),
                        typeof (Int32),
                        typeof (Int32),
                        typeof (Int32),
                        typeof (Int32),
                        typeof (Int32)
                    },
                null
                );
            // Setting return type
            method.SetReturnType(typeof (DateTime));
            // Adding parameters
            ILGenerator gen = method.GetILGenerator();
            // Preparing locals
            LocalBuilder cs = gen.DeclareLocal(typeof (DateTime));
            // Preparing labels
            Label label22 = gen.DefineLabel();
            // Writing body
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ldc_I4, 2000);
            gen.Emit(OpCodes.Ldc_I4_7);
            gen.Emit(OpCodes.Ldc_I4_S, 23);
            gen.Emit(OpCodes.Ldc_I4_S, 15);
            gen.Emit(OpCodes.Ldc_I4_S, 15);
            gen.Emit(OpCodes.Ldc_I4_0);
            gen.Emit(OpCodes.Newobj, ctor1);
            gen.Emit(OpCodes.Stloc_0);
            gen.Emit(OpCodes.Br_S, label22);
            gen.MarkLabel(label22);
            gen.Emit(OpCodes.Ldloc_0);
            gen.Emit(OpCodes.Ret);
            // finished
            return method;
        }






        static void Main(string[] args)
        {
            Program prg = new Program();
            AppDomain currentDomain = AppDomain.CurrentDomain;
            AssemblyName assemName = new AssemblyName();
            assemName.Name = "MyAssembly";

            AssemblyBuilder assemBuilder = currentDomain.DefineDynamicAssembly(assemName, AssemblyBuilderAccess.Run);

            ModuleBuilder moduleBuilder = assemBuilder.DefineDynamicModule("MyModule");

            TypeBuilder typeBuilder = moduleBuilder.DefineType("MyClass", TypeAttributes.Public);
            var methodBuilder = prg.BuildMethodStartTime(typeBuilder);


            Program.CallDynamicMethod(typeBuilder);
            Program.CallStaticMethod(typeBuilder);

            assemBuilder.Save("mymodule.dll");
            System.Console.ReadLine();
        }

        private static void CallStaticMethod(TypeBuilder typeBuilder)
        {
            Type t = typeBuilder.CreateType();
            MethodInfo helloWorld = t.GetMethod("StartTime");
            if (helloWorld != null)
            {
                DateTime dt = (DateTime) helloWorld.Invoke(null, null);
                System.Console.WriteLine("Time is: " + dt.ToShortTimeString());
            }
        }

        private static void CallDynamicMethod(TypeBuilder typeBuilder)
        {
            Type t = typeBuilder.CreateType();
            if (t != null)
            {
                object o = Activator.CreateInstance(t);
                MethodInfo helloWorld = t.GetMethod("StartTime");
                if (helloWorld != null)
                {
                    DateTime dt = (DateTime) helloWorld.Invoke(o, null);
                    System.Console.WriteLine("Time is: " + dt.ToShortTimeString());
                }
            }
        }
    }
}

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