Msil-the language of the CLR (Part 2)

Source: Internet
Author: User
Tags mscorlib
Introduction

In this Part I will briefly explain the compile time and runtime workflow of a managed assembly as well as analyzing msil with some example programs.

The compilation and execution process of a high level language

As I eluded to in Part 1 a high level language compiler doesn't do everything required in order for you to actually run your managed assembly (or assemblies), we only have an intermediate representation, such as your processor doesn' t understand msil-it only understands assembly for its specific architecture.

High level language compiler (compile time)

OK, you are in Visual Studio and you hit F6-this "builds" your application. Builds is probably the correct term, Visual Studio uses msbuild to build you a managed module.

The actual native code generation of your application (the managed module) is done at runtime by the just in time (JIT) compiler.

JIT Compiler (runtime)

The JIT compiler is invoked milliseconds before code is called to be executed, e.g. If a method add is about to be called by your application then the JIT compiler quickly (very quickly !) Takes the msil representation of that method and generates native code for the method in order for your processor to understand it and actually do something! When I refer to native code I am referring to your machines processor architecture-this is more than likely an x86 or x64, IA64 processors are largely found in server machines.

An interesting point is that with generics the runtime generates the code and then caches it so that no further code gen is already med, when other types are used with that generic type that are not within the direct inheritance chain of the previously cached code then code gen is already med to satisfy that scenario. unlike C ++ templates the C # sort of equivalent generics is done at runtime not compile time.

X86, and x64

This is really a very brief note about the underlying pros and cons of the x86 and x64 ubuntures. when the JIT compiler generates native code for either of the two ubuntures the processor will actually go ahead and further optimize the order by which the instructions are executed in order to attain maximum throughput. this sounds great, and for the most part it is-but we all make mistakes, and processors are no different.

IA64

This is probably the most annoying and yet satisfying processor to target as a compiler writer. unlike x86 and x64 processors The IA64 family of processors execute instructions in the order that it reads es them-it doesn't muddle them up to provide greater throughput like the x86 and x64 Processor family does.

Note: I shocould say that it performs less optimization than x86 and x64 Processor family.

So, the IA64 family allows the compiler writer to optimize native code Gen to the hills and back! But, get the optimization wrong and the processor won't help you that much!

Ngen.exe

The tool ngen (short for native generator, stick image in between the two and it makes more sense !) Takes a managed module and goes ahead and generates architecture specific native code therefore bypassing the JIT compilation stage that occurs at runtime.

There are pros and cons of ngen, the biggest pro that I can think of is improved start up time for an application because of the omission of the JIT compilation stage. as with most things however, there are more factors to think about other than start up time, e.g. the JIT compiler knows a lot more about the environment of the machine at runtime and so can generate more efficient native code as a result.

Note: I 've not checked but I'm guessing that ngen in. Net 3.5 has been further enhanced to generate more optimized code-I may be wrong though with that statement.

Stack Based Evaluation

The CLR uses stack based evaluation when dealing with msil. To start off with we will look at a really simple example, the aim of the application is to add two numbers together and print the result.

First a little background, there is an add operation that Pop's the last two integers off the stack and uses them as its operands-the result of the addition is then pushed onto the stack.

We start off by pushing the two operands onto the stack, each of which is an int32 (4 bytes) 10 and 12 respectively. A call to the operation add pop's the last two items off the stack (two int32's) and uses them as it's operands, computing the result 22. the add operation pushes 22 onto the stack.

Just like the add operation a call to system. console. writeline will pop the last item off the stack and use it as its operand. unlike a high level language we need to explicitly say what overload of the writeline method to use-as the add operation pushed 22 which is an 32 bit integer onto the stack we will use the int32 overload of the writeline method.

. Assembly extern mscorlib {}
. Assembly addexample
{
. Ver 1: 0: 0: 0
}
. Module addexample.exe
. Method Private Static void main () cel managed
{
. Entrypoint
. Maxstack 2
LDC. i4.s 10
LDC. i4.s 12
Add
Call void [mscorlib] system. Console: writeline (int32)
RET
}

I will explain how to compile and run this example later, but to save you waiting the programme does work as expected printing 22 out to the console.

Using Ing tools

There are tools that ship with. net Framework that assist with both disconfiguring managed modules so you can have a look at both the metadata and msil of an application, as well as a tool that will compile msil into a portable executable (PE ).

Ilasm.exe

This tool intermediate language extends er (ilasm.exe) takes some msil (normally a file with. il extension) and generates a PE. ilasm is a command line tool. the ilasm tool can be located in the framework folder of the Microsoft. net Child folder of windows.

As an example, we will take the simple add programme we created earlier and run it through ilasm.exe. I saved the Add example as a text file named add. il on my desktop. the following command will compile the simple application:

C:/users/<user>/desktop> "C:/Windows/Microsoft. NET/framework64/v2.0.50727/ilasm
"Add. Il
Upon successful compilation you will see the following message:
Microsoft (R). Net Framework il runner er. Version 2.0.50727.1378
Copyright (c) Microsoft Corporation. All rights reserved.
Refreshing 'add. Il 'to EXE --> 'add.exe'
Source file is ANSI
Assembled global method main
Creating PE File
Emitting classes:
Emitting fields and methods:
Global methods: 1;
Emitting events and properties:
Global
Writing PE File
Operation completed successfully

As I explained in part 1 A managed module requires a manifest-omitting the manifest (e.g. assembly name etc) will not compile. this seems to be a common error when people use ilasm and see the compilation fail.

To run the sample application simply type the name of the executable and hit Enter-22 will appear on your console... that was great wasn't it ?!

Summary

In this Part I have introduced you to the various stages of a program's execution (both compile and runtime ), as well as explained the various pro's and con's of processor ubuntures and the stack based nature of msil.

In the 3rd and final part of the series we will look at some other tools to assist with analyzing msil, as well as looking at the major language constructs like namespaces, types, methods, etc in msil.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.