Mono Cecil – przykład użycia

W poprzednim poście wspomniałem o mojej walce w Mono Cecil, dzisiaj chciałbym się podzielić moimi wrażeniami i doświadczeniem. Dodam tylko, że o Mono usłyszałem na spotkaniach wrocławskiej grupy .net, wykład prowadził Paweł Łukasik, slajdy z wykładu dostępne są na jego blogu: http://pawlos.blogspot.com. Jak zwykle zapraszam na spotkania i wykłady.

Źródła które pokaże, są tylko prostym przykładem, zamysłem tego co chciałem zrobić w docelowym rozwiązaniu. Powinny jednak wystarczyć by ukazać jak działa Mono Cecil.
Sztuczka miała polegać na dodaniu funkcjonalności do istniejącej już aplikacji; jestem leniwy i nie chce klikać myszą w guziczki góra, dół, prawo i lewo, chciałbym mieć możliwość nawigowania za pomocą strzałek na klawiaturze. Rozwiązania są dwa, można napisać taką implementacji od zera w IL i doklejeniu jej do docelowej aplikacji. Druga możliwość, to skopiowanie gotowej implementacji z innej aplikacji. Wszyscy jesteśmy leniwi, tak więc rozwiązanie drugie było bardziej kuszące.
Cały projekt jest dostępy na git hubie dostępy dla każdego.

Zabrałem się więc do roboty i oto do czego doszedłem:
Kod wykonujący brudną robotę:

  1. using System.Linq;
  2.  
  3. namespace mcWorker
  4. {
  5.     using Mono.Cecil;
  6.     using Mono.Cecil.Cil;
  7.  
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             string sourceExe = @”contentSourceForm.exe”;
  13.             string targetExe = @”contentTargetForm.exe”;
  14.  
  15.             string srcMethod1 = “Form1_KeyDown”;
  16.             string srcMethod2 = “Form1_KeyUp”;
  17.  
  18.             // Source of code
  19.             AssemblyDefinition adSrc = AssemblyDefinition.ReadAssembly(sourceExe);
  20.             TypeDefinition typeSrc = adSrc.MainModule.Types
  21.                 .Where(t => t.Name == “SourceForm”).First();
  22.  
  23.  
  24.             // Place where code will be added
  25.             AssemblyDefinition adDst = AssemblyDefinition.ReadAssembly(targetExe);
  26.             TypeDefinition typeDst = adDst.MainModule.Types
  27.                 .Where(t => t.Name == “TargetForm”).First();
  28.  
  29.             // Copy both methods from src to dst
  30.             MethodDefinition m1 = CopyMethod(adSrc, typeSrc, srcMethod1, adDst, typeDst);
  31.             MethodDefinition m2 = CopyMethod(adSrc, typeSrc, srcMethod2, adDst, typeDst);
  32.  
  33.             // Now they should be marked as event handlers
  34.             AddEventHandlers(adDst, typeDst, “KeyDown”, m1);
  35.             AddEventHandlers(adDst, typeDst, “KeyUp”, m2);
  36.  
  37.             adDst.Write(@”newTarget.exe”);
  38.  
  39.         }
  40.  
  41.         private static void AddEventHandlers(AssemblyDefinition adDestination,
  42.                                             TypeDefinition typeDestination,
  43.                                             string aEventName,
  44.                                             MethodDefinition aEventHandler)
  45.         {
  46.             // For the simpliciyty of code the event handler will be connected
  47.             // to the events in default constructors
  48.             // Just before leaving it
  49.  
  50.             // I know that there is just one constructor, but this is only an example!
  51.             var ctor = typeDestination.Methods.Where(m => m.IsConstructor).First();
  52.  
  53.             // Find last return code
  54.             // We will put our code just before that opcode
  55.             var lastRet = ctor.Body.Instructions.Reverse()
  56.                 .Where(i => i.OpCode == OpCodes.Ret).First();
  57.  
  58.             // Now we need an IL generator
  59.             var ilg = ctor.Body.GetILProcessor();
  60.  
  61.             // and now the magic
  62.             ilg.InsertBefore(lastRet, Instruction.Create(OpCodes.Ldarg_0));
  63.             ilg.InsertBefore(lastRet, Instruction.Create(OpCodes.Ldarg_0));
  64.             ilg.InsertBefore(lastRet, Instruction.Create(OpCodes.Ldftn, aEventHandler));
  65.  
  66.             // I did check here also that there is only one construcor
  67.             ilg.InsertBefore(
  68.                 lastRet,
  69.                 Instruction.Create(
  70.                     OpCodes.Newobj,
  71.                     adDestination.MainModule
  72.                     .Import(typeof(System.Windows.Forms.KeyEventHandler)
  73.                     .GetConstructors().First())));
  74.  
  75.             ilg.InsertBefore(
  76.                 lastRet,
  77.                 Instruction.Create(
  78.                     OpCodes.Callvirt,
  79.                     adDestination.MainModule
  80.                     .Import(typeof(System.Windows.Forms.Control)
  81.                     .GetEvent(aEventName).GetAddMethod())));
  82.         }
  83.  
  84.         private static MethodDefinition CopyMethod(AssemblyDefinition adSource,
  85.                                                     TypeDefinition typeSource,
  86.                                                     string mthdName,
  87.                                                     AssemblyDefinition adDestination,
  88.                                                     TypeDefinition typeDestination)
  89.         {
  90.             // source
  91.             MethodDefinition srcMethod = typeSource.Methods
  92.                 .Where(m => m.Name == mthdName).First();
  93.  
  94.             // now create a new place holder for copy
  95.             MethodDefinition target = new MethodDefinition(srcMethod.Name,
  96.                                                         srcMethod.Attributes,
  97.                                                         adDestination.MainModule
  98.                                                         .Import(srcMethod.ReturnType));
  99.  
  100.             // Copy all method parameters
  101.             // I could use var, but I did this on purpose to show the type used.
  102.             foreach (ParameterDefinition pd in srcMethod.Parameters)
  103.             {
  104.                 target.Parameters.Add(
  105.                     new ParameterDefinition(pd.Name, pd.Attributes, adDestination.MainModule
  106.                         .Import(pd.ParameterType)));
  107.             }
  108.  
  109.             // Now copy all local variables that are defined withing method body
  110.             // I could use var, but I did this on purpose to show the type used.
  111.             foreach (VariableDefinition vd in srcMethod.Body.Variables)
  112.             {
  113.                 target.Body.Variables
  114.                     .Add(new VariableDefinition(adDestination.MainModule
  115.                         .Import(vd.VariableType)));
  116.             }
  117.  
  118.             // copy the state
  119.             target.Body.InitLocals = srcMethod.Body.InitLocals;
  120.  
  121.             /* copy all instructions from SRC to DST */
  122.             foreach (Instruction instruction in srcMethod.Body.Instructions)
  123.             {
  124.                 // Case when method call another method defined withing SRC type/assembly
  125.                 MethodReference mr = instruction.Operand as MethodReference;
  126.                 // Case when method load field from type/assembly
  127.                 FieldReference fr = instruction.Operand as FieldReference;
  128.                 TypeReference tr = instruction.Operand as TypeReference;
  129.                 if (mr != null)
  130.                 {
  131.                     if (mr.DeclaringType == typeSource)
  132.                     {
  133.                         // That would mean that here we have a
  134.                         // method call to method within source type
  135.                         // And this need to be redirected to source type
  136.                         // or handled in some other way
  137.                         // But in this example is not used
  138.                         // If you want some examples please contace me
  139.                     }
  140.                     else
  141.                     {
  142.                         target.Body.Instructions.Add(
  143.                             Instruction.Create(instruction.OpCode,
  144.                             adDestination.MainModule.Import(mr)));
  145.                     }
  146.                 }
  147.                 else
  148.                 {
  149.                     if (fr != null)
  150.                     {
  151.                         // So we migth found our selfs in position that we need
  152.                         // to redirect this load to some other field or remove it.
  153.                         // For now lets redirect for different field
  154.                         // Please try to remove the code between TRY ME
  155.                         // and check what peverify.exe will tell
  156.                         /*TRY ME*/
  157.                         if (fr.Name == “sourceStatus”)
  158.                         {
  159.                             target.Body.Instructions.Add(
  160.                                 Instruction.Create(
  161.                                     instruction.OpCode,
  162.                                     adDestination.MainModule.Import(typeDestination.Fields
  163.                                     .Where(f => f.Name == “targetStatus”).First())));
  164.                         }
  165.                         else/*TRY ME*/
  166.                         {
  167.                             target.Body.Instructions.Add(Instruction
  168.                                 .Create(instruction.OpCode, adDestination.MainModule.Import(fr)));
  169.                         }
  170.  
  171.                     }
  172.                     else if (tr != null)
  173.                     {
  174.                         target.Body.Instructions.Add(Instruction
  175.                             .Create(instruction.OpCode, adDestination.MainModule.Import(tr)));
  176.                     }
  177.                     else
  178.                     {
  179.                         target.Body.Instructions.Add(instruction);
  180.                     }
  181.                 } // else
  182.             } // foreach
  183.  
  184.             typeDestination.Methods.Add(target);
  185.             return target;
  186.         }
  187.     }
  188. }

Źródło z którego chce wziąć kod (zależy mi na obsłudze klawiszy).

  1. using System.Windows.Forms;
  2.  
  3. namespace SourceForm
  4. {
  5.     public partial class SourceForm : Form
  6.     {
  7.         public SourceForm()
  8.         {
  9.             InitializeComponent();
  10.         }
  11.  
  12.         private void Form1_KeyDown(object sender, KeyEventArgs e)
  13.         {
  14.             if (e.KeyCode == Keys.Escape)
  15.             {
  16.                 this.sourceStatus.Text = string.Format(“I did forget to mention that {0} ends the game.”, e.KeyCode.ToString());
  17.             }
  18.             else
  19.             {
  20.                 this.sourceStatus.Text = string.Format(“Key {0} (down).”, e.KeyCode.ToString());
  21.             }
  22.  
  23.         }
  24.  
  25.         private void Form1_KeyUp(object sender, KeyEventArgs e)
  26.         {
  27.             if (e.KeyCode == Keys.Escape)
  28.             {
  29.                 this.Close();
  30.             }
  31.             else
  32.             {
  33.                 this.sourceStatus.Text = string.Format(“Key {0} (up).”, e.KeyCode.ToString());
  34.             }
  35.         }
  36.  
  37.         private void Form1_MouseDown(object sender, MouseEventArgs e)
  38.         {
  39.             this.sourceStatus.Text = string.Format(“Mouse: {0} down”, e.Button.ToString());
  40.         }
  41.  
  42.         private void Form1_MouseUp(object sender, MouseEventArgs e)
  43.         {
  44.             this.sourceStatus.Text = string.Format(“Mouse: {0} up”, e.Button.ToString());
  45.         }
  46.     }
  47. }

Tak wygląda implementacja, którą chce rozszerzyć:

  1. using System.Windows.Forms;
  2.  
  3. namespace TargetForm
  4. {
  5.     public partial class TargetForm : Form
  6.     {
  7.         public TargetForm()
  8.         {
  9.             InitializeComponent();
  10.         }
  11.  
  12.         private void TargetForm_MouseDown(object sender, MouseEventArgs e)
  13.         {
  14.             this.targetStatus.Text = string.Format(“down: {0}”, e.Button.ToString());
  15.         }
  16.  
  17.         private void TargetForm_MouseUp(object sender, MouseEventArgs e)
  18.         {
  19.             this.targetStatus.Text = string.Format(“up: {0}”, e.Button.ToString());
  20.         }
  21.     }
  22. }

Komentarze w kodzie 🙂 Mam nadzieję że są w miarę zrozumiałe, jeżeli będzie coś niejasnego, zawsze służę pomocą.
Co ciekawe, warto spojrzeć (w źródła), że pola sourceStatus oraz targetStatus nie są tego samego typu, ale oba posiadają te same pola (Text) i oba dziedziczą po Control, dzięki temu pięknie zadziałał polimorfizm.

Oczywiste oczywistości:

  • Kod który podłącza event handlery do eventów nie wymyśliłem sam, z pomocą przyszedł reflektor. Zobaczyłem (czytaj skopiowałem) kod do obsługi myszy i wstawiłem analogiczny do obsługi klawiatury
  • Za pierwszym razem też wydawało mi się to strasznie zakręcone i okrutnie trudne, ale po trzecim podejściu do problemu, wszystko nabiera sensu. W sumie nawet fajnie się przegląda IL 😉 żarcik taki.
  • Nie wszystko się od razu udaje, przykład z TRY ME, za pierwszym razem (w trzecim podejściu) zapomniałem o tym i coś nie zadziałało. Na szczęście narzędzie peverify.exe potrafi o tym przypomnieć. Także możliwość debugowania dużo ułatwia, gdy można podejrzeć dokładnie wartości zmiennych i w razie potrzeby dla testów zmieniać jest w trakcie działania programu.
  • Google – szukajcie rozwiązań, jest spora szansa, że ktoś już miał problem podobny do waszego i został on rozwiązany. Jeżeli nie, to być może naprowadzi was na rozwiązanie waszego problemu. Nie warto odpuszczać, bo na pewno jakoś się da 🙂

Pokazany przykład jest prostym rozwiązaniem, a kod który przenosi funkcjonalność z aplikacji do aplikacji nie jest najbardziej rozbudowany i przemyślany. W przypadku, gdy pojawiają się dodatkowe wywołania metod w źródłowym assembly, zaczyna komplikować wszystko, trzeba sprawdzać nazwy metod, przypisywać referencję na docelowe assembly, pilnować typów, etc. Trzeba się bardziej nagimnastykować. Tutaj akurat nie chciałem się na tym skupiać.
Jeżeli coś nie działa sprawdzajcie reflektorem czy innym programem do podglądania kodu, czy nie zapomnieliście za importować gdzieś typu, lub czy wywołania się zgadzają. Czy wszystkie zmienne zostały za deklarowane w ciele (body) metody. Jeszcze raz przypominam o narzędziu peverify, które wskazuje co i gdzie jest nie tak.

Powodzenia i niech moc będzie z wami.
Jarek

//EDIT
Klient nasz pannn. Poprawiłem główny kod, teraz powinno być łatwiej go czytać. Ale nie chciało mi się tego robić dla form. Tam zresztą nie ma wiele ciekawego do oglądania.

2 thoughts on “Mono Cecil – przykład użycia

  1. A dałoby się połamać linie w kodzie? tak aby nie trzeba było używać scroll'a poziomego ? 🙂
    Troszku wygodniej by się analizowało kod, oczywiście ja nie narzekam 😉

Leave a Reply to Paweł NiewolnyCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.