Alex Rivera | Logout

What happens when a .net application is started?

Asked 2011-07-07T04:50:51.717
35

I have been developing apps using .net for quite sometime now. But, I am still not sure how does the CLR know that a .net app has started. Is there like one instance of CLR per app? I don't think this can be the case as there is just one GC which manages all the memory for all .net apps. Does the CLR kind of run in background? I am quite confused.

Edit
Report

1 Answer

49

Hmm, let me take a shot at this too.

  1. Somebody builds a .NET application in C#, or .NET 'Intermediate Language', or another managed language.

  2. The compiler for that language csc.exe (C#), or ilasm.exe (bytecode assembler), or whichever, produces a PE executable. The PE executable has a specific structure that the compiler or assembler populates. That includes:

    • an entry point, and
    • a list of dynamic libraries that it uses (the IMPORT table). One of those libraries is mscoree.dll
    • lots of metadata, including the targeted .NET runtime version
  3. When the executable is clicked on, ran from the command line, or executed from a Win32 API, the Windows loader implementation (in NTDLL.dll) takes over

  4. The loader code is responsible for getting the executable into memory, loading dynamic link libraries if needed, mapping linked libraries into a place the executable code can reach them, and updating the Import Address Table with the actual addresses of the mapped libraries.

  5. Once all is ready, the loader jumps to the entry point (through what I assume is some shenanigans switching from kernel space to user space, or to protected mode, since the application runs in it's own protected 32 or 64 bit memory space). The entry point goes to mscoree.dll - the .NET Common Object Runtime Execution Engine, which was just mapped into the processes memory. I've seen this DLL referred to as the .NET startup shim, and it allows the multiple installs of .NET to exist on one machine. Mscoree.dll is the library you'll use if you are embedding a .NET language in your own regular application.

  6. Mscoree.dll looks at the metadata loaded from the PE executable, specifically the CLR header, and th

answered 2011-07-09T03:56:58.507

Your Answer