16th Jun 2009

Hello World in IL

I am always fascinated by the inside the hood views of things, how they work, how they all fit in together. Since I program in C# majority of the time, naturally I am interested in learning about how a program written in C# is converted to IL, how the IL code looks for a specific C# program and how the IL is converted to native code. The first step for all this would be to learn IL. I have made several attempts in the past to learn IL but I never made a good effort towards achieving that goal. Today I decided I would write a program IL, and I sure did write one. In keeping with the tradition it is a program that prints the string "Hello, World !" to the console. Here is the C# version:

using System;
 
namespace HelloWorldIL
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World !");
        }
    }
}

 

Here is the IL version.

.assembly extern mscorlib {}
.assembly HelloWorldIL {}
 
.namespace HelloWorldIL 
{
    .class Program 
    {
        .method static public void Main() cil managed 
        {
            .entrypoint
            .maxstack 8            
            ldstr "Hello, World !"
            call void [mscorlib] System.Console::WriteLine(string)
            ret    
        }
    }
}

I would like to claim that I wrote it without any help, but for the sake of honesty I should say that I peeked at the disassembled code using ILDASM. As you can see the disassembled code is a mess and not so easy to understand, I spent hours cleaning up the code and trying to understand what everything means and the result is helloworldil.il.

The elements that start with a ‘.’ are called directives.

The program starts with a .assembly extern directive. The .assembly extern is used to reference an external assembly. Since mscrolib.dll is the most important assembly for a .NET program, ILASM will automatically add an external reference to it, so from an IL coder’s perspective it is optional to add a .assembly extern directive for mscorlib.dll. The .assembly extern directive has the following syntax:

.assembly extern name  as alias { /* additional directives here */}

The aliasing is optional and is used in the situations where multiple assemblies have same name.

After the .assembly extern directive, we have a .assembly directive. The .assembly directive is used to specify metadata for the assembly which will be generated by ILASM. The .assembly directive has the following syntax:

.assembly name { /* additional directives here */}

For both .assembly and .assembly extern directives we can use additional directives to specify additional attributes for the assembly such as .publickey, .hash, .ver etc. For eg:

The .namespace directive creates a new namespace and the .class directive creates a new type.

Inside the .class directive we put other directives such as .method, .property, .field etc.

The .method directive specifies a method and the cil and managed attributes means that the method contains IL code and that the implementation is managed.

The .entrypoint directive marks the method as the starting point of the application. This means that in IL you can name your entry point method any legal name unlike in C# where it should always be named Main.

The .maxstack sets the size of the evaluation stack and the default value is 8 slots. It limits the number of items permitted simulataneously on the evaluation stack.

The ldstr command loads a string to the evaluation stack.

The call command calls a specified method whose parameters are on the evaluation stack.

The ret command is equivalent to return in C# and returns control to the caller.

I have used the following books to learn more about IL and I think it would be useful for anybody who wants to know more about the inner workings of IL and .NET.

One great tool for learning the underpinning of .NET is Reflector.

Posted by Posted by pc under Filed under General Comments No Comments »

13th Jun 2009

Hello World in IL

I am always fascinated by the inside the hood views of things, how they work, how they all fit in together. Since I program in C# majority of the time, naturally I am interested in learning about how a program written in C# is converted to IL, how the IL code looks for a specific C# program and how the IL is converted to native code. The first step for all this would be to learn IL. I have made several attempts in the past to learn IL but I never made a good effort towards achieving that goal. Today I decided I would write a program IL, and I sure did write one. In keeping with the tradition it is a program that prints the string “Hello, World !” to the console. Here is the C# version followed by the IL version.

Hello World in IL

I would like to claim that I wrote it without any help, but for the sake of honesty I should say that I peeked at the disassembled code using ILDASM. As you can see the disassembled code is a mess and not so easy to understand, I spent hours cleaning up the code and trying to understand what everything means and the result is helloworldil.il.

The elements that start with a ‘.’ are called directives.

The program starts with a .assembly extern directive. The .assembly extern is used to reference an external assembly. Since mscrolib.dll is the most important assembly for a .NET program, ILASM will automatically add an external reference to it, so from an IL coder’s perspective it is optional to add a .assembly extern directive for mscorlib.dll. The .assembly extern directive has the following syntax:

.assembly extern name  as alias { /* additional directives here */}

The aliasing is optional and is used in the situations where multiple assemblies have same name.

After the .assembly extern directive, we have a .assembly directive. The .assembly directive is used to specify metadata for the assembly which will be generated by ILASM. The .assembly directive has the following syntax:

.assembly name { /* additional directives here */}

For both .assembly and .assembly extern directives we can use additional directives to specify additional attributes for the assembly such as .publickey, .hash, .ver etc. For eg:

externdirective.JPG

The .namespace directive creates a new namespace and the .class directive creates a new type.

Inside the .class directive we put other directives such as .method, .property, .field etc.

The .method directive specifies a method and the cil and managed attributes means that the method contains IL code and that the implementation is managed.

The .entrypoint directive marks the method as the starting point of the application. This means that in IL you can name your entry point method any legal name unlike in C# where it should always be named Main.

The .maxstack sets the size of the evaluation stack and the default value is 8 slots. It limits the number of items permitted simulataneously on the evaluation stack.

The ldstr command loads a string to the evaluation stack.

The call command calls a specified method whose parameters are on the evaluation stack.

The ret command is equivalent to return in C# and returns control to the caller.

I have used the following books to learn more about IL and I think it would be useful for anybody who wants to know more about the inner workings of IL and .NET.

One great tool for learning the underpinning of .NET is Reflector.

Posted by Posted by pc under Filed under .NET, C#, Technical Comments No Comments »

11th Jun 2009

Obama, H1 and Search engines

A very significant traffic from search engines to my site is generated by the query “Obama + H1“. It is due to this post. On Bing and Google this query puts my blog as the #1 result but Yahoo doesn’t even show it on the first 5 pages (I didn’t look further). But for “Obama + H1B”, Yahoo manages to pull me into the third place.

While I am talking about search engines I might as well say that I am beginning to like Bing. The results are mostly spot-on (and getting better) and the daily images turns out to be a better idea than I thought it was. I knew a few people who made Bing their homepage just for the images. Well I know that the search page is not supposed to be the destination and should be as simple as possible but hey, if it manages to pull in people, then why not ? But I don’t know how the background image works out for low bandwidth users. For Google fans and power users I suggest trying Bing for 10 days without prejudice. I was not initially sold on the new branding but I made Bing my home page and you know what, I am liking it now.How it is going to turn out, we need to wait and see.

You might also want to do a blind search. And some old news in case you haven’t seen it yet, pretty impressive.

Posted by Posted by pc under Filed under H1B, Interesting, Internet Comments No Comments »

10th Jun 2009

Covariance in Arrays

The following code throws an ArrayTypeMismatchException.

Covariance in Arrays

I was never aware of this until today. Here is the reason for this behaviour.

On a related note, Generics catches this problem at compile time.

Click here to get code that you can copy-paste.

Posted by Posted by pc under Filed under C#, Technical Comments 1 Comment »

10th Jun 2009

Follow me on Twitter

Follow me on Twitter at http://twitter.com/cpradeep

Posted by Posted by pc under Filed under Internet, Personal Comments No Comments »

02nd Apr 2009

Evaluating Expressions in C#

What do you think would be printed on the Console when the TestEvaluationOrder method is executed ?

Evaluating Expressions in C#

What would be printed if we add parenthesis to the expression as follows:

evaluationorder2.jpg

Are you surprised by the results ?

Posted by Posted by pc under Filed under C#, Technical Comments No Comments »

15th Oct 2008

Algorithms in a Nutshell

Authors George Heineman, Gary Pollice and Stanley Selkow have written a very promising book - Algorithms in a Nutshell - published by O’Reilly. The authors are professors at Worcester Polytechnic Institute (WPI). The hardcopy will be available on October 21, 2008, but the book is already available on Safari.

The table of contents :

Part I: I
Chapter 1. Algorithms Matter
Section 1.1. Understand the Problem
Section 1.2. Experiment if Necessary
Section 1.3. Side Story
Section 1.4. The Moral of the Story
Section 1.5. References
Chapter 2. The Mathematics of Algorithms
Section 2.1. Size of a Problem Instance
Section 2.2. Rate of Growth of Functions
Section 2.3. Analysis in the Best, Average, and Worst Cases
Section 2.4. Performance Families
Section 2.5. Mix of Operations
Section 2.6. Benchmark Operations
Section 2.7. One Final Point
Section 2.8. References
Chapter 3. Patterns and Domains
Section 3.1. Patterns: A Communication Language
Section 3.2. Algorithm Pattern Format
Section 3.3. Pseudocode Pattern Format
Section 3.4. Design Format
Section 3.5. Empirical Evaluation Format
Section 3.6. Domains and Algorithms
Section 3.7. Floating-Point Computations
Section 3.8. Manual Memory Allocation
Section 3.9. Choosing a Programming Language
Section 3.10. References
Part II: II
Chapter 4. Sorting Algorithms
Section 4.1. Overview
Section 4.2. Insertion Sort
Section 4.3. Median Sort
Section 4.4. Quicksort
Section 4.5. Selection Sort
Section 4.6. Heap Sort
Section 4.7. Counting Sort
Section 4.8. Bucket Sort
Section 4.9. Criteria for Choosing a Sorting Algorithm
Section 4.10. References
Chapter 5. Searching
Section 5.1. Overview
Section 5.2. Sequential Search
Section 5.3. Binary Search
Section 5.4. Hash-based Search
Section 5.5. Binary Tree Search
Chapter 6. Graph Algorithms
Section 6.1. Overview
Section 6.2. Depth-First Search
Section 6.3. Breadth-First Search
Section 6.4. Single-Source Shortest Path
Section 6.5. All Pairs Shortest Path
Section 6.6. Minimum Spanning Tree Algorithms
Section 6.7. References
Chapter 7. Path Finding in AI
Section 7.1. Overview
Section 7.2. Depth-First Search
Section 7.3. Breadth-First Search
Section 7.4. A*Search
Section 7.5. Comparison
Section 7.6. Minimax
Section 7.7. NegMax
Section 7.8. AlphaBeta
Section 7.9. References
Chapter 8. Network Flow Algorithms
Section 8.1. Overview
Section 8.2. Maximum Flow
Section 8.3. Bipartite Matching
Section 8.4. Reflections on Augmenting Paths
Section 8.5. Minimum Cost Flow
Section 8.6. Transshipment
Section 8.7. Transportation
Section 8.8. Assignment
Section 8.9. Linear Programming
Section 8.10. References
Chapter 9. Computational Geometry
Section 9.1. Overview
Section 9.2. Convex Hull Scan
Section 9.3. LineSweep
Section 9.4. Nearest Neighbor Queries
Section 9.5. Range Queries
Section 9.6. References
Part III: III
Chapter 10. When All Else Fails
Section 10.1. Variations on a Theme
Section 10.2. Approximation Algorithms
Section 10.3. Offline Algorithms
Section 10.4. Parallel Algorithms
Section 10.5. Randomized Algorithms
Section 10.6. Algorithms That Can Be Wrong, but with Diminishing Probability
Section 10.7. References
Chapter 11. Epilogue
Section 11.1. Overview
Section 11.2. Principle: Know Your Data
Section 11.3. Principle: Decompose the Problem into Smaller Problems
Section 11.4. Principle: Choose the Right Data Structure
Section 11.5. Principle: Add Storage to Increase Performance
Section 11.6. Principle: If No Solution Is Evident, Construct a Search
Section 11.7. Principle: If No Solution Is Evident, Reduce Your Problem to Another Problem That Has a Solution
Section 11.8. Principle: Writing Algorithms Is Hard—Testing Algorithms Is Harder
Part IV: IV
Appendix A. Benchmarking
Section A.1. Statistical Foundation
Section A.2. Hardware
Section A.3. Reporting
Section A.4. Precision

Posted by Posted by pc under Filed under Books Comments No Comments »

15th Oct 2008

Apress books in Safari

Apress books used to be published online through Books 24×7, but now they are available in Safari as well. Apress has some nice books and I already have a Safari account, so this is great news for me.

Posted by Posted by pc under Filed under Books Comments No Comments »

10th Oct 2008

Diet update - Oct 10 2008

176.2 pounds as of today morning. I have found that the days on which I play or do exercise I lose approx. 2 pounds. On other days, the weight remains approximately the same.

Total loss till today is something between 12 and 14 pounds. I am so happy :)

Posted by Posted by pc under Filed under Diet, Health, Personal Comments 4 Comments »

06th Oct 2008

Diet update - Oct 06 2008

Today morning my weight was 182.4 pounds which comes to approximately 82.7 Kgs. This means that I lost something between 6 to 8 pounds in the first two days (i didnt measure my weight before starting the diet but I think it was something between 188 - 190 pounds which was the case when I last weighed myself). This rate of reduction is excellent from what I have read and it certainly gives me some motivation to continue the diet. The going is tough and the sugar craving is very high but I hope things will get better in the days to come.

Yesterday morning I had 2 eggs and a sausage for brunch. In the evening I had 2 chicken pieces and for dinner I fried some shrimp. I snacked on beef jerky in between meals as well. I drank 3 caffeine free diet cokes and ate a couple of packets of Splenda to satisfy my sugar craving.

I played badminton on saturday and volleyball on sunday so I am guessing that it helped in burning some fat.

I haven’t decided what my target weight should be. I don’t want to put too much pressure on myself. When the cravings get high, I console myself with the fact that I can quit any time that I want, but by having a target weight it would feel like a failure if I quit before that. I am just going to keep going as far as I can.

The hardest part would be keeping the weight off after I start eating carbohydrates again. I don’t have a plan sketched out for that, but most probably I would start exercising more.

Posted by Posted by pc under Filed under Diet, Health, Personal Comments 2 Comments »