This is a mirror of official site: http://jasper-net.blogspot.com/

Using Mono Cecil Decompiler within Windbg to decompile

| Wednesday, June 9, 2010
I have been hacking Mono lately and one of the coolest projects I have seen is the Mono Decompiler. It’s like Reflector but no UI and an API to decompile. Guess what, even reflector is built on top of Mono Cecil.  Most of times when I have to debug I would end up using  !dumpil  sos command to get  the IL  of the method desc.  I am not an IL guru, I am much comfortable reading C# than IL. I could have used reflector to do the same thing, but here are couple of reasons for doing this.

I don’t have to open another application and I am comfortable with cdb.exe
I like to understand this library , which I could use in the future.
Here is a simple app that would return C# code.  I could have written a windbg extension, but I am lazy

using System;
using System.IO;
using System.Linq;
using System.Text;
using Mono.Cecil;
using Cecil.Decompiler.Languages;

namespace Conosole
{

class Decompiler
{
static void Main(string[] args)
{
var function = args[1].Split(new[] { '.' });

//MethodName
var methodName = function.Last();

//Typename
var typeName = function.ElementAt(function.Length - 2);

//Namespace
var ns = function.TakeWhile((c, i) => i < function.Length - 2).Aggregate(new StringBuilder(),(sb,s) => sb.Append(s+".")).ToString().Trim(new [] {'.'}) ;

Console.WriteLine((from module in AssemblyFactory.GetAssembly(args[0]).Modules.Cast<ModuleDefinition>()
from type in module.Types.Cast<TypeDefinition>()
from method in type.Methods.Cast<MethodDefinition>()
where type.Namespace == ns && type.Name == typeName && method.Name == methodName
select method.SourceCode()).First());
}
}

public static class Extensions
{
public static string SourceCode(this MethodDefinition methodName)
{
var writer = new StringWriter();
CSharp.GetLanguage(CSharpVersion.V3).GetWriter(new PlainTextFormatter(writer)).Write(methodName);
return writer.ToString();
}
}
}

Read more: Naveen's Blog

Posted via email from jasper22's posterous

0 comments: