MetadataResolver.cs :  » Aspect-Oriented-Frameworks » Runtime-Assembly-Instrumentation-Library » rail » MSIL » C# / CSharp Open Source

Home
C# / CSharp Open Source
1.2.6.4 mono .net core
2.2.6.4 mono core
3.Aspect Oriented Frameworks
4.Bloggers
5.Build Systems
6.Business Application
7.Charting Reporting Tools
8.Chat Servers
9.Code Coverage Tools
10.Content Management Systems CMS
11.CRM ERP
12.Database
13.Development
14.Email
15.Forum
16.Game
17.GIS
18.GUI
19.IDEs
20.Installers Generators
21.Inversion of Control Dependency Injection
22.Issue Tracking
23.Logging Tools
24.Message
25.Mobile
26.Network Clients
27.Network Servers
28.Office
29.PDF
30.Persistence Frameworks
31.Portals
32.Profilers
33.Project Management
34.RSS RDF
35.Rule Engines
36.Script
37.Search Engines
38.Sound Audio
39.Source Control
40.SQL Clients
41.Template Engines
42.Testing
43.UML
44.Web Frameworks
45.Web Service
46.Web Testing
47.Wiki Engines
48.Windows Presentation Foundation
49.Workflows
50.XML Parsers
C# / C Sharp
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source » Aspect Oriented Frameworks » Runtime Assembly Instrumentation Library 
Runtime Assembly Instrumentation Library » rail » MSIL » MetadataResolver.cs
/*
  The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); 
  you may not use this file except in compliance with the License. You may obtain a copy of the License at 
  http://www.mozilla.org/MPL/ 
  Software distributed under the License is distributed on an "AS IS" basis, 
  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language 
  governing rights and limitations under the License. 

  The Original Code is RAIL(Runtime Assembly Instrumentation Library) Alpha Version.
  The Initial Developer of the Original Code is University of Coimbra,
  Computer Science Department, Dependable Systems Group. Copyright (C) University of Coimbra. 
  All Rights Reserved.  
*/
using System.Diagnostics;
using System;
using Mono.PEToolkit;
using Mono.PEToolkit.Metadata;
using Rail.Reflect;
using System.Reflection;
namespace Rail.MSIL{

  /// <summary>
  /// Utility class used to resolve the metadata tokens into user level objects 
  /// like RType, RField and RMethod.
  /// </summary>
  public sealed class MetadataResolver 
  {
    /// <summary>
    /// 
    /// </summary>
    private readonly Image assmLoader;
    /// <summary>
    /// 
    /// </summary>
    private readonly RAssemblyDef assmRail;

    /// <summary>
    /// Each instance will have a predefined context, which consists of the
    /// low level object <code>Assmbl</code> used to obtain physical data and
    /// a high level object <code>RAssembly</code> used to obtain the high level
    /// representations.
    /// </summary>
    /// <param name="assmLoader">The object with the metadata information of the assembly.</param>
    /// <param name="assmRail">The final representation of the assembly being loaded.</param>
    public MetadataResolver(Image assmLoader, RAssemblyDef assmRail) 
    {
      this.assmLoader = assmLoader;
      this.assmRail = assmRail;
    }

    /// <summary>
    /// Resolves a string token.
    /// </summary>
    /// <param name="stringToken">32-bit metadata string token.</param>
    /// <returns></returns>
    public String ResolveString(int stringToken) 
    {

      if ((stringToken) >> 24 != 0x70)
        throw new InvalidProgramException("Wrong token in ldstr");
      MDStream stream = assmLoader.MetaDataRoot.Streams["#US"] as MDStream;
      return MetadataResolver.USStream(stream.RawData,(stringToken) & 0x00ffffff);
    }

    /// <summary>
    /// read the string from the userstrings stream
    /// </summary>
    public static string USStream(byte [] stream,int index)
    {
        int len =  1;
        int cnt = 0;

        //Get the length of the string
        if ((stream[index] & 0x80) == 0) 
        {
          len = stream[index];
          index += 1;
        }
        else if ((stream[index] & 0x40) == 0) 
        {
          len = ((stream[index] & ~0x80) << 8 | stream[index + 1]);
          index += 2;
        }
        else 
        {
          len = ((stream[index] & ~0xC0) << 24 | stream[index + 1] << 16 | stream[index + 2] << 8 | stream[index + 3]);
          index += 4;
        }

        System.Text.StringBuilder temp = new System.Text.StringBuilder(len / 2);
        while(true) 
        {
          
          
          if (len-cnt-1==0) break;
          temp.Append((char)stream[index + cnt]);
          //this works... but I'm not sure if it is the right way to do it
          ++cnt;
          ++cnt;
        }
        string returnString = temp.ToString();
        return temp.ToString();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="blobStream"></param>
    /// <param name="finalPosition"></param>
    /// <param name="startPosition"></param>
    /// <returns></returns>
    public static int GetBlobSizeToRead(byte [] blobStream,out int finalPosition,int startPosition)
    {
      finalPosition = startPosition;
      int sizeToRead = 0;
      if ((blobStream[finalPosition] & 0x80) == 0)
      {
        sizeToRead = blobStream[finalPosition];
        ++finalPosition;
      }
      else if ((blobStream[finalPosition] & 0x40) == 0)
      {
        sizeToRead = (blobStream[finalPosition] & ~0x80) << 8 |
          blobStream[finalPosition + 1];
        finalPosition += 2;
      }
      else
      {
        sizeToRead = (blobStream[finalPosition] & ~0xC0) << 24 | blobStream[finalPosition + 1] << 16 | 
          blobStream[finalPosition + 2] << 8 | blobStream[finalPosition + 3];
        finalPosition += 4;
      }
      return sizeToRead;
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="blobStream"></param>
    /// <param name="finalPosition"></param>
    /// <param name="startPosition"></param>
    public static void SetBlobReadPosition(byte [] blobStream,out int finalPosition,int startPosition)
    {
      finalPosition = startPosition;
      if ((blobStream[finalPosition] & 0x80) == 0)
        ++finalPosition;
      else if ((blobStream[finalPosition] & 0x40) == 0)
        finalPosition += 2;
      else
        finalPosition += 4;
    }

    /// <summary>
    /// Resolves a metadada token like the one that follows a <code>ldtoken</code> instruction.
    /// The return value may be a RType, a RField or a RMethod.
    /// </summary>
    /// <param name="token">The metadata token</param>
    /// <returns></returns>
    public RMember ResolveToken(int token) 
    {
      //            TypeDef : 0x02
      //            TypeRef : 0x01
      //            Field : 0x04
      //            Method : 0x06
      //            MemberRef : 0x0A
      TablesHeap tabs = this.assmLoader.MetadataRoot.TablesHeap;
      uint table = (uint)(token & 0x7f000000);
      int index = token & 0x00FFFFFF;

      if ((table & 0x02000000)!=0 )
        return this.assmRail.RModuleDef.GetTypeByToken(index);
      else if ((table & 0x01000000)!=0 )
        return this.assmRail.GetTypeByToken(index);
      else if ((table & 0x04000000)!=0 )
        return (RFieldDef)this.assmRail.rFieldDefs[(index)-1];
      else if ((table & 0x06000000)!=0 )
        throw new NotSupportedException("Token Not Supported");
      else if ((table & 0x0A000000)!=0 )
      {
        MemberRefRow tmr = (MemberRefRow)tabs[TableId.MemberRef][index];
        MDStream blobStream = this.assmLoader.MetadataRoot.Streams["#Blob"] as MDStream;
        StringsHeap stringsHeap = (this.assmLoader.MetadataRoot.Streams["#Strings"] as MDStream).Heap as StringsHeap;
        string memberName = stringsHeap[tmr.Name];
        RType rtr = null;
        RMethodBase rmb = null;
        switch (tmr.Class.Type)
        {
          case TokenType.TypeRef: 
            rtr = this.assmRail.GetTypeByToken(tmr.Class.RID);
            break;
          case TokenType.TypeDef: 
            rtr = this.assmRail.RModuleDef.GetTypeByToken(tmr.Class.RID);
            break;
          case TokenType.MethodDef:
            rmb = (RMethodBase)this.assmRail.rMethodDefs[(tmr.Class.RID - 1)];
            break;
          case TokenType.TypeSpec:
                  
            if (tabs[TableId.TypeSpec]!=null)
            {
              if (tabs[TableId.TypeSpec]!=null)
                if (tmr.Class.RID<=tabs[TableId.TypeSpec].NumberOfRows)
                {
                  TypeSpecRow tts = (TypeSpecRow)tabs[TableId.TypeSpec][tmr.Class.RID];
                  TypeSpecSig tss = new TypeSpecSig(blobStream.RawData,tts.Signature);
                  rtr = (RTypeRef)RType.GetRType(tss.Type,this.assmRail);
                }
            }
            break;
          case TokenType.ModuleRef:
          default:
            throw new Exception("Unsupported token type");
        }
        int tempPos = tmr.Signature;
        if ((blobStream.RawData[tempPos] & 0x80) == 0)
          tempPos += 1;
        else if ((blobStream.RawData[tempPos] & 0x40) == 0)
          tempPos += 2;
        else
          tempPos += 4;
        bool testeField = (blobStream.RawData[tempPos] == 0x06 ||
          blobStream.RawData[tempPos] == 0x6);
        if (testeField)
        {
          FieldSig fs = new FieldSig(blobStream.RawData,tmr.Signature);
          RType fieldType = RType.GetRType(fs.Type,this.assmRail);
          CallingConventions cc = (CallingConventions)fs.CallingConvention;
          if (rtr!=null)
            return rtr.GetField(memberName);
          else if (rmb!=null)
            return ((RTypeRef)rmb.DeclaringType).GetField(memberName);
        }
        else
        {
          MethodRefSig mrs = new MethodRefSig(blobStream.RawData,tmr.Signature);
          if (mrs!=null)
          {
            RType retType = RType.GetRType(mrs.retType.Type,this.assmRail);
            RParameter [] mrParams = new RParameter[mrs.ParamCount];

            for (int mrParamsIndex = 0; mrParamsIndex<mrs.ParamCount;mrParamsIndex++)
            {
              Param inParam = mrs.Params[mrParamsIndex];            
              RType pType = RType.GetRType(inParam.Type,this.assmRail);
              if (inParam.ByRef)
                pType = this.assmRail.GetRTypeRef(pType.NameWithNameSpace+"&");
              mrParams[mrParamsIndex] = 
                new RParameter(!mrs.HasThis?mrParamsIndex:mrParamsIndex+1,pType);
            }
            if (rtr!=null) 
            {
              if (memberName == ".ctor" || memberName == ".cctor") 
                return rtr.GetConstructor(mrParams);
              else
                return rtr.GetMethod(memberName, retType, mrParams);

            }
          }
        }
        throw new InvalidProgramException("FieldRef or MemberRef  not found");
      }
      else
        throw new NotSupportedException("BAD TOKEN");
    }
    
    /// <summary>
    /// Resolves a InlineSig token.
    /// </summary>
    /// <param name="token">The metadata token</param>
    /// <returns></returns>
    public String ResolveSig(int token) 
    {
      throw new NotSupportedException();    
    }

    /// <summary>
    /// TypeDefOrRef Tag
    /// </summary>
    public enum TypeDefOrRefTag 
    {
      TypeDef = 0x02,
      TypeRef = 0x01,
      TypeSpec = 0x1B
    }


    /// <summary>
    /// Converts a type token into a RType.
    /// </summary>
    /// <param name="typeToken"></param>
    /// <returns></returns>
    public RType ResolveType(int typeToken) 
    {
      RType ret = null;
      switch ((TypeDefOrRefTag)(typeToken >> 24)) 
      {
        case TypeDefOrRefTag.TypeDef: 
          ret = this.assmRail.RModuleDef.GetTypeByToken(typeToken & 0x00ffffff);
          break;
        case TypeDefOrRefTag.TypeRef: 
          ret = this.assmRail.GetTypeByToken(typeToken & 0x00ffffff);
          break;
        case TypeDefOrRefTag.TypeSpec: 
          TypeSpecRow metaTypeSpec = (TypeSpecRow)this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeSpec][typeToken & 0x00ffffff];
          MDStream blobStream = this.assmLoader.MetaDataRoot.Streams["#Blob"] as MDStream;
          TypeSpecSig tps = new TypeSpecSig(blobStream.RawData,metaTypeSpec.Signature);
          ret = RType.GetRType(tps.Type,this.assmRail);
          break;
        default :
          throw new AssemblyReadException("Not a correct TypeDefOrRefTag");
      }
      return ret;

    }

    /// <summary>
    /// Converts a method token into a RMethod
    /// </summary>
    /// <param name="methodToken">The token of the method</param>
    /// <returns>The RMethodBase corresponding</returns>
    public RMethodBase ResolveMethod(int methodToken) 
    {
      RMethodBase method = null;
      int tbl = methodToken >> 24;
      if (tbl == 10) 
      {
        MemberRefRow metaMemberRef = (MemberRefRow)this.assmLoader.MetaDataRoot.TablesHeap[TableId.MemberRef][methodToken & 0x00ffffff]; //this begins in zero and the index is for 1 or higher
        MDStream blobStream = this.assmLoader.MetaDataRoot.Streams["#Blob"] as MDStream;
        method = (RMethodBase)GetReflectionMethod(assmLoader,blobStream.RawData, assmRail,metaMemberRef);  
      } 
      else 
      {
        MethodRow metaMethod = (MethodRow)this.assmLoader.MetaDataRoot.TablesHeap[TableId.Method][methodToken & 0x00ffffff];
        method = (RMethodBase)GetReflectionMethod(metaMethod,methodToken & 0x00ffffff);
      }
      
      if (method == null)
        throw new InvalidProgramException("Error finding the method!");
      return method;
    }


    /// <summary>
    /// Converts a method token into a RMethod
    /// </summary>
    /// <param name="tType">The token type</param>
    /// <param name="RID">the index</param>
    /// <returns>The RMethodBase corresponding</returns>
    public RMethodBase ResolveMethod(TokenType tType, int RID) 
    {
      RMethodBase method = null;
      if (tType == TokenType.MemberRef) 
      {
        MemberRefRow metaMemberRef = 
          this.assmLoader.MetaDataRoot.TablesHeap[TableId.MemberRef][RID] as MemberRefRow; 
        MDStream blobStream = this.assmLoader.MetaDataRoot.Streams["#Blob"] as MDStream;
        method = (RMethodBase)GetReflectionMethod(assmLoader,blobStream.RawData, assmRail,metaMemberRef);  
      } 
      else 
      {
        MethodRow metaMethod = 
          this.assmLoader.MetaDataRoot.TablesHeap[TableId.Method][RID] as MethodRow;
        method = (RMethodBase)GetReflectionMethod(metaMethod,RID);
      }
      
      if (method == null)
        throw new InvalidProgramException("Error finding the method!");
      return method;
    }

    /// <summary>
    /// Converts a field token into a RField
    /// </summary>
    /// <param name="fieldToken"></param>
    /// <returns></returns>
    public RField ResolveField(int fieldToken) 
    {    
      RField field = null;
      
      TokenType tt = (TokenType)(((fieldToken) >> 24) << 24) ;
      if (tt == TokenType.MemberRef) 
      {
        
        MemberRefRow metaMemberRef = (MemberRefRow)this.assmLoader.MetaDataRoot.TablesHeap[TableId.MemberRef][fieldToken & 0x00ffffff]; 
        field = GetReflectionField(metaMemberRef);
        
      }
      else 
      {
        
        
        FieldRow metaField = (FieldRow)this.assmLoader.MetaDataRoot.TablesHeap[TableId.Field][fieldToken & 0x00ffffff];
        field = GetReflectionField(metaField,fieldToken & 0x00ffffff);
        
      }
      if (field==null)
        throw new NullReferenceException("error finding the field");
      return field;
    }

    /// <summary>
    /// Method to get the MethodBase for the method
    /// </summary>
    /// <param name="metaMethod">The representation of the Method</param>
    /// <returns>The MethodBase for the method</returns>
    internal RMethodBase GetReflectionMethod(MethodRow metaMethod, int methodIndex) 
    {        
      int typeIndex = 2;
      while (typeIndex < this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeDef].NumberOfRows)
      {
        TypeDefRow tdr = this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeDef][typeIndex] as TypeDefRow;
        TypeDefRow nextTdr = this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeDef][typeIndex + 1] as TypeDefRow;
        if (tdr.MethodList == nextTdr.MethodList
          && methodIndex >= tdr.MethodList)
        {
          ++typeIndex;
          continue;
        }        
        if (tdr.MethodList==methodIndex)
          break;
        if (tdr.MethodList>methodIndex)
        {
          typeIndex -= 1;
          break;
        }
        if (tdr.MethodList < methodIndex && nextTdr.MethodList > methodIndex)
        {
          break;
        }
        ++typeIndex;
      }

      RType type = this.assmRail.RModuleDef.GetTypeByToken(typeIndex);      
      StringsHeap strHeap = (this.assmLoader.MetaDataRoot.Streams["#Strings"] as MDStream).Heap as StringsHeap;
      MDStream blobStream = this.assmLoader.MetaDataRoot.Streams["#Blob"] as MDStream;
      return FindMethod(type,
        strHeap[metaMethod.Name], 
        metaMethod.Signature,
        assmLoader,
        blobStream.RawData,
        MetadataSignatures.SigTypeEnum.MethodDefSig,
        assmRail);
    }
    

    /// <summary>
    /// 
    /// </summary>
    /// <param name="pe"></param>
    /// <param name="blobStream"></param>
    /// <param name="assemblyDef"></param>
    /// <param name="tmr"></param>
    /// <returns></returns>
    internal static RMethodBase GetReflectionMethod(Image pe, byte [] blobStream,RAssemblyDef assemblyDef,MemberRefRow tmr) 
    {
      StringsHeap stringsHeap = (pe.MetadataRoot.Streams["#Strings"] as MDStream).Heap as StringsHeap;
      switch (tmr.Class.Type) 
      {
        case TokenType.TypeRef: 
        {
          RType tt = assemblyDef.GetTypeByToken(tmr.Class.RID);
          return FindMethod(tt, 
            stringsHeap[tmr.Name],
            tmr.Signature, 
            pe, 
            blobStream, 
            MetadataSignatures.SigTypeEnum.MethodRefSig,
            assemblyDef);
        }
        case TokenType.TypeDef: 
        {
          RType tt = assemblyDef.RModuleDef.GetTypeByToken(tmr.Class.RID);
          return FindMethod(tt, 
            stringsHeap[tmr.Name],
            tmr.Signature, 
            pe, 
            blobStream, 
            MetadataSignatures.SigTypeEnum.MethodDefSig,
            assemblyDef);
        }
        case TokenType.MethodDef: 
          throw new NotImplementedException();
        case TokenType.ModuleRef:
          throw new NotImplementedException();
        case TokenType.TypeSpec:
        {
          
          TypeSpecRow metaTypeSpec = (TypeSpecRow)pe.MetaDataRoot.TablesHeap[TableId.TypeSpec][tmr.Class.RID];
          TypeSpecSig typeSpecSignature = new TypeSpecSig(blobStream,metaTypeSpec.Signature);
          RType tttt =  RType.GetRType(typeSpecSignature.Type,assemblyDef);
          return FindMethod(tttt, 
            stringsHeap[tmr.Name],
            tmr.Signature, 
            pe, 
            blobStream, 
            MetadataSignatures.SigTypeEnum.MethodRefSig,
            assemblyDef);
        }
      }
      return null;
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="metaMemberRef"></param>
    /// <returns></returns>
    internal RField GetReflectionField(MemberRefRow metaMemberRef) 
    {
      StringsHeap strHeap = (this.assmLoader.MetaDataRoot.Streams["#Strings"] as MDStream).Heap as StringsHeap;
      
      switch ((TokenType)metaMemberRef.Class.Type) 
      {
        case TokenType.TypeRef: 
        {
          RTypeRef tt = assmRail.GetTypeByToken(metaMemberRef.Class.RID); //TODO:Check the index
          return tt.GetField(strHeap[metaMemberRef.Name]);
        }
        case TokenType.MethodDef:
        case TokenType.ModuleRef:
        case TokenType.TypeSpec:
          throw new Exception("Unsupported token type");
      }
      return null;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="metaField"></param>
    /// <param name="FieldIndex"></param>
    /// <returns></returns>
    internal unsafe RFieldDef GetReflectionField(FieldRow metaField, int FieldIndex) //change the name you asshole
    {
      
      int typeIndex = 2;
      RTypeDef currentRType = null;
      while (typeIndex <= this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeDef].NumberOfRows)
      {
        TypeDefRow tdr = this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeDef][typeIndex] as TypeDefRow;
        currentRType = (RTypeDef)this.assmRail.RModuleDef.GetTypeByToken(typeIndex);
//        while ((currentRType.BaseType!=null && 
//          (currentRType.BaseType.NameWithNameSpace.Equals("System.Enum") ||
//          currentRType.BaseType.NameWithNameSpace.Equals("System.MulticastDelegate"))) ||
//          (currentRType.Attributes & TypeAttributes.Interface) != 0 ||
//          currentRType.FieldsCount == 0)
//        {
//          ++typeIndex;
//          tdr = this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeDef][typeIndex] as TypeDefRow;
//          currentRType = (RTypeDef)this.assmRail.RModuleDef.GetTypeByToken(typeIndex);
//        }
        TypeDefRow nextTdr = null;
        if (typeIndex + 1 <= this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeDef].NumberOfRows)
          nextTdr =  this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeDef][typeIndex + 1] as TypeDefRow;
        if (nextTdr!=null && tdr.FieldList == nextTdr.FieldList)
        {
          ++typeIndex;
          continue;
        }
        if (tdr.FieldList == FieldIndex)
          break;
        else if (tdr.FieldList > FieldIndex)
        {
          --typeIndex;
          break;
        }
        else if (this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeDef].NumberOfRows >= typeIndex + 1)
        {
          TypeDefRow nexTdr = this.assmLoader.MetaDataRoot.TablesHeap[TableId.TypeDef][typeIndex + 1] as TypeDefRow;
          if (nexTdr.FieldList > FieldIndex)
            break;
        }
        ++typeIndex;
      }
      
      FieldAttributes fieldAttributes = (FieldAttributes)metaField.Flags;
      MDStream blobStream = this.assmLoader.MetaDataRoot.Streams["#Blob"] as MDStream;
      StringsHeap strSream = (this.assmLoader.MetaDataRoot.Streams["#Strings"] as MDStream).Heap as StringsHeap;
      FieldSig fs = new FieldSig(blobStream.RawData,metaField.Signature);
      RType fielType = RType.GetRType(fs.Type,assmRail);
      string fieldName = strSream[metaField.Name];
      
      RFieldDef rfd = (RFieldDef)currentRType.GetField(fieldName);
      if (rfd == null)
        throw new NullReferenceException();
      return rfd;
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="t"></param>
    /// <param name="Name"></param>
    /// <param name="Index"></param>
    /// <param name="pe"></param>
    /// <param name="blobStream"></param>
    /// <param name="s"></param>
    /// <param name="assemblyDef"></param>
    /// <returns></returns>
    internal static RMethodBase FindMethod(RType t, string Name, int Index,Image pe, 
      byte [] blobStream, MetadataSignatures.SigTypeEnum s,RAssemblyDef assemblyDef) 
    {
      RType[] ta = null;
      RType retType = null;
      CallingConventions cc = CallingConventions.Any;
      if (s.Equals(MetadataSignatures.SigTypeEnum.MethodDefSig)) 
      {
        MethodDefSig Sig = new MethodDefSig(blobStream,Index);
        ta = new RType[Sig.ParamCount];
        for (int i = 0;i<Sig.Params.Length; i++)
        {
          ta[i] = RType.GetRType(Sig.Params[i].Type,assemblyDef);
          if (Sig.Params[i].ByRef)
          {
            RType pRTypeTemp = ta[i];
            ta[i] = assemblyDef.GetRTypeRef(ta[i].NameWithNameSpace+"&");
            if (ta[i] == null && pRTypeTemp is RTypeDef)
            {
              Assembly [] asms = assemblyDef.LoadDomain.GetAssemblies();
              if (asms==null)
                asms = new Assembly[0];
              Assembly asm = null;
              foreach (Assembly a in asms)
                if (a.FullName==assemblyDef.Name.FullName ||
                  a.GetName().Name.Equals(assemblyDef.Name.Name))
                {
                  asm = a;
                  break;
                }
              if (asm==null)
                try
                {
                    asm = assemblyDef.LoadDomain.Load(assemblyDef.Name.FullName);
                }
                catch (System.Exception)
                {
                  //asm = assemblyDef.LoadDomain.Load(assemblyDef.Name.Name);
                  AssemblyLoader objc = (AssemblyLoader) assemblyDef.LoadDomain.CreateInstanceAndUnwrap(
                    "Rail",
                    "Rail.Reflect.AssemblyLoader");
                  asm = objc.LoadAssemblyByPatialName(assemblyDef.Name.Name);
                }

              //Assembly asm = assemblyDef.LoadDomain.Load(assemblyDef.CurrentRawAssembly);
              Type ttt = asm.GetType(pRTypeTemp.NameWithNameSpace+"&");
              ta[i] = assemblyDef.DefineTypeRef(ttt);
            }
          }
        }
        cc = (CallingConventions)Sig.CallingConvention;
        retType = RType.GetRType(Sig.retType.Type,assemblyDef);
      }
      else if (s.Equals(MetadataSignatures.SigTypeEnum.MethodRefSig))
      {
        MethodRefSig Sig = new MethodRefSig(blobStream,Index);
        ta = new RType[Sig.ParamCount];
        for (int i = 0;i<Sig.Params.Length; i++)
        {
          ta[i] = RType.GetRType(Sig.Params[i].Type,assemblyDef);
          if (Sig.Params[i].ByRef)
            ta[i] = assemblyDef.GetRTypeRef(ta[i].NameWithNameSpace+"&");
        }
        for (int i = Sig.Params.Length;i<Sig.ParamCount; i++)
        {
          ta[i] = RType.GetRType(Sig.ParamsAfterSentinel[i-Sig.Params.Length].Type,assemblyDef);  
          if (Sig.Params[i].ByRef)
            ta[i] = assemblyDef.GetRTypeRef(ta[i].NameWithNameSpace+"&");
        }
        cc = (CallingConventions)Sig.CallingConvention;
        retType = RType.GetRType(Sig.retType.Type,assemblyDef);
        //string sfilna = retType.FullName;
      }
      RMethodBase ret = null;
    
      RParameter [] rp = new RParameter[ta.Length];
      int j = 0;
      foreach (RType rr in ta)
      {
        rp[j++] = new RParameter(1,rr);
      }

      if ( Name == ".ctor" ) 
      {
        ret = (RMethodBase)t.GetConstructor(rp);
      } 
      else if ( Name == ".cctor" ) 
      {
        ret = (RMethodBase)t.GetConstructor(rp);
      } 
      else
      {
//        RMethod[] tas = t.GetMethods();
//        for (int i = 0;i <tas.Length;i++) 
//        {
//          if (string.Compare(tas[i].Name,0,Name,0,tas[i].Name.Length,true)==0)
//            if (string.Compare(tas[i].Name,0,Name,0,Name.Length,true)==0)
//              if(tas[i].ReturnType.ReturnType.NameWithNameSpace==retType.NameWithNameSpace) 
//              {
//                RParameter [] pi = tas[i].GetParameters();
//                bool trueAllParams = true;
//                if (pi==null) 
//                  pi = new RParameter[0];
//                if (ta==null) 
//                  ta = new RType[0];
//                if (pi.Length!=ta.Length)
//                  trueAllParams = false;
//                if (trueAllParams)
//                  for (int j = 0; j < pi.Length;j++) 
//                  {
//                    if (!(pi[j].ParameterType.NameWithNameSpace==ta[j].NameWithNameSpace))
//                      trueAllParams = false;
//                  }
//                if (trueAllParams) 
//                {
//                  ret = tas[i];
//                  break;
//                }
//              }
//              
//        }
        if (t is RTypeRef)
          ret = ((RTypeRef)t).GetMethod(Name,retType,rp);
        else
          ret = t.GetMethod(Name,retType,rp);
      }
      if (ret==null)
        throw new NullReferenceException();
      return (RMethodBase)ret;
    }
  }
}
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.