SlideShare a Scribd company logo
1 of 12
Understanding CIL & Dynamic Assemblies Paul Fryer June 2011
Why learn CIL? Understand how various .net languages map to CIL tokens. Disassemble, edit CIL, and recompile. Build dynamic assemblies using System.Refelection.Emit. Leveraging CTS features that aren’t available in higher level languages (C# can’t define global level members for example).
Token Sets CIL Directives .namespace, .class, .method, .assembly CIL Attributes public, extends, implements CIL Operation Codes (opcodes) ldstr, box, unbox, throw, sizeof
Opcode/Mnemonic Distinction Mnemonic symbols (add, sub) are used rather than binary opcodes (0X85, 0X59). Decompilers like ildasm.exe map the opcodes to their mnemonic representations.
CIL is Stack Based When looking at CIL code you’ll notice things like stloc.0 – the zero represents index 0 on the stack.
Look at Compiled Assemblies Use ildsam.exe to disassemble assembly. <Microsoft SDKs>indows7.0Ain Commercial tools exist too: Reflector http://reflector.red-gate.com
Write IL Code with an IDE MonoDevelop http://monodevelop.com
Write “Hello World” 		.method public hidebysig static void Main(string[] args) cil managed 		{ 			.entrypoint 			.maxstack 1 ldstr "Hello World!" 			call void [mscorlib]System.Console::WriteLine(string) 			ret 		}
Stack Multiple Variables 		.method public hidebysig static void Main(string[] args) cil managed 		{ 			.entrypoint 			.maxstack 3 			.locals init ([0] string myStr, [1] int32 myInt, [2] object myObj) ldstr "CIL code is Fun!" 			stloc.0 			ldc.i4 33 			stloc.1 newobj instance void [mscorlib]System.Object::.ctor() 			stloc.2 			ret 		}
For Loop 		.method public hidebysig static void Main(string[] args) cil managed 		{ 			.entrypoint 			.maxstack 2 			.locals init ([0] int32 i) 			IL_0: ldc.i4.0 			IL_1: stloc.0 			IL_2: br.s IL_8 			IL_4: ldloc.0 			IL_5: ldc.i4.1 			IL_6: add 			IL_7: stloc.0 			IL_8: ldloc.0 			IL_9: ldc.i4.s 10 IL_b: blt.s IL_4 			ret 		}
Generate Dynamic Assemblies We’ll use the System.Reflection.Emitnamespace to output dynamic code into our current AppDomain.
public static void CreateMyAsm(AppDomaincurAppDomain)         {             // Build the assembly name. var name = new AssemblyName("MyAssembly") {Version = new Version("1.0.0.0")};             // Create a new assembly in the current app domain. var assembly = curAppDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save);             // Because this is a single file assembly, the module name is the same as assembly. var module = assembly.DefineDynamicModule("MyAssembly", "MyAssembly.dll");             // Define the public class named "HelloWorld". varhelloWorldClass = module.DefineType("MyAssembly.HelloWorld", TypeAttributes.Public);             // Define the string variable named "theMessage". varmsgField = helloWorldClass.DefineField("theMessage", Type.GetType("System.String"), FieldAttributes.Private);             // Create the custom constructor. varconstructorArgs = new[] {typeof (string)}; var constructor = helloWorldClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorArgs); varconstructorIL = constructor.GetILGenerator(); constructorIL.Emit(OpCodes.Ldarg_0); varobjectClass = typeof (object); varsuperConstructor = objectClass.GetConstructor(new Type[0]); constructorIL.Emit(OpCodes.Call, superConstructor); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Ldarg_1); constructorIL.Emit(OpCodes.Stfld, msgField); constructorIL.Emit(OpCodes.Ret);             // Create the default constructor. helloWorldClass.DefineDefaultConstructor(MethodAttributes.Public);             // create the GetMsg() method. vargetMsgMethod = helloWorldClass.DefineMethod("GetMsg", MethodAttributes.Public, typeof (string), null); varmethodIL = getMsgMethod.GetILGenerator(); methodIL.Emit(OpCodes.Ldarg_0); methodIL.Emit(OpCodes.Ldfld, msgField); methodIL.Emit(OpCodes.Ret);             // create the hellow world method varsayHiMethod = helloWorldClass.DefineMethod("SayHello", MethodAttributes.Public, null, null); methodIL = sayHiMethod.GetILGenerator(); methodIL.EmitWriteLine("Hello from the HelloWorld class!"); methodIL.Emit(OpCodes.Ret);             // Bake the HelloWorld class helloWorldClass.CreateType();             // (optionally) save assembly to file assembly.Save("MyAssembly.dll");         }

More Related Content

Similar to Understanding cil & dynamic assemblies

Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesDurgesh Singh
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaMatthias Noback
 
Example Cosmos SDK Application Tutorial
Example Cosmos SDK Application TutorialExample Cosmos SDK Application Tutorial
Example Cosmos SDK Application TutorialJim Yang
 
Secrets of .NET Assemblies and Memory Management
Secrets of .NET Assemblies and Memory ManagementSecrets of .NET Assemblies and Memory Management
Secrets of .NET Assemblies and Memory ManagementAbhishek Sur
 
Rules SDK IBM WW BPM Forum March 2013
Rules SDK IBM WW BPM Forum March 2013Rules SDK IBM WW BPM Forum March 2013
Rules SDK IBM WW BPM Forum March 2013Dan Selman
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumMatthias Noback
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - TryoutMatthias Noback
 
Creating A Language Editor Using Dltk
Creating A Language Editor Using DltkCreating A Language Editor Using Dltk
Creating A Language Editor Using DltkKaniska Mandal
 
WPF and Prism 4.1 Workshop at BASTA Austria
WPF and Prism 4.1 Workshop at BASTA AustriaWPF and Prism 4.1 Workshop at BASTA Austria
WPF and Prism 4.1 Workshop at BASTA AustriaRainer Stropek
 
Dotnet framework difference faqs- 3
Dotnet framework difference faqs- 3Dotnet framework difference faqs- 3
Dotnet framework difference faqs- 3Umar Ali
 

Similar to Understanding cil & dynamic assemblies (20)

C# Unit 1 notes
C# Unit 1 notesC# Unit 1 notes
C# Unit 1 notes
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
 
IOC + Javascript
IOC + JavascriptIOC + Javascript
IOC + Javascript
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
Assemblies in asp
Assemblies in aspAssemblies in asp
Assemblies in asp
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony Barcelona
 
Example Cosmos SDK Application Tutorial
Example Cosmos SDK Application TutorialExample Cosmos SDK Application Tutorial
Example Cosmos SDK Application Tutorial
 
Secrets of .NET Assemblies and Memory Management
Secrets of .NET Assemblies and Memory ManagementSecrets of .NET Assemblies and Memory Management
Secrets of .NET Assemblies and Memory Management
 
Rules SDK IBM WW BPM Forum March 2013
Rules SDK IBM WW BPM Forum March 2013Rules SDK IBM WW BPM Forum March 2013
Rules SDK IBM WW BPM Forum March 2013
 
201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup Belgium
 
C#ppt
C#pptC#ppt
C#ppt
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - Tryout
 
Dotnet basics
Dotnet basicsDotnet basics
Dotnet basics
 
Creating A Language Editor Using Dltk
Creating A Language Editor Using DltkCreating A Language Editor Using Dltk
Creating A Language Editor Using Dltk
 
WPF and Prism 4.1 Workshop at BASTA Austria
WPF and Prism 4.1 Workshop at BASTA AustriaWPF and Prism 4.1 Workshop at BASTA Austria
WPF and Prism 4.1 Workshop at BASTA Austria
 
Dotnet framework difference faqs- 3
Dotnet framework difference faqs- 3Dotnet framework difference faqs- 3
Dotnet framework difference faqs- 3
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
C# tutorial
C# tutorialC# tutorial
C# tutorial
 
Module 2: Overview of c#
Module 2:  Overview of c#Module 2:  Overview of c#
Module 2: Overview of c#
 

Understanding cil & dynamic assemblies

  • 1. Understanding CIL & Dynamic Assemblies Paul Fryer June 2011
  • 2. Why learn CIL? Understand how various .net languages map to CIL tokens. Disassemble, edit CIL, and recompile. Build dynamic assemblies using System.Refelection.Emit. Leveraging CTS features that aren’t available in higher level languages (C# can’t define global level members for example).
  • 3. Token Sets CIL Directives .namespace, .class, .method, .assembly CIL Attributes public, extends, implements CIL Operation Codes (opcodes) ldstr, box, unbox, throw, sizeof
  • 4. Opcode/Mnemonic Distinction Mnemonic symbols (add, sub) are used rather than binary opcodes (0X85, 0X59). Decompilers like ildasm.exe map the opcodes to their mnemonic representations.
  • 5. CIL is Stack Based When looking at CIL code you’ll notice things like stloc.0 – the zero represents index 0 on the stack.
  • 6. Look at Compiled Assemblies Use ildsam.exe to disassemble assembly. <Microsoft SDKs>indows7.0Ain Commercial tools exist too: Reflector http://reflector.red-gate.com
  • 7. Write IL Code with an IDE MonoDevelop http://monodevelop.com
  • 8. Write “Hello World” .method public hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 1 ldstr "Hello World!" call void [mscorlib]System.Console::WriteLine(string) ret }
  • 9. Stack Multiple Variables .method public hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 3 .locals init ([0] string myStr, [1] int32 myInt, [2] object myObj) ldstr "CIL code is Fun!" stloc.0 ldc.i4 33 stloc.1 newobj instance void [mscorlib]System.Object::.ctor() stloc.2 ret }
  • 10. For Loop .method public hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 2 .locals init ([0] int32 i) IL_0: ldc.i4.0 IL_1: stloc.0 IL_2: br.s IL_8 IL_4: ldloc.0 IL_5: ldc.i4.1 IL_6: add IL_7: stloc.0 IL_8: ldloc.0 IL_9: ldc.i4.s 10 IL_b: blt.s IL_4 ret }
  • 11. Generate Dynamic Assemblies We’ll use the System.Reflection.Emitnamespace to output dynamic code into our current AppDomain.
  • 12. public static void CreateMyAsm(AppDomaincurAppDomain) { // Build the assembly name. var name = new AssemblyName("MyAssembly") {Version = new Version("1.0.0.0")}; // Create a new assembly in the current app domain. var assembly = curAppDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save); // Because this is a single file assembly, the module name is the same as assembly. var module = assembly.DefineDynamicModule("MyAssembly", "MyAssembly.dll"); // Define the public class named "HelloWorld". varhelloWorldClass = module.DefineType("MyAssembly.HelloWorld", TypeAttributes.Public); // Define the string variable named "theMessage". varmsgField = helloWorldClass.DefineField("theMessage", Type.GetType("System.String"), FieldAttributes.Private); // Create the custom constructor. varconstructorArgs = new[] {typeof (string)}; var constructor = helloWorldClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorArgs); varconstructorIL = constructor.GetILGenerator(); constructorIL.Emit(OpCodes.Ldarg_0); varobjectClass = typeof (object); varsuperConstructor = objectClass.GetConstructor(new Type[0]); constructorIL.Emit(OpCodes.Call, superConstructor); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Ldarg_1); constructorIL.Emit(OpCodes.Stfld, msgField); constructorIL.Emit(OpCodes.Ret); // Create the default constructor. helloWorldClass.DefineDefaultConstructor(MethodAttributes.Public); // create the GetMsg() method. vargetMsgMethod = helloWorldClass.DefineMethod("GetMsg", MethodAttributes.Public, typeof (string), null); varmethodIL = getMsgMethod.GetILGenerator(); methodIL.Emit(OpCodes.Ldarg_0); methodIL.Emit(OpCodes.Ldfld, msgField); methodIL.Emit(OpCodes.Ret); // create the hellow world method varsayHiMethod = helloWorldClass.DefineMethod("SayHello", MethodAttributes.Public, null, null); methodIL = sayHiMethod.GetILGenerator(); methodIL.EmitWriteLine("Hello from the HelloWorld class!"); methodIL.Emit(OpCodes.Ret); // Bake the HelloWorld class helloWorldClass.CreateType(); // (optionally) save assembly to file assembly.Save("MyAssembly.dll"); }