Tuesday, January 27, 2009

Taming Coreclr Part-1

This is my life's first blog so kindly bear me for mistakes.
CLR fascinates me since beginning. It is the virtual platform to execute managed code.
When i saw the silverlight executing managed code inside the browser, it really thrilled me.
Silerlight is made up of three main components:

NpCtrl is a NP plugin for browsers. So whenever browser loads a page having XAP refrences, NpCtrl is loaded. As per the my research this plugin then loads the AgCore which is the main Silverlight unmanaged execution engine.
AgCore (Ag is symbol of silver in periodic table) is responsible for rendering the contents. if the xap has any Msil references or MSIL code, AgCore asks NpCtrl to load CoreClr. I am not sure about this indirection, as AgCore can itself load the CoreClr but it asks NpCtrl to load the CoreClr.

Dissecting the CoreClr:
CoreClr.dll is unmanaged COM library which is self contained and full CIL execution system(EE,GC etc). Microsoft has not released publicly interfaces and API's supported by CoreClr. So i took a side approach to reverse engineer the CoreClr.
I opened the coreclr with PE explorer and here are the public exports:
1. g_CLREngineMetrics
2. GetCLRRuntimeHost

As the name suggests second export should be used to get the CLRRuntimeHost handle. As its big brother(CLR) usage interface ICLRRuntimeHost for providing the hosting capabilities. To know more about Hosting CLR i recommend read Customizing the Microsoft .NET Framework Common Language Runtime by Steven Pratschner

GetCLRRuntimeHost expects two parameters, one is the GUID for CLRRuntimeHost and second is pointer to pointer to CLRHOST interface which i initial thought is ICLRRuntimeHost type (but it did not). So biggest challenge was to get the GUID for CLRHOST. I disassemble the coreclr using my old time friend IDA PRO. I used GuidFinder a plugin for IDA but it was not able to find any GUID. So i adopted another approach, I created a plugin for firefox a general purpose plugin for txt extensions. So what this plugin does, It loads coreclr explicitly and used Detour to intercept calls made to GetCLRRuntimeHost. So i think you got how i managed to find GUID for CoreCLRHost.
Here is CoreCLR guid

0x712AB73F, 0x2C22,0x4807, 0xAD, 0x7E, 0xF5, 0x01, 0xD7, 0xB7, 0x2C, 0x2D)

I called it CLRGUID.

Rest in next blog.. I will appreciate if you provide any feedback :)