# # Sample code to demonstrate how to use ILReader # By Haibo Luo @ http://blogs.msdn.com/haibo_luo # # THIS CODE IS PROVIDED "AS IS", WITH NO WARRANTIES INTENDED OR IMPLIED. USE AT YOUR OWN RISK # import clr, sys, System try: clr.AddReference(r'ClrTest.Reflection.ILReader.dll') except: print '\nFail to add reference of ILReader. One simple fix is to copy ILReader.dll to the current directory.' sys.exit(1) from ClrTest.Reflection import * # # Find which method could throw the specified exception # class ThrowExceptionHunter(ILInstructionVisitor): def __init__(self, method, exceptionType): self.method = method self.ctors = exceptionType.GetConstructors() self.found = False def VisitInlineMethodInstruction(self, instruction): if instruction.Method in self.ctors: print instruction.Method, '|', self.method self.found = True clrStringType = clr.GetClrType(System.String) exceptionType = clr.GetClrType(System.ArgumentOutOfRangeException) for method in clrStringType.GetMethods(): h = ThrowExceptionHunter(method, exceptionType) for il in ILReader(method): il.Accept(h) if h.found: break # # Find all methods called by String.StartsWith # method = clrStringType.GetMethod('StartsWith', System.Array[System.Type]([str, System.StringComparison])) reader = ILReader(method) class CalleeFinder(ILInstructionVisitor): def __init__(self): self.callees = [] def VisitInlineMethodInstruction(self, instruction): self.callees.append(instruction.Method) v = CalleeFinder() reader.Accept(v) print "How many:", len(v.callees) for x in v.callees: print x, '/', x.DeclaringType # # Find all unique methods called by String.StartsWith # class CalleeFinderNoDup(ILInstructionVisitor): def __init__(self): self.callees = set() def VisitInlineMethodInstruction(self, instruction): self.callees.add(instruction.Method) v = CalleeFinderNoDup() reader.Accept(v) print "How many:", len(v.callees) for x in v.callees: print x, '/', x.DeclaringType # # print the IL for String.StartsWith # v = ReadableILStringVisitor(ReadableILStringToTextWriter(System.Console.Out)) reader.Accept(v)