public void Write(MethodBody body, /*Telerik Authorship*/ MetadataToken methodToken, /*Telerik Authorship*/ MetadataToken localVarToken)
        {
            var method = new SourceMethod (body.Method);

            var instructions = GetInstructions (body);
            int count = instructions.Count;
            if (count == 0)
                return;

            var offsets = new int [count];
            var start_rows = new int [count];
            var start_cols = new int [count];

            SourceFile file;
            Populate (instructions, offsets, start_rows, start_cols, out file);

            var builder = writer.OpenMethod (file.CompilationUnit, 0, method);

            for (int i = 0; i < count; i++)
                builder.MarkSequencePoint (
                    offsets [i],
                    file.CompilationUnit.SourceFile,
                    start_rows [i],
                    start_cols [i],
                    false);

            if (body.HasVariables)
                AddVariables (body.Variables);

            writer.CloseMethod ();
        }
Пример #2
0
		void WriteToken (MetadataToken token)
		{
			if (token.RID == 0)
				m_codeWriter.Write (0);
			else
				m_codeWriter.Write (token.ToUInt ());
		}
Пример #3
0
        public uint EncodeToken(MetadataToken token)
        {
            var index = Array.IndexOf(_tables, token.TokenType);
            if (index == -1)
                throw new ArgumentException("Table is not supported by this encoder.", "token");

            return (token.Rid << _tableIndexBitCount) | (uint)index;
        }
Пример #4
0
        public AssemblyNameReference(string name, Version version)
        {
            if (name == null)
                throw new ArgumentNullException ("name");

            this.name = name;
            this.version = Mixin.CheckVersion (version);
            this.hash_algorithm = AssemblyHashAlgorithm.None;
            this.token = new MetadataToken (TokenType.AssemblyRef);
        }
Пример #5
0
 /// <summary>
 /// This method returns the member with the specified metadata token in the given module. It supports more TokenTypes than the standard Cecil method.
 /// </summary>
 /// <param name="module"></param>
 /// <param name="token"></param>
 /// <returns></returns>
 internal static IMetadataTokenProvider LookupTokenExtended(this ModuleDefinition module, MetadataToken token)
 {
     switch (token.TokenType) {
         case TokenType.TypeDef:
         case TokenType.TypeRef:
         case TokenType.MemberRef:
         case TokenType.Field:
         case TokenType.Method:
         case TokenType.MethodSpec:
         case TokenType.TypeSpec:
             return module.LookupToken(token);
         default:
             IMetadataTokenProvider provider;
             var success = _tokenProviderCache.GetValue(module, InitializeTokenProviderCache).TryGetValue(token.ToUInt32(),
                 out provider);
             return success ? provider : null;
     }
 }
Пример #6
0
        internal void AddDynamicArgument(DynamicScope dynamicScope, Type clsArgument, Type[]?requiredCustomModifiers, Type[]?optionalCustomModifiers)
        {
            IncrementArgCounts();

            Debug.Assert(clsArgument != null);

            if (optionalCustomModifiers != null)
            {
                for (int i = 0; i < optionalCustomModifiers.Length; i++)
                {
                    Type t = optionalCustomModifiers[i];

                    if (t is not RuntimeType rtType)
                    {
                        throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(optionalCustomModifiers));
                    }

                    if (t.HasElementType)
                    {
                        throw new ArgumentException(SR.Argument_ArraysInvalid, nameof(optionalCustomModifiers));
                    }

                    if (t.ContainsGenericParameters)
                    {
                        throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(optionalCustomModifiers));
                    }

                    AddElementType(CorElementType.ELEMENT_TYPE_CMOD_OPT);

                    int token = dynamicScope.GetTokenFor(rtType.TypeHandle);
                    Debug.Assert(!MetadataToken.IsNullToken(token));
                    AddToken(token);
                }
            }

            if (requiredCustomModifiers != null)
            {
                for (int i = 0; i < requiredCustomModifiers.Length; i++)
                {
                    Type t = requiredCustomModifiers[i];

                    if (t is not RuntimeType rtType)
                    {
                        throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(requiredCustomModifiers));
                    }

                    if (t.HasElementType)
                    {
                        throw new ArgumentException(SR.Argument_ArraysInvalid, nameof(requiredCustomModifiers));
                    }

                    if (t.ContainsGenericParameters)
                    {
                        throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(requiredCustomModifiers));
                    }

                    AddElementType(CorElementType.ELEMENT_TYPE_CMOD_REQD);

                    int token = dynamicScope.GetTokenFor(rtType.TypeHandle);
                    Debug.Assert(!MetadataToken.IsNullToken(token));
                    AddToken(token);
                }
            }

            AddOneArgTypeHelper(clsArgument);
        }
Пример #7
0
		public string GetString (MetadataToken token)
		{
			return reader.image.UserStringHeap.Read (token.RID);
		}
Пример #8
0
        public bool MoveNext()
        {
            int nextRid = m_currentRid + 1;

            if (nextRid >= m_endRid) {
                if (m_tables == null) {
                    throw new ObjectDisposedException("MetadataTableEnumerator");
                }
                return false;
            }

            m_currentRid = nextRid;

            switch (m_indirection) {
                case EnumerationIndirection.Method:
                    m_currentToken = m_tables.m_import.MethodPtrTable.GetMethodFor(m_currentRid);
                    break;

                case EnumerationIndirection.Field:
                    m_currentToken = m_tables.m_import.FieldPtrTable.GetFieldFor(m_currentRid);
                    break;

                case EnumerationIndirection.Property:
                    m_currentToken = m_tables.m_import.PropertyPtrTable.GetPropertyFor(m_currentRid);
                    break;

                case EnumerationIndirection.Event:
                    m_currentToken = m_tables.m_import.EventPtrTable.GetEventFor(m_currentRid);
                    break;

                case EnumerationIndirection.Param:
                    m_currentToken = m_tables.m_import.ParamPtrTable.GetParamFor(m_currentRid);
                    break;

                default:
                    m_currentToken = new MetadataToken(m_type, (uint)m_currentRid);
                    break;
            }

            return true;
        }
Пример #9
0
		public override void VisitAssemblyLinkedResource (AssemblyLinkedResource res)
		{
			MetadataToken impl = new MetadataToken (TokenType.AssemblyRef,
				(uint) m_asm.MainModule.AssemblyReferences.IndexOf (res.Assembly) + 1);

			AddManifestResource (0, res.Name, res.Flags, impl);
		}
Пример #10
0
		public void SetOverrideMapping (uint rid, MetadataToken [] mapping)
		{
			Overrides [rid] = mapping;
		}
Пример #11
0
		public void SetInterfaceMapping (uint type_rid, MetadataToken [] mapping)
		{
			Interfaces [type_rid] = mapping;
		}
Пример #12
0
        // Does a given typedef in the specified PE file implement the specified interface?
        private bool ImplementsHelper(PEFileReader peFile, MetadataToken typeDefToken, TypeInfo ifaceType)
        {
            System.Diagnostics.Contracts.Contract.Requires(typeDefToken.Table == MDTables.Tables.TypeDef);

            MDTables mdScope = peFile.MetaData;

            // Walk through all rules of the interface implementation table,
            // looking for this typeDefToken.  If we find it, check to see if
            // that row says this type implements the specified interface.
            // If not, continue walking the interface impl table.
            uint numRows = mdScope.RowsInTable(MDTables.Tables.InterfaceImpl);

            for (uint i = 0; i < numRows; i++)
            {
                mdScope.SeekToRowOfTable(MDTables.Tables.InterfaceImpl, i);
                uint typeDefRow = mdScope.ReadRowIndex(MDTables.Tables.TypeDef);
                if (typeDefRow == typeDefToken.Index)
                {
                    // if we implement it, return true.  Else continue.
                    MetadataToken interfaceToken = mdScope.ReadMetadataToken(MDTables.Encodings.TypeDefOrRef);
                    if (ifaceType.HasName)
                    {
                        mdScope.SeekToMDToken(interfaceToken);
                        // Interface for IContract should be a typeref.
                        switch (interfaceToken.Table)
                        {
                        case MDTables.Tables.TypeRef:
                        {
                            MetadataToken resolutionScope = mdScope.ReadMetadataToken(MDTables.Encodings.ResolutionScope);
                            String        ifaceName       = mdScope.ReadString();
                            if (!String.Equals(ifaceName, ifaceType._typeName))
                            {
                                continue;
                            }
                            String ifaceNameSpace = mdScope.ReadString();
                            if (!String.Equals(ifaceNameSpace, ifaceType._nameSpace))
                            {
                                continue;
                            }
                            if (MiniAssembly.Equals(ifaceType.Assembly, peFile, resolutionScope))
                            {
                                return(true);
                            }
                            break;
                        }

                        case MDTables.Tables.TypeDef:
                        {
                            // This type implements an interface defined in the same assembly.
                            // This isn't really interesting for the add-in model, based on what
                            // we've currently designed and our limited use of this class.
                            mdScope.B.ReadUInt32();          // TypeAttributes
                            String ifaceName = mdScope.ReadString();
                            if (!String.Equals(ifaceName, ifaceType._typeName))
                            {
                                continue;
                            }
                            String ifaceNameSpace = mdScope.ReadString();
                            if (!String.Equals(ifaceNameSpace, ifaceType._nameSpace))
                            {
                                continue;
                            }
                            if (this._assembly.Equals(ifaceType._assembly))
                            {
                                return(true);
                            }
                            break;
                        }

                        case MDTables.Tables.TypeSpec:
                            // Since we're only looking for IContract, which is non-generic,
                            // we should ignore this row and move on.
                            System.Diagnostics.Contracts.Contract.Assert(false, "Checking whether a type implements a TypeSpec is NYI (generic interface?)");
                            break;

                        default:
                            System.Diagnostics.Contracts.Contract.Assert(false, "Support for this interface type is NYI");
                            throw new NotImplementedException(String.Format(CultureInfo.CurrentCulture, Res.UnsupportedInterfaceType, interfaceToken.Table));
                        }
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
            }
            return(false);
        }
Пример #13
0
        public MiniConstructorInfo[] GetConstructors(bool includePrivate)
        {
            System.Diagnostics.Contracts.Contract.Assert(HasToken /* || HasReflectionType*/, "GetConstructors needs a token (or you should uncomment the support for Reflection types)");

            List <MiniConstructorInfo> ctors = new List <MiniConstructorInfo>();

            /*
             * if (HasReflectionType) {
             *  System.Reflection.BindingFlags visibility = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public;
             *  if (includePrivate)
             *      visibility |= System.Reflection.BindingFlags.NonPublic;
             *  foreach (System.Reflection.ConstructorInfo ctor in _reflectionType.GetConstructors(visibility))
             *      ctors.Add(new MiniConstructorInfo(ctor));
             *  return ctors.ToArray();
             * }
             */

            System.Diagnostics.Contracts.Contract.Assert(_mdToken.Table == MDTables.Tables.TypeDef);

            PEFileReader peFile = _assembly.PEFileReader;

            peFile.InitMetaData();
            MDTables MetaData = peFile.MetaData;

            MetaData.SeekToMDToken(_mdToken);
            System.Reflection.TypeAttributes flags = (System.Reflection.TypeAttributes)peFile.B.ReadUInt32();
            System.Reflection.TypeAttributes vis   = System.Reflection.TypeAttributes.VisibilityMask & flags;
            bool isPublic = (vis == System.Reflection.TypeAttributes.Public); // don't support NestedPublic

            if (!includePrivate && !isPublic)
            {
                return(new MiniConstructorInfo[0]);
            }
            MetaData.ReadStringIndex();                                                                   // typename
            MetaData.ReadStringIndex();                                                                   // namespace

            MetadataToken baseClass        = MetaData.ReadMetadataToken(MDTables.Encodings.TypeDefOrRef); // Base class
            uint          firstMemberIndex = MetaData.ReadRowIndex(MDTables.Tables.FieldDef);             // Field list
            uint          firstMethodIndex = MetaData.ReadRowIndex(MDTables.Tables.MethodDef);            // Method list
            uint          lastMethodIndex;

            // If this is the last entry in the TypeDef table, then all the rest of the methods in the MethodDef
            // table belong to this type.  Otherwise, look for the methods belonging to the next type.
            if (_mdToken.Index == MetaData.RowsInTable(MDTables.Tables.TypeDef))
            {
                lastMethodIndex = MetaData.RowsInTable(MDTables.Tables.MethodDef);
            }
            else
            {
                MetaData.SeekToRowOfTable(MDTables.Tables.TypeDef, _mdToken.Index);            // Seek to next type (not off by 1!)
                peFile.B.ReadUInt32();                                                         // Flags
                MetaData.ReadStringIndex();                                                    // type name
                MetaData.ReadStringIndex();                                                    // namespace
                MetaData.ReadMetadataToken(MDTables.Encodings.TypeDefOrRef);                   // Next type's base class
                MetaData.ReadRowIndex(MDTables.Tables.FieldDef);                               // field list;
                uint firstMethodOfNextType = MetaData.ReadRowIndex(MDTables.Tables.MethodDef); // method list
                lastMethodIndex = firstMethodOfNextType - 1;
            }

            // Now walk through list of methods, looking for ones w/ the name ".ctor".
            for (uint i = firstMethodIndex; i <= lastMethodIndex; i++)
            {
                MetadataToken method = new MetadataToken(MDTables.Tables.MethodDef, i);
                MetaData.SeekToMDToken(method);
                UInt32 rva       = peFile.B.ReadUInt32();
                UInt16 implFlags = peFile.B.ReadUInt16();                                                             // MethodImplAttributes
                System.Reflection.MethodAttributes attrs = (System.Reflection.MethodAttributes)peFile.B.ReadUInt16(); // Flags - MethodAttributes
                // Visibility check
                if (!includePrivate && (attrs & System.Reflection.MethodAttributes.Public) == 0)
                {
                    continue;
                }
                String methodName = MetaData.ReadString();  // Name
                // @
                if (!String.Equals(methodName, ".ctor"))
                {
                    continue;
                }

                byte[] sig = MetaData.ReadBlob();
                try
                {
                    MiniParameterInfo[] parameters = ParseSig(sig);
                    ctors.Add(new MiniConstructorInfo(parameters));
                }
                catch (GenericsNotImplementedException)
                {
                    // may be caused by a Generic contract.  The user will be warned elsewhere that generic contracts are not supported.

                    /*
                     * if (Warnings != null) {
                     *  lock (Warnings) {
                     *      Warnings.Add(String.Format(CultureInfo.CurrentCulture, Res.UnparsibleConstructorSignature, this.Name, e.GetType().Name, e.Message));
                     *  }
                     * }
                     */
                }
            } // for each .ctor
            return(ctors.ToArray());
        }
Пример #14
0
 public ConstantRow(ElementType type, MetadataToken parent, uint value) : this()
 {
     Type   = type;
     Parent = parent;
     Value  = value;
 }
Пример #15
0
 public MemberID(string assemblyName, string moduleName, MetadataToken token)
 {
     AssemblyQualifiedTypeName = assemblyName;
     ModuleName = moduleName;
     Token      = token.ToInt32();
 }
Пример #16
0
 /// <summary>
 /// Creates a new row for the edit-and-continue remap metadata table.
 /// </summary>
 /// <param name="token">The token that was remapped.</param>
 public EncMapRow(MetadataToken token)
 {
     Token = token;
 }
Пример #17
0
 public MethodSymbols(MetadataToken methodToken)
 {
     this.method_token = methodToken;
 }
Пример #18
0
 internal ModuleReference()
 {
     this.token = new MetadataToken (TokenType.ModuleRef);
 }
Пример #19
0
        public override void VisitTypeReferenceCollection(TypeReferenceCollection refs)
        {
            ArrayList orderedTypeRefs = new ArrayList (refs.Count);
            foreach (TypeReference tr in refs)
                orderedTypeRefs.Add (tr);

            orderedTypeRefs.Sort (TableComparers.TypeRef.Instance);

            TypeRefTable trTable = m_tableWriter.GetTypeRefTable ();
            foreach (TypeReference t in orderedTypeRefs) {
                MetadataToken scope;

                if (t.Module.Assembly != m_mod.Assembly)
                    throw new ReflectionException ("A type as not been correctly imported");

                if (t.Scope == null)
                    continue;

                if (t.DeclaringType != null)
                    scope = new MetadataToken (TokenType.TypeRef, GetRidFor (t.DeclaringType));
                else if (t.Scope is AssemblyNameReference)
                    scope = new MetadataToken (TokenType.AssemblyRef,
                        GetRidFor ((AssemblyNameReference) t.Scope));
                else if (t.Scope is ModuleDefinition)
                    scope = new MetadataToken (TokenType.Module,
                        GetRidFor ((ModuleDefinition) t.Scope));
                else if (t.Scope is ModuleReference)
                    scope = new MetadataToken (TokenType.ModuleRef,
                        GetRidFor ((ModuleReference) t.Scope));
                else
                    scope = new MetadataToken (TokenType.ExportedType, 0);

                TypeRefRow trRow = m_rowWriter.CreateTypeRefRow (
                    scope,
                    m_mdWriter.AddString (t.Name),
                    m_mdWriter.AddString (t.Namespace));

                trTable.Rows.Add (trRow);
                t.MetadataToken = new MetadataToken (TokenType.TypeRef, (uint) trTable.Rows.Count);
            }
        }
Пример #20
0
 /// <summary>
 /// Creates a module reference from a module reference metadata row.
 /// </summary>
 /// <param name="context">The reader context.</param>
 /// <param name="token">The token to initialize the module reference for.</param>
 /// <param name="row">The metadata table row to base the module reference. on.</param>
 public SerializedModuleReference(ModuleReaderContext context, MetadataToken token, in ModuleReferenceRow row)
Пример #21
0
		public void SetGenericConstraintMapping (uint gp_rid, MetadataToken [] mapping)
		{
			GenericConstraints [gp_rid] = mapping;
		}
Пример #22
0
        private void AddOneArgTypeHelper(Type clsArgument, Type[]?requiredCustomModifiers, Type[]?optionalCustomModifiers)
        {
            // This function will not increase the argument count. It only fills in bytes
            // in the signature based on clsArgument. This helper is called for return type.

            Debug.Assert(clsArgument != null);

            if (optionalCustomModifiers != null)
            {
                for (int i = 0; i < optionalCustomModifiers.Length; i++)
                {
                    Type t = optionalCustomModifiers[i];

                    if (t == null)
                    {
                        throw new ArgumentNullException(nameof(optionalCustomModifiers));
                    }

                    if (t.HasElementType)
                    {
                        throw new ArgumentException(SR.Argument_ArraysInvalid, nameof(optionalCustomModifiers));
                    }

                    if (t.ContainsGenericParameters)
                    {
                        throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(optionalCustomModifiers));
                    }

                    AddElementType(CorElementType.ELEMENT_TYPE_CMOD_OPT);

                    int token = m_module !.GetTypeToken(t).Token;
                    Debug.Assert(!MetadataToken.IsNullToken(token));
                    AddToken(token);
                }
            }

            if (requiredCustomModifiers != null)
            {
                for (int i = 0; i < requiredCustomModifiers.Length; i++)
                {
                    Type t = requiredCustomModifiers[i];

                    if (t == null)
                    {
                        throw new ArgumentNullException(nameof(requiredCustomModifiers));
                    }

                    if (t.HasElementType)
                    {
                        throw new ArgumentException(SR.Argument_ArraysInvalid, nameof(requiredCustomModifiers));
                    }

                    if (t.ContainsGenericParameters)
                    {
                        throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(requiredCustomModifiers));
                    }

                    AddElementType(CorElementType.ELEMENT_TYPE_CMOD_REQD);

                    int token = m_module !.GetTypeToken(t).Token;
                    Debug.Assert(!MetadataToken.IsNullToken(token));
                    AddToken(token);
                }
            }

            AddOneArgTypeHelper(clsArgument);
        }
Пример #23
0
 public override uint Encode(MetadataToken token)
 {
     throw new NotImplementedException();
 }
Пример #24
0
 /// <summary>
 /// Creates a security declaration from a declaration metadata row.
 /// </summary>
 /// <param name="context">The reader context.</param>
 /// <param name="token">The token to initialize the declaration for.</param>
 /// <param name="row">The metadata table row to base the security declaration on.</param>
 public SerializedSecurityDeclaration(
     ModuleReaderContext context,
     MetadataToken token,
     in SecurityDeclarationRow row)
Пример #25
0
 /// <summary>
 /// Creates a exported type from a exported type metadata row.
 /// </summary>
 /// <param name="context">The reader context.</param>
 /// <param name="token">The token to initialize the exported type for.</param>
 /// <param name="row">The metadata table row to base the exported type on.</param>
 public SerializedExportedType(ModuleReaderContext context, MetadataToken token, in ExportedTypeRow row)
 /// <summary>
 /// Creates a member reference from an implementation map metadata row.
 /// </summary>
 /// <param name="context">The reader context.</param>
 /// <param name="token">The token to initialize the mapping for.</param>
 /// <param name="row">The metadata table row to base the mapping on.</param>
 public SerializedImplementationMap(
     ModuleReaderContext context,
     MetadataToken token,
     in ImplementationMapRow row)
Пример #27
0
		void WriteMetadataToken (MetadataToken token)
		{
			WriteUInt32 (token.ToUInt32 ());
		}
Пример #28
0
 /// <summary>
 /// Creates a method semantics object from a method semantics row.
 /// </summary>
 /// <param name="context">The reader context.</param>
 /// <param name="token">The token to initialize the semantics for.</param>
 /// <param name="row">The metadata table row to base the semantics on.</param>
 public SerializedMethodSemantics(ModuleReaderContext context, MetadataToken token, in MethodSemanticsRow row)
Пример #29
0
		void PatchRawFatMethod (ByteBuffer buffer, MethodSymbols symbols, CodeWriter writer, out MetadataToken local_var_token)
		{
			var flags = ReadUInt16 ();
			buffer.WriteUInt16 (flags);
			buffer.WriteUInt16 (ReadUInt16 ());
			symbols.code_size = ReadInt32 ();
			buffer.WriteInt32 (symbols.code_size);
			local_var_token = ReadToken ();

			if (local_var_token.RID > 0) {
				var variables = symbols.variables = ReadVariables (local_var_token);
				buffer.WriteUInt32 (variables != null
					? writer.GetStandAloneSignature (symbols.variables).ToUInt32 ()
					: 0);
			} else
				buffer.WriteUInt32 (0);

			PatchRawCode (buffer, symbols.code_size, writer);

			if ((flags & 0x8) != 0)
				PatchRawSection (buffer, writer.metadata);
		}
Пример #30
0
 /// <summary>
 /// Initializes the module reference with a metadata token.
 /// </summary>
 /// <param name="token">The metadata token.</param>
 protected ModuleReference(MetadataToken token)
     : base(token)
 {
     _name = new LazyVariable <string>(GetName);
 }
Пример #31
0
		internal ModuleReference ()
		{
			this.token = new MetadataToken (TokenType.ModuleRef);
		}
Пример #32
0
 /// <summary>
 /// Creates a field definition from a field metadata row.
 /// </summary>
 /// <param name="context">The reader context.</param>
 /// <param name="token">The token to initialize the field for.</param>
 /// <param name="row">The metadata table row to base the field definition on.</param>
 public SerializedFieldDefinition(ModuleReaderContext context, MetadataToken token, in FieldDefinitionRow row)
 public MetadataMember ResolveMember(MetadataToken token)
 {
     return null;
 }
Пример #34
0
 public string GetString(MetadataToken token)
 {
     return(reader.image.UserStringHeap.Read(token.RID));
 }
Пример #35
0
        public override void VisitCustomAttributeCollection(CustomAttributeCollection customAttrs)
        {
            if (customAttrs.Count == 0)
                return;

            CustomAttributeTable caTable = m_tableWriter.GetCustomAttributeTable ();
            foreach (CustomAttribute ca in customAttrs) {
                MetadataToken parent;
                if (customAttrs.Container is AssemblyDefinition)
                    parent = new MetadataToken (TokenType.Assembly, 1);
                else if (customAttrs.Container is ModuleDefinition)
                    parent = new MetadataToken (TokenType.Module, 1);
                else if (customAttrs.Container is IMetadataTokenProvider)
                    parent = (customAttrs.Container as IMetadataTokenProvider).MetadataToken;
                else
                    throw new ReflectionException ("Unknown Custom Attribute parent");

                uint value = ca.IsReadable ?
                    m_sigWriter.AddCustomAttribute (GetCustomAttributeSig (ca), ca.Constructor) :
                    m_mdWriter.AddBlob (m_mod.GetAsByteArray (ca));
                CustomAttributeRow caRow = m_rowWriter.CreateCustomAttributeRow (
                    parent,
                    ca.Constructor.MetadataToken,
                    value);

                caTable.Rows.Add (caRow);
            }
        }
Пример #36
0
 public CallSite GetCallSite(MetadataToken token)
 {
     return(reader.ReadCallSite(token));
 }
Пример #37
0
		public bool TryGetInterfaceMapping (TypeDefinition type, out MetadataToken [] mapping)
		{
			return Interfaces.TryGetValue (type.token.RID, out mapping);
		}
Пример #38
0
        void PatchRawFatMethod(ByteBuffer buffer, MethodSymbols symbols, CodeWriter writer, out MetadataToken local_var_token)
        {
            var flags = ReadUInt16();

            buffer.WriteUInt16(flags);
            buffer.WriteUInt16(ReadUInt16());
            symbols.code_size = ReadInt32();
            buffer.WriteInt32(symbols.code_size);
            local_var_token = ReadToken();

            if (local_var_token.RID > 0)
            {
                var variables = symbols.variables = ReadVariables(local_var_token);
                buffer.WriteUInt32(variables != null
                    ? writer.GetStandAloneSignature(symbols.variables).ToUInt32()
                    : 0);
            }
            else
            {
                buffer.WriteUInt32(0);
            }

            PatchRawCode(buffer, symbols.code_size, writer);

            if ((flags & 0x8) != 0)
            {
                PatchRawSection(buffer, writer.metadata);
            }
        }
Пример #39
0
		public bool TryGetGenericConstraintMapping (GenericParameter generic_parameter, out MetadataToken [] mapping)
		{
			return GenericConstraints.TryGetValue (generic_parameter.token.RID, out mapping);
		}
 /// <summary>
 /// Creates a generic parameter from a generic parameter metadata row.
 /// </summary>
 /// <param name="context">The reader context.</param>
 /// <param name="token">The token to initialize the generic parameter for.</param>
 /// <param name="row">The metadata table row to base the generic parameter on.</param>
 public SerializedGenericParameter(ModuleReaderContext context, MetadataToken token, in GenericParameterRow row)
Пример #41
0
		public bool TryGetOverrideMapping (MethodDefinition method, out MetadataToken [] mapping)
		{
			return Overrides.TryGetValue (method.token.RID, out mapping);
		}
Пример #42
0
 /// <summary>
 /// Initializes the file reference with a metadata token.
 /// </summary>
 /// <param name="token">The metadata token.</param>
 protected FileReference(MetadataToken token)
     : base(token)
 {
     _name      = new LazyVariable <string>(GetName);
     _hashValue = new LazyVariable <byte[]>(GetHashValue);
 }
Пример #43
0
        public ByteBuffer PatchRawMethodBody(MethodDefinition method, CodeWriter writer, out int code_size, out MetadataToken local_var_token)
        {
            var position = MoveTo (method);

            var buffer = new ByteBuffer ();

            var flags = ReadByte ();

            switch (flags & 0x3) {
            case 0x2: // tiny
                buffer.WriteByte (flags);
                local_var_token = MetadataToken.Zero;
                code_size = flags >> 2;
                PatchRawCode (buffer, code_size, writer);
                break;
            case 0x3: // fat
                Advance (-1);
                PatchRawFatMethod (buffer, writer, out code_size, out local_var_token);
                break;
            default:
                throw new NotSupportedException ();
            }

            MoveBackTo (position);

            return buffer;
        }
Пример #44
0
 protected internal MetadataMember(MetadataHeader header, MetadataToken token, MetadataRow row)
 {
     Header        = header;
     MetadataToken = token;
     MetadataRow   = row;
 }
Пример #45
0
 public override bool Validate(MetadataToken token)
 {
     throw new NotImplementedException();
 }
Пример #46
0
 void WriteMetadataToken(MetadataToken token)
 {
     WriteUInt32(token.ToUInt32());
 }
Пример #47
0
		void AddManifestResource (uint offset, string name, ManifestResourceAttributes flags, MetadataToken impl)
		{
			ManifestResourceTable mrTable = m_tableWriter.GetManifestResourceTable ();
			ManifestResourceRow mrRow = m_rowWriter.CreateManifestResourceRow (
				offset,
				flags,
				m_mdWriter.AddString (name),
				impl);

			mrTable.Rows.Add (mrRow);
		}
 public AttachedPropertyDefinition(FieldDefinition fieldDefinition, MetadataToken metadataToken) : base(fieldDefinition)
 {
     this.fieldDefinition = fieldDefinition;
     MetadataToken        = metadataToken;
 }
Пример #49
0
 public void Reset()
 {
     m_currentRid = m_startRid;
     m_currentToken = default(MetadataToken);
 }
Пример #50
0
 private uint GetIndexSize(MetadataToken table, MetaDataTableInfo[] tables)
 {
     return(tables[(int)table].RowCount <= ushort.MaxValue ? 2U : 4U);
 }
Пример #51
0
		MetadataToken GetStandAloneSignatureToken (uint signature)
		{
			MetadataToken token;
			if (standalone_signatures.TryGetValue (signature, out token))
				return token;

			token = new MetadataToken (TokenType.Signature, metadata.AddStandAloneSignature (signature));
			standalone_signatures.Add (signature, token);
			return token;
		}
Пример #52
0
        void DefineScope(ScopeDebugInformation scope, MethodDebugInformation info, out MetadataToken import_parent)
        {
            var start_offset = scope.Start.Offset;
            var end_offset   = scope.End.IsEndOfMethod
                                ? info.code_size
                                : scope.End.Offset;

            import_parent = new MetadataToken(0u);

            writer.OpenScope(start_offset);

            if (scope.Import != null && scope.Import.HasTargets && !import_info_to_parent.TryGetValue(info.scope.Import, out import_parent))
            {
                foreach (var target in scope.Import.Targets)
                {
                    switch (target.Kind)
                    {
                    case ImportTargetKind.ImportNamespace:
                        writer.UsingNamespace("U" + target.@namespace);
                        break;

                    case ImportTargetKind.ImportType:
                        writer.UsingNamespace("T" + TypeParser.ToParseable(target.type));
                        break;

                    case ImportTargetKind.DefineNamespaceAlias:
                        writer.UsingNamespace("A" + target.Alias + " U" + target.@namespace);
                        break;

                    case ImportTargetKind.DefineTypeAlias:
                        writer.UsingNamespace("A" + target.Alias + " T" + TypeParser.ToParseable(target.type));
                        break;
                    }
                }

                import_info_to_parent.Add(info.scope.Import, info.method.MetadataToken);
            }

            var sym_token = info.local_var_token.ToInt32();

            if (!scope.variables.IsNullOrEmpty())
            {
                for (int i = 0; i < scope.variables.Count; i++)
                {
                    var variable = scope.variables [i];
                    DefineLocalVariable(variable, sym_token, start_offset, end_offset);
                }
            }

            if (!scope.constants.IsNullOrEmpty())
            {
                for (int i = 0; i < scope.constants.Count; i++)
                {
                    var constant = scope.constants [i];
                    DefineConstant(constant);
                }
            }

            if (!scope.scopes.IsNullOrEmpty())
            {
                for (int i = 0; i < scope.scopes.Count; i++)
                {
                    MetadataToken _;
                    DefineScope(scope.scopes [i], info, out _);
                }
            }

            writer.CloseScope(end_offset);
        }
Пример #53
0
		public VariableDefinitionCollection ReadVariables (MetadataToken local_var_token)
		{
			var position = reader.position;
			var variables = reader.ReadVariables (local_var_token);
			reader.position = position;

			return variables;
		}
		void ReadCilBody (MethodBody body, BinaryReader br)
		{
			long start = br.BaseStream.Position;
			Instruction last = null;
			m_instructions.Clear();
			InstructionCollection code = body.Instructions;
			GenericContext context = new GenericContext (body.Method);

			while (br.BaseStream.Position < start + body.CodeSize) {
				OpCode op;
				long offset = br.BaseStream.Position - start;
				int cursor = br.ReadByte ();
				if (cursor == 0xfe)
					op = OpCodes.TwoBytesOpCode [br.ReadByte ()];
				else
					op = OpCodes.OneByteOpCode [cursor];

				Instruction instr = new Instruction ((int) offset, op);
				switch (op.OperandType) {
				case OperandType.InlineNone :
					break;
				case OperandType.InlineSwitch :
					uint length = br.ReadUInt32 ();
					int [] branches = new int [length];
					int [] buf = new int [length];
					for (int i = 0; i < length; i++)
						buf [i] = br.ReadInt32 ();
					for (int i = 0; i < length; i++)
						branches [i] = Convert.ToInt32 (br.BaseStream.Position - start + buf [i]);
					instr.Operand = branches;
					break;
				case OperandType.ShortInlineBrTarget :
					sbyte sbrtgt = br.ReadSByte ();
					instr.Operand = Convert.ToInt32 (br.BaseStream.Position - start + sbrtgt);
					break;
				case OperandType.InlineBrTarget :
					int brtgt = br.ReadInt32 ();
					instr.Operand = Convert.ToInt32 (br.BaseStream.Position - start + brtgt);
					break;
				case OperandType.ShortInlineI :
					if (op == OpCodes.Ldc_I4_S)
						instr.Operand = br.ReadSByte ();
					else
						instr.Operand = br.ReadByte ();
					break;
				case OperandType.ShortInlineVar :
					instr.Operand = GetVariable (body, br.ReadByte ());
					break;
				case OperandType.ShortInlineParam :
					instr.Operand = GetParameter (body, br.ReadByte ());
					break;
				case OperandType.InlineSig :
					instr.Operand = GetCallSiteAt (br.ReadInt32 (), context);
					break;
				case OperandType.InlineI :
					instr.Operand = br.ReadInt32 ();
					break;
				case OperandType.InlineVar :
					instr.Operand = GetVariable (body, br.ReadInt16 ());
					break;
				case OperandType.InlineParam :
					instr.Operand = GetParameter (body, br.ReadInt16 ());
					break;
				case OperandType.InlineI8 :
					instr.Operand = br.ReadInt64 ();
					break;
				case OperandType.ShortInlineR :
					instr.Operand = br.ReadSingle ();
					break;
				case OperandType.InlineR :
					instr.Operand = br.ReadDouble ();
					break;
				case OperandType.InlineString :
					instr.Operand = m_root.Streams.UserStringsHeap [GetRid (br.ReadInt32 ())];
					break;
				case OperandType.InlineField :
				case OperandType.InlineMethod :
				case OperandType.InlineType :
				case OperandType.InlineTok :
					MetadataToken token = new MetadataToken (br.ReadInt32 ());
					switch (token.TokenType) {
					case TokenType.TypeDef:
						instr.Operand = m_reflectReader.GetTypeDefAt (token.RID);
						break;
					case TokenType.TypeRef:
						instr.Operand = m_reflectReader.GetTypeRefAt (token.RID);
						break;
					case TokenType.TypeSpec:
						instr.Operand = m_reflectReader.GetTypeSpecAt (token.RID, context);
						break;
					case TokenType.Field:
						instr.Operand = m_reflectReader.GetFieldDefAt (token.RID);
						break;
					case TokenType.Method:
						instr.Operand = m_reflectReader.GetMethodDefAt (token.RID);
						break;
					case TokenType.MethodSpec:
						instr.Operand = m_reflectReader.GetMethodSpecAt (token.RID, context);
						break;
					case TokenType.MemberRef:
						instr.Operand = m_reflectReader.GetMemberRefAt (token.RID, context);
						break;
					default:
						throw new ReflectionException ("Wrong token: " + token);
					}
					break;
				}

				m_instructions.Add (instr.Offset, instr);

				if (last != null) {
					last.Next = instr;
					instr.Previous = last;
				}

				last = instr;

				code.Add (instr);
			}

			// resolve branches
			foreach (Instruction i in code) {
				switch (i.OpCode.OperandType) {
				case OperandType.ShortInlineBrTarget:
				case OperandType.InlineBrTarget:
					i.Operand = GetInstruction (body, (int) i.Operand);
					break;
				case OperandType.InlineSwitch:
					int [] lbls = (int []) i.Operand;
					Instruction [] instrs = new Instruction [lbls.Length];
					for (int j = 0; j < lbls.Length; j++)
						instrs [j] = GetInstruction (body, lbls [j]);
					i.Operand = instrs;
					break;
				}
			}

			if (m_reflectReader.SymbolReader != null)
				m_reflectReader.SymbolReader.Read (body, m_instructions);
		}
Пример #55
0
		public CallSite GetCallSite (MetadataToken token)
		{
			return reader.ReadCallSite (token);
		}
Пример #56
0
        public void WriteCodedToken(MetadataToken token, CodedTokenType tokenType)
        {
            var codedToken = CodedTokenSchema.GetCodedToken(token, tokenType);

            WriteBySize(codedToken.Value, IsLargeToken(tokenType));
        }
Пример #57
0
 public void WriteForwardInfo(MetadataToken import_parent)
 {
     Write(CustomMetadataType.ForwardInfo, () => writer.WriteUInt32(import_parent.ToUInt32()));
 }
Пример #58
0
        [System.Security.SecurityCritical]  // auto-generated
        private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
        {
            // This function will not increase the argument count. It only fills in bytes
            // in the signature based on clsArgument. This helper is called for return type.

            Contract.Requires(clsArgument != null);
            Contract.Requires((optionalCustomModifiers == null && requiredCustomModifiers == null) || !clsArgument.ContainsGenericParameters);

            if (optionalCustomModifiers != null)
            {
                for (int i = 0; i < optionalCustomModifiers.Length; i++)
                {
                    Type t = optionalCustomModifiers[i];

                    if (t == null)
                    {
                        throw new ArgumentNullException(nameof(optionalCustomModifiers));
                    }

                    if (t.HasElementType)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(optionalCustomModifiers));
                    }

                    if (t.ContainsGenericParameters)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(optionalCustomModifiers));
                    }

                    AddElementType(CorElementType.CModOpt);

                    int token = m_module.GetTypeToken(t).Token;
                    Contract.Assert(!MetadataToken.IsNullToken(token));
                    AddToken(token);
                }
            }

            if (requiredCustomModifiers != null)
            {
                for (int i = 0; i < requiredCustomModifiers.Length; i++)
                {
                    Type t = requiredCustomModifiers[i];

                    if (t == null)
                    {
                        throw new ArgumentNullException(nameof(requiredCustomModifiers));
                    }

                    if (t.HasElementType)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(requiredCustomModifiers));
                    }

                    if (t.ContainsGenericParameters)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(requiredCustomModifiers));
                    }

                    AddElementType(CorElementType.CModReqd);

                    int token = m_module.GetTypeToken(t).Token;
                    Contract.Assert(!MetadataToken.IsNullToken(token));
                    AddToken(token);
                }
            }

            AddOneArgTypeHelper(clsArgument);
        }
		void ReadExceptionHandlerEnd (ExceptionHandler eh, BinaryReader br, MethodBody body)
		{
			switch (eh.Type) {
			case ExceptionHandlerType.Catch :
				MetadataToken token = new MetadataToken (br.ReadInt32 ());
				eh.CatchType = m_reflectReader.GetTypeDefOrRef (token, new GenericContext (body.Method));
				break;
			case ExceptionHandlerType.Filter :
				eh.FilterStart = GetInstruction (body, br.ReadInt32 ());
				eh.FilterEnd = GetInstruction (body, eh.HandlerStart.Previous.Offset);
				break;
			default :
				br.ReadInt32 ();
				break;
			}
		}
Пример #60
0
        public void WriteToken(MetadataToken token)
        {
            var tableType = Convert(token.Type);

            WriteBySize(token.RID, IsLargeTable(tableType));
        }