Search code examples
c#interopcilmdbgimetadataimport

Get base class hierarchy methods with IMetaDataImport EnumMethods


I'm trying to implement managed debugger looking at MDBG sample.

MDBG is capable of resolving function names within given scope, but it's not taking in consideration base classes.

MDBG is doing this:

    /// <summary>
    /// Resolves a Function from a Module, Class Name, and Function Name.
    /// </summary>
    /// <param name="mdbgModule">The Module that has the Function.</param>
    /// <param name="className">The name of the Class that has the Function.</param>
    /// <param name="functionName">The name of the Function.</param>
    /// <returns>The MDbgFunction that matches the given parameters.</returns>
    public MDbgFunction ResolveFunctionName(MDbgModule mdbgModule, string className, string functionName) {
        ...
        foreach (MethodInfo mi in t.GetMethods()) {
            if (mi.Name.Equals(functionName)) {
                func = mdbgModule.GetFunction((mi as MetadataMethodInfo).MetadataToken);
                break;
            }
        }
        return func;
    }

While the Type.GetMethods() is overriden and has this implementation, using IMetaDataImport.EnumMethods:

     public override MethodInfo[] GetMethods(BindingFlags bindingAttr) {
        ArrayList al = new ArrayList();
        IntPtr hEnum = new IntPtr();

        int methodToken;
        try {
            while (true) {
                int size;
                m_importer.EnumMethods(ref hEnum, (int) m_typeToken, out methodToken, 1, out size);
                if (size == 0) {
                    break;
                }
                al.Add(new MetadataMethodInfo(m_importer, methodToken));
            }
        }
        finally {
            m_importer.CloseEnum(hEnum);
        }
        return (MethodInfo[]) al.ToArray(typeof (MethodInfo));
    }

The problem is that m_importer.EnumMethods() Enumerates MethodDef tokens representing methods of the specified type, but I'm interested in all methods from the class hierarchy.

How can I get all the Methods defined in class hierarchy? (Obviously, common methods like reflection cannot be used, since I'm analyzing type defined in other process)

My limited knowledge of interop and deep CLR/CIL structure creates impediments for finding the right way to go here.

Any advice/suggestion is welcome!

Regards,


Solution

  • GetTypeProps will return the metadata token of the base type in ptkExtends, you can use that to walk up the inheritance tree and collect the methods from each as you go.

    Be aware, however, that the metadata token might not be a TypeDef. It could be a TypeRef (requiring you to resolve the type) or a TypeSpec (requiring you to parse the type signature and extract an appropriate TypeDef/TypeRef).