Sunday, January 27, 2008

IL Generator

From past few months I am constantly trying to increase my knowledge about IL i.e. intermediate language generated when we compile our code thought any .net runtime compliant compiler. There are few classes in mscorlib.dll under System.Reflection.Emit namespace that are used by these compilers to generate IL suitable for our code files. I'll try to give you some brief introduction about IL working and i'll use .Net Reflector and ILDasm.exe for demonstration.

Just to get you started let me tell you soemthing about these tools:

  1. .NET Reflector - This is a tool which allows you to browse thought constituents of your assemblies. You can reverse engineer all the classes that are part of your assembly in any .net compliant language like C# or VB.NET
  2. ILDasm - Let's you dis assemble your IL code. You can check out complete IL code with all opcodes. Apart from this IlDasm also let's you check assemblies manifest for metadata

Let us start with some IL generation:

  • Class ILGenerator
    [assembly : mscorlib.dll] [namespace: System.Reflection.Emit]
    This class generates Microsoft IL instruction. It contains a large number of methods that are used to emit appropriate IL instructions.
    There are methods to emit calli instructions, methods for exception handling stuff etc. Large portion of this class s occupied by Emit method overloads. There more than 10 overloads available for emit method.



Emit method takes a OpCode structure object. There is another class in System.Reflection.Emit namespace known as OpCodes. This has all the opcodes that you find in you IL. Almost all of these OpCodes are declared as readonly variables and initialized with some specific values.
This is OpCode structure and as you can see it has variables mostly of some enum type. Like StackBehaviour is an enum. OpCodes class is given below. Just look at the constuctor used for initializing readonly fields. After combining all these things together an IL instruction is pushed to a MSIL stream of instruction.















There is a method InternalEmit which almost all Emit methods in ILGenerator class calls. Let us look at this method: if opcode.m_size == 1 This checks weather opcode size is 1 bytes or 2 bytes long. If opCodesize is 1 then opCode byte is added to MSIL Stream byte array and its length is incremented by 1. But if we have 2 byte opcode then both bytes are added to MSIL byte stream array and its length is increased by 2 i.e. one after each addition. At last InternalEmit calls UpdateStackSize method which I'll leave for readers exploration.

Knowing about IL and metadata has helped me a lot in solving issues related to performance. I recommend knowing few things about IL to all .net developers.

References

  1. OpCodes : http://msdn2.microsoft.com/en-us/library/system.reflection.emit.opcodes_members.aspx
  2. ILGenerator : http://msdn2.microsoft.com/en-us/library/system.reflection.emit.ilgenerator.aspx

EnJoy Coding
Currently listening to: Who I am- Eminem

Sunday, January 13, 2008

My Hibernation is over

Friends! you must be wondering why I was not adding any new posts. Actually December was a bit hectic in many ways. I was going into a transition from being a senior developer to a team lead. Another reason was my desktop computer that started behaving in a scary manner.

Leaving all that behind I want to tell you a special thing. I got a new laptop. Cheers! This statement of mine is over simplified but yes i bought a new laptop from US while I was sitting here in India.
My laptop purchase story goes like this, in mid November a friend of mine told me that one of his friend is coming to India from US in mid December. That was a good news for me as from past few months I was planning to purchase a new laptop. In India these machines costs over 50,000 Rs. and if you plan to do Microsoft applications then you should be ready to shell out around 1,00,000 Rs. After this I started searching for a good deal on web. some of the sites that I dogged were BestBuy.com, ZipZoomFly.com, CircuitCity.com and list goes on. But one thing that I noticed was either these sites were having below par factory models or they were costly. Processor were always 1.6 or 1.8 GHz Core 2 and if you want 2 GB ram then price shoots up.

After few weeks I decided upon Toshiba Qosmio 15.4" version. This is a great machine and I configured it on Toshiba's shopping portal. But to my surprise Toshiba only accepted credit cards issued by US banks. Toshiba suggested me to use over the wire money transfer feature but I wasn't sure about its security and authenticity. So I decided to switch over to HP. HP was having some good offers running. I configured a 17" HP DV9500T machine and got around 450$ discount. Cool!

Machine specs are as follows:
  1. Intel Core 2 Duo 2.2 GHz [Santa Rosa platform]
  2. 2 GB DDR2 RAM
  3. 240 GB 7200 RPM HDD [120Gb dual hard disks]
  4. NVIDIA GS8600M GPU 256 mb DDR3 Dedicated vedio memory
  5. 17" Ultra bright screen [Best in market]
  6. Finger print reader
  7. DVD writer with Label Flash
  8. ALTEC LANCING speakers
  9. HDMI port
  10. WebCam 1.3 MP

Amazing power and great looks. Check out the picture





.














I have started on learning XAML and WPF. I'll start posting topics related to WPF from next week. Apart from this I plan to continue on my C# 3.0 feature listing. I hope! having a laptop will surely help. Wait n watch. I have also installed Call of Duty 2 and its going good. I plan to play at least half n hour daily. You know games are my passion and I can not let my passion die. Check out this screen shot,

Currently listening to: Akon- Blame it on me
~nJoY CoDiNg~

Tuesday, December 4, 2007

Crazy Enums

Few days back I got a great opportunity to talk with a senior thoughtworker, Chris. He told me few things related to Agile and NUnit. Apart from this there was one intresting thing that I want to share. Almost all of us have worked with .Net Enums. Let me show you something,
Create a project and add one Enum to it,

enum MyEnum
{
Orange=0,
Red=1,
Green=2
}


Now create another class where we will use this Enum,

class Program
{
static void Main(string[] args)
{
MyEnum obj;
obj = (MyEnum)5;
Console.WriteLine(obj.ToString());
Console.ReadLine();
}
}


Did you noticed something? Our Enum only had 0,1 and 2 as valid values. I went on and assigned 5 to it. Now try compiling this code. Aha! no compilation errors. Now try running this. Everything goes well and 5 gets printed on console. Did you expected this?
I never expected this. Did Microsoft forget about type safety and type checking issues while copying from Java Enums? I think Java enums works fine.
If you ever worked with Bit Flags you will some how realize that all this is due to them. Bit flags can actually take up values which are a combination of values that are defined in Bit Flag Enum. Here is an example:

[Flags]
internal enum Actions
{
None = 0,
Read = 0X0001,
Write = 0X0002,
ReadWrite = Actions.Read Actions.Write
...
}

There are number of threads going on in forums related to this. Just keep this in mind before using Enums.
I am exited about playing EA Game's CRYSIS. I have the DVD and will be installing the game tomorrow. Actually I need to clean up my system a bit before I get on with the game. CRYSIS CD says, "Game needs 20 Gb of free hard drive space."

Currently listening to: Black or White - MJ
~nJoY CoDiNg~

Monday, November 19, 2007

Amazing Graphics..EA Rocks!!!

Check these screenshots of Need for speed Most wanted...amazing graphics...EA Games rocks..









Saturday, November 10, 2007

C# 3.0 - What's new?

Hello! everyone. This is festive time here in India. Yesterday we all celebrated Diwali, festival of light. I must tell you that lot of things have changed, things like playing with crackers, going out with friends and watching the way people decorated their houses using lights and ribbons. Yesterday, after having our Diwali prayer I just watched a movie (CHUCK) @ home and slept at around 11. Nothing new for me and it turned out to be yet another holiday. I wish things remained the same way as they were before.

Now let's talk technology. Microsoft have another a new set of features to C# in its third avatar. There is complete list available at MSDN, but I just wanted to add my comments to it as I study new features one by one. What I am planning is, I'll study one new feature everyday, post it here with my comments.
  1. Implicitly Typed Local Variables
    • Type is inferred by the expression used to initialize the variable
    • Only applicable to local variable
    • Variable declared using keyword 'var'
    • There should be no Type with name 'var' defined in scope. Only then type inferring will work
    • We should initialize the variable where we declaring it
    • Initialized must be an expression.
    • Local variable declaration should not include multiple variables
    • Initializer should not refer to variable itself
    • Some Examples: [ <=> is Same as ]
      var i = 5; <=> int i = 5;
      var s = "Hello";
      <=> string s = "Hello";
      var d = 1.0;
      <=> double d = 1.0;
      var numbers = new int[] {1, 2, 3};
      <=> int[] number = new int[]{1,2,3};
    • Some incorrect use of var:
      var x; // Error, no initializer to infer type from
      var y = {1, 2, 3}; // Error, collection initializer not permitted
      var z = null; // Error, null type not permitted
      var u = x => x + 1; // Error, lambda expressions do not have a type
      var v = v++; // Error, initializer cannot refer to variable itself
    • for, foreach and using (resource acquisition) can also use var. Like,
      int[] numbers = { 1, 2, 3, 4, 5 };
      foreach (var n in numbers) { //Do some thing }
    • COMMENTS
      Why do we need to use var? Everything should be Type Strict. I think this will impact performance as compiler will use some kind of intelligence to find out variable type and it will surely take up some time. This is no scripting language...man this is C#. It will just complicate things even more and add to huge list of keywords that we already have like sealed, virtual, override, abstract, new, internal etc. I don't see any use of this so called added feature.
      Please let me know your opinions.
Currently Listening To: Shadow of the day-LINKIN PARK
~eNjOy cOdinG~