public MethodDefinitionProjection(MethodDefinition method, MethodDefinitionTreatment treatment)
 {
     Attributes = method.Attributes;
     ImplAttributes = method.ImplAttributes;
     Name = method.Name;
     Treatment = treatment;
 }
 internal MethodImplAttribute(MethodImplAttributes methodImplAttributes)
 {
     MethodImplOptions all = 
         MethodImplOptions.Unmanaged | MethodImplOptions.ForwardRef | MethodImplOptions.PreserveSig | 
         MethodImplOptions.InternalCall | MethodImplOptions.Synchronized | MethodImplOptions.NoInlining;
     _val = ((MethodImplOptions)methodImplAttributes) & all;
 }
 // used by MethodImplAttribute
 public void SetMethodImplementation(int attributeIndex, MethodImplAttributes attributes)
 {
     VerifySealed(expected: false);
     Debug.Assert(attributeIndex >= 0);
     this.attributes = attributes;
     this.methodImplIndex = attributeIndex;
     SetDataStored();
 }
        public void SetImplementationFlags(MethodImplAttributes implementationFlags)
        {
            TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract);
            MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public);

            method.SetImplementationFlags(implementationFlags);
            Assert.Equal(implementationFlags, method.MethodImplementationFlags);
        }
Example #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MethodDefRow"/> struct.
 /// </summary>
 /// <param name="rva">The rva.</param>
 /// <param name="implFlags">The impl flags.</param>
 /// <param name="flags">The flags.</param>
 /// <param name="nameStringIdx">The name string idx.</param>
 /// <param name="signatureBlobIdx">The signature BLOB idx.</param>
 /// <param name="paramList">The param list.</param>
 public MethodDefRow(uint rva, MethodImplAttributes implFlags, MethodAttributes flags, TokenTypes nameStringIdx, 
     TokenTypes signatureBlobIdx, TokenTypes paramList)
 {
     _rva = rva;
     _implFlags = implFlags;
     _flags = flags;
     _nameStringIdx = nameStringIdx;
     _signatureBlobIdx = signatureBlobIdx;
     _paramList = paramList;
 }
Example #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MethodDefRow"/> struct.
        /// </summary>
        /// <param name="rva">The rva.</param>
        /// <param name="implFlags">The impl flags.</param>
        /// <param name="flags">The flags.</param>
        /// <param name="nameStringIdx">The name string idx.</param>
        /// <param name="signatureBlobIdx">The signature BLOB idx.</param>
        /// <param name="paramList">The param list.</param>
        public MethodDefRow(uint rva, MethodImplAttributes implFlags, MethodAttributes flags, HeapIndexToken nameStringIdx,
								HeapIndexToken signatureBlobIdx, Token paramList)
        {
            this._rva = rva;
            this._implFlags = implFlags;
            this._flags = flags;
            this._nameStringIdx = nameStringIdx;
            this._signatureBlobIdx = signatureBlobIdx;
            this._paramList = paramList;
        }
Example #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MethodDefRow"/> struct.
        /// </summary>
        /// <param name="rva">The rva.</param>
        /// <param name="implFlags">The impl flags.</param>
        /// <param name="flags">The flags.</param>
        /// <param name="paramList">The param list.</param>
        public MethodDefRow(uint rva, MethodImplAttributes implFlags, MethodAttributes flags, HeapIndexToken nameString,
								HeapIndexToken signatureBlob, Token paramList)
        {
            Rva = rva;
            ImplFlags = implFlags;
            Flags = flags;
            NameString = nameString;
            SignatureBlob = signatureBlob;
            ParamList = paramList;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CilRuntimeMethod"/> class.
        /// </summary>
        /// <param name="module">The module.</param>
        /// <param name="name">The name.</param>
        /// <param name="signature">The signature.</param>
        /// <param name="token">The token.</param>
        /// <param name="declaringType">Type of the declaring.</param>
        /// <param name="methodAttributes">The method attributes.</param>
        /// <param name="methodImplAttributes">The method impl attributes.</param>
        /// <param name="rva">The rva.</param>
        public CilRuntimeMethod(ITypeModule module, string name, MethodSignature signature, Token token, RuntimeType declaringType, MethodAttributes methodAttributes, MethodImplAttributes methodImplAttributes, uint rva)
            : base(module, token, declaringType)
        {
            base.Attributes = methodAttributes;
            base.ImplAttributes = methodImplAttributes;
            base.Rva = rva;
            this.Name = name;
            this.Signature = signature;

            this.Parameters = new List<RuntimeParameter>();
        }
Example #9
0
		public MethodDefOptions(MethodDef method) {
			this.ImplAttributes = method.ImplAttributes;
			this.Attributes = method.Attributes;
			this.Name = method.Name;
			this.MethodSig = method.MethodSig;
			this.ImplMap = method.ImplMap;
			this.CustomAttributes.AddRange(method.CustomAttributes);
			this.DeclSecurities.AddRange(method.DeclSecurities);
			this.ParamDefs.AddRange(method.ParamDefs);
			this.GenericParameters.AddRange(method.GenericParameters);
			this.Overrides.AddRange(method.Overrides);
		}
Example #10
0
        public MethodDefinition(string name, RVA rva,
			MethodAttributes attrs, MethodImplAttributes implAttrs,
			bool hasThis, bool explicitThis, MethodCallingConvention callConv)
            : base(name, hasThis, explicitThis, callConv)
        {
            m_rva = rva;
            m_attributes = attrs;
            m_implAttrs = implAttrs;

            if (!IsStatic)
                m_this = new ParameterDefinition ("this", 0, (ParameterAttributes) 0, null);
        }
Example #11
0
		public MethodDefOptions(MethodDef method) {
			ImplAttributes = method.ImplAttributes;
			Attributes = method.Attributes;
			SemanticsAttributes = method.SemanticsAttributes;
			RVA = method.RVA;
			Name = method.Name;
			MethodSig = method.MethodSig;
			ImplMap = method.ImplMap;
			CustomAttributes.AddRange(method.CustomAttributes);
			DeclSecurities.AddRange(method.DeclSecurities);
			ParamDefs.AddRange(method.ParamDefs);
			GenericParameters.AddRange(method.GenericParameters);
			Overrides.AddRange(method.Overrides);
		}
Example #12
0
        private void LoadData(CLIFile pFile)
        {
            RVA = pFile.ReadUInt32();
            ImplFlags = (MethodImplAttributes)pFile.ReadUInt16();
            Flags = (MethodAttributes)pFile.ReadUInt16();
            Name = pFile.ReadStringHeap(pFile.ReadHeapIndex(CLIHeapOffsetSize.Strings32Bit));
            Signature = pFile.ReadBlobHeap(pFile.ReadHeapIndex(CLIHeapOffsetSize.Blob32Bit));
            if (pFile.ParamTable.Length >= 0xFFFF) ParamListIndex = pFile.ReadInt32() - 1;
            else ParamListIndex = pFile.ReadUInt16() - 1;

            if (RVA != 0)
            {
                Body = new MethodDefBodyData();
                Body.LoadData(this);
            }
        }
Example #13
0
		public MethodBodyOptions(MethodDef method) {
			this.CodeType = method.CodeType;
			if (method.MethodBody is CilBody) {
				var headerRva = method.RVA;
				var headerFileOffset = (FileOffset)method.Module.ToFileOffset((uint)headerRva);
				var rva = (RVA)((uint)headerRva + method.Body.HeaderSize);
				var fileOffset = (FileOffset)((long)headerFileOffset + method.Body.HeaderSize);
				this.CilBodyOptions = new CilBodyOptions((CilBody)method.MethodBody, headerRva, headerFileOffset, rva, fileOffset);
				this.BodyType = MethodBodyType.Cil;
			}
			else if (method.MethodBody is NativeMethodBody) {
				this.NativeMethodBodyOptions = new NativeMethodBodyOptions((NativeMethodBody)method.MethodBody);
				this.BodyType = MethodBodyType.Native;
			}
			else
				this.BodyType = MethodBodyType.None;
		}
Example #14
0
		public MethodBodyOptions(MethodDef method)
		{
			this.CodeType = method.CodeType;
			if (method.MethodBody is CilBody) {
				FileOffset fileOffset = 0;
				var mod = method.Module as ModuleDefMD;
				if (mod != null)
					fileOffset = mod.MetaData.PEImage.ToFileOffset(method.RVA);
				this.CilBodyOptions = new CilBodyOptions((CilBody)method.MethodBody, method.RVA, fileOffset);
				this.BodyType = MethodBodyType.Cil;
			}
			else if (method.MethodBody is NativeMethodBody) {
				this.NativeMethodBodyOptions = new NativeMethodBodyOptions((NativeMethodBody)method.MethodBody);
				this.BodyType = MethodBodyType.Native;
			}
			else
				this.BodyType = MethodBodyType.None;
		}
Example #15
0
 public MethodBodyOptions(MethodDef method)
 {
     CodeType = method.CodeType;
     if (method.MethodBody is CilBody)
     {
         var headerRva        = method.RVA;
         var headerFileOffset = (FileOffset)(method.Module.ToFileOffset((uint)headerRva) ?? (uint)headerRva);
         var rva        = (RVA)((uint)headerRva + method.Body.HeaderSize);
         var fileOffset = (FileOffset)((long)headerFileOffset + method.Body.HeaderSize);
         CilBodyOptions = new CilBodyOptions((CilBody)method.MethodBody, headerRva, headerFileOffset, rva, fileOffset);
         BodyType       = MethodBodyType.Cil;
     }
     else if (method.MethodBody is NativeMethodBody)
     {
         NativeMethodBodyOptions = new NativeMethodBodyOptions((NativeMethodBody)method.MethodBody);
         BodyType = MethodBodyType.Native;
     }
     else
     {
         BodyType = MethodBodyType.None;
     }
 }
Example #16
0
        private void SetMethodImplAttribute(CustomAttributeBuilder customBuilder)
        {
            MethodImplOptions opt;

            switch (customBuilder.Constructor.ParameterCount)
            {
            case 0:
                opt = 0;
                break;

            case 1:
            {
                object val = customBuilder.GetConstructorArgument(0);
                if (val is short)
                {
                    opt = (MethodImplOptions)(short)val;
                }
                else if (val is int)
                {
                    opt = (MethodImplOptions)(int)val;
                }
                else
                {
                    opt = (MethodImplOptions)val;
                }
                break;
            }

            default:
                throw new NotSupportedException();
            }
            MethodCodeType?type = customBuilder.GetFieldValue <MethodCodeType>("MethodCodeType");

            implFlags = (MethodImplAttributes)opt;
            if (type.HasValue)
            {
                implFlags |= (MethodImplAttributes)type;
            }
        }
Example #17
0
        public void DisplayMethodTable(byte[] metadata, byte[] blob, byte[] strings, int[] rows)
        {
            int  old  = tableoffset;
            bool b    = tablepresent(rows, 6);
            int  offs = tableoffset;

            tableoffset = old;

            if (b)
            {
                for (int k = 1; k <= rows[6]; k++)
                {
                    int rva = BitConverter.ToInt32(metadata, offs);

                    offs += 4;
                    MethodImplAttributes impflags = (MethodImplAttributes)BitConverter.ToInt16(metadata, offs);

                    offs += 2;
                    int flags = (int)BitConverter.ToInt16(metadata, offs);

                    offs += 2;
                    int name = ReadStringIndex(metadata, offs);

                    offs += offsetstring;
                    int signature = ReadBlobIndex(metadata, offs);

                    offs += offsetblob;
                    int param = BitConverter.ToInt16(metadata, offs);

                    offs += 2;

                    Console.WriteLine("Name : {0}", GetString(strings, name));

                    string s = DisplayMethodSignature(blob, signature, param, GetString(strings, name));
                    Console.WriteLine("Signature: #Blob[{0}] {1}", signature, s);
                }
            }
        }
		internal static string ToString(MethodImplAttributes flags) {
			var sb = new StringBuilder();

			switch ((flags & MethodImplAttributes.CodeTypeMask)) {
			case MethodImplAttributes.IL: sb.Append("IL"); break;
			case MethodImplAttributes.Native: sb.Append("Native"); break;
			case MethodImplAttributes.OPTIL: sb.Append("OPTIL"); break;
			case MethodImplAttributes.Runtime: sb.Append("Runtime"); break;
			}

			if ((flags & MethodImplAttributes.Unmanaged) != 0)
				sb.Append(" | Unmanaged");
			else
				sb.Append(" | Managed");

			if ((flags & MethodImplAttributes.ForwardRef) != 0)
				sb.Append(" | ForwardRef");

			if ((flags & MethodImplAttributes.PreserveSig) != 0)
				sb.Append(" | PreserveSig");

			if ((flags & MethodImplAttributes.InternalCall) != 0)
				sb.Append(" | InternalCall");

			if ((flags & MethodImplAttributes.Synchronized) != 0)
				sb.Append(" | Synchronized");

			if ((flags & MethodImplAttributes.NoInlining) != 0)
				sb.Append(" | NoInlining");

			if ((flags & MethodImplAttributes.AggressiveInlining) != 0)
				sb.Append(" | AggressiveInlining");

			if ((flags & MethodImplAttributes.NoOptimization) != 0)
				sb.Append(" | NoOptimization");

			return sb.ToString();
		}
Example #19
0
        /// <summary>
        /// Gets method parameters and method flags
        /// </summary>
        /// <param name="methodAttrs">Method attributes</param>
        /// <param name="methodImplAttrs">Method implementation attributes</param>
        /// <returns></returns>
        public MDParameters GetMDParameters(out MethodAttributes methodAttrs, out MethodImplAttributes methodImplAttrs)
        {
            methodAttrs     = 0;
            methodImplAttrs = 0;
            var mod = Module;

            if (mod == null)
            {
                return(null);
            }
            var mdi = mod.GetMetaDataInterface <IMetaDataImport>();

            if (mdi == null)
            {
                return(null);
            }
            var name = MetaDataUtils.GetMethodDefName(mdi, Token, out methodAttrs, out methodImplAttrs);

            if (name == null)
            {
                return(null);
            }
            return(MetaDataUtils.GetParameters(mdi, Token));
        }
Example #20
0
 public MethodBodyOptions(MethodDef method)
 {
     this.CodeType = method.CodeType;
     if (method.MethodBody is CilBody)
     {
         FileOffset fileOffset = 0;
         var        mod        = method.Module as ModuleDefMD;
         if (mod != null)
         {
             fileOffset = mod.MetaData.PEImage.ToFileOffset(method.RVA);
         }
         this.CilBodyOptions = new CilBodyOptions((CilBody)method.MethodBody, method.RVA, fileOffset);
         this.BodyType       = MethodBodyType.Cil;
     }
     else if (method.MethodBody is NativeMethodBody)
     {
         this.NativeMethodBodyOptions = new NativeMethodBodyOptions((NativeMethodBody)method.MethodBody);
         this.BodyType = MethodBodyType.Native;
     }
     else
     {
         this.BodyType = MethodBodyType.None;
     }
 }
Example #21
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="readerModule">The module which contains this <c>Method</c> row</param>
        /// <param name="rid">Row ID</param>
        /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception>
        /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception>
        public MethodDefMD(ModuleDefMD readerModule, uint rid)
        {
#if DEBUG
            if (readerModule == null)
            {
                throw new ArgumentNullException("readerModule");
            }
            if (readerModule.TablesStream.MethodTable.IsInvalidRID(rid))
            {
                throw new BadImageFormatException(string.Format("Method rid {0} does not exist", rid));
            }
#endif
            this.origRid      = rid;
            this.rid          = rid;
            this.readerModule = readerModule;
            uint name;
            uint signature = readerModule.TablesStream.ReadMethodRow(origRid, out this.rva, out this.implAttributes, out this.attributes, out name);
            this.name               = readerModule.StringsStream.ReadNoNull(name);
            this.origRva            = rva;
            this.origImplAttributes = (MethodImplAttributes)implAttributes;
            this.declaringType2     = readerModule.GetOwnerType(this);
            this.signature          = readerModule.ReadSignature(signature, new GenericParamContext(declaringType2, this));
            this.parameterList      = new ParameterList(this, declaringType2);
        }
Example #22
0
    public static int Main()
    {
        EventInfo            ei = typeof(Test).GetEvent("MyEvent");
        MethodImplAttributes methodImplAttributes = ei.GetAddMethod().GetMethodImplementationFlags();

        if ((methodImplAttributes & MethodImplAttributes.Synchronized) == 0)
        {
            Console.WriteLine("FAILED");
            return(1);
        }

        methodImplAttributes = ei.GetRemoveMethod().GetMethodImplementationFlags();
        if ((methodImplAttributes & MethodImplAttributes.Synchronized) == 0)
        {
            Console.WriteLine("FAILED");
            return(2);
        }

        ei = typeof(S).GetEvent("MyEvent");
        methodImplAttributes = ei.GetAddMethod().GetMethodImplementationFlags();

        if ((methodImplAttributes & MethodImplAttributes.Synchronized) != 0)
        {
            Console.WriteLine("FAILED");
            return(3);
        }

        methodImplAttributes = ei.GetRemoveMethod().GetMethodImplementationFlags();
        if ((methodImplAttributes & MethodImplAttributes.Synchronized) != 0)
        {
            Console.WriteLine("FAILED");
            return(4);
        }

        return(0);
    }
Example #23
0
        /// <summary>
        /// Reads a method body
        /// </summary>
        /// <param name="method">Method</param>
        /// <param name="rva">Method RVA</param>
        /// <param name="implAttrs">Method impl attrs</param>
        /// <param name="gpContext">Generic parameter context</param>
        /// <returns>A <see cref="MethodBody"/> or <c>null</c> if none</returns>
        internal MethodBody ReadMethodBody(MethodDefMD method, RVA rva, MethodImplAttributes implAttrs, GenericParamContext gpContext)
        {
            MethodBody mb;
            var mDec = methodDecrypter;
            if (mDec != null && mDec.GetMethodBody(method.OrigRid, rva, method.Parameters, gpContext, out mb)) {
                var cilBody = mb as CilBody;
                if (cilBody != null)
                    return InitializeBodyFromPdb(cilBody, method.OrigRid);
                return mb;
            }

            if (rva == 0)
                return null;
            var codeType = implAttrs & MethodImplAttributes.CodeTypeMask;
            if (codeType == MethodImplAttributes.IL)
                return InitializeBodyFromPdb(ReadCilBody(method.Parameters, rva, gpContext), method.OrigRid);
            if (codeType == MethodImplAttributes.Native)
                return new NativeMethodBody(rva);
            return null;
        }
Example #24
0
 private void SetMethodCodeTypeAttribute(MethodImplAttributes attribute, bool value)
 {
     ImplAttributes = (MethodImplAttributes)((uint)ImplAttributes).SetMaskedAttribute((uint)MethodImplAttributes.CodeTypeMask,
                                                                                      (uint)attribute, value);
 }
Example #25
0
		public void SetImplementationFlags(MethodImplAttributes attributes)
		{
			implFlags = attributes;
		}
Example #26
0
		private void SetMethodImplAttribute(CustomAttributeBuilder customBuilder)
		{
			MethodImplOptions opt;
			switch (customBuilder.Constructor.ParameterCount)
			{
				case 0:
					opt = 0;
					break;
				case 1:
					{
						object val = customBuilder.GetConstructorArgument(0);
						if (val is short)
						{
							opt = (MethodImplOptions)(short)val;
						}
						else if (val is int)
						{
							opt = (MethodImplOptions)(int)val;
						}
						else
						{
							opt = (MethodImplOptions)val;
						}
						break;
					}
				default:
					throw new NotSupportedException();
			}
			MethodCodeType? type = customBuilder.GetFieldValue<MethodCodeType>("MethodCodeType");
			implFlags = (MethodImplAttributes)opt;
			if (type.HasValue)
			{
				implFlags |= (MethodImplAttributes)type;
			}
		}
        public static StringBuilder AppendMethodImplAttributes(StringBuilder sb, MethodImplAttributes attributes)
        {
            string codeType;
            switch (attributes & MethodImplAttributes.CodeTypeMask)
            {
                case MethodImplAttributes.IL: codeType = "cil"; break;
                case MethodImplAttributes.OPTIL: codeType = "optil"; break;
                case MethodImplAttributes.Runtime: codeType = "runtime"; break;
                case MethodImplAttributes.Native: codeType = "native"; break;

                default:
                    throw new InvalidOperationException();
            }

            sb.Append(codeType);
            sb.Append(" ");
            sb.Append((attributes & MethodImplAttributes.Unmanaged) == MethodImplAttributes.Unmanaged ? "unmanaged" : "managed");

            if ((attributes & MethodImplAttributes.PreserveSig) != 0) sb.Append(" preservesig");
            if ((attributes & MethodImplAttributes.ForwardRef) != 0) sb.Append(" forwardref");
            if ((attributes & MethodImplAttributes.InternalCall) != 0) sb.Append(" internalcall");
            if ((attributes & MethodImplAttributes.Synchronized) != 0) sb.Append(" synchronized");
            if ((attributes & MethodImplAttributes.NoInlining) != 0) sb.Append(" noinlining");
            if ((attributes & MethodImplAttributes.AggressiveInlining) != 0) sb.Append(" aggressiveinlining");
            if ((attributes & MethodImplAttributes.NoOptimization) != 0) sb.Append(" nooptimization");

            return sb;
        }
Example #28
0
        public MethodDefinitionHandle AddMethodDefinition(
            MethodAttributes attributes, 
            MethodImplAttributes implAttributes,
            StringHandle name,
            BlobHandle signature,
            int bodyOffset,
            ParameterHandle paramList)
        {
            _methodDefTable.Add(new MethodRow
            {
                Flags = (ushort)attributes,
                ImplFlags = (ushort)implAttributes,
                Name = name,
                Signature = signature,
                BodyOffset = bodyOffset,
                ParamList = (uint)MetadataTokens.GetRowNumber(paramList)
            });

            return MetadataTokens.MethodDefinitionHandle(_methodDefTable.Count);
        }
Example #29
0
        internal static string ToString(MethodImplAttributes flags)
        {
            var sb = new StringBuilder();

            switch ((flags & MethodImplAttributes.CodeTypeMask))
            {
            case MethodImplAttributes.IL: sb.Append("IL"); break;

            case MethodImplAttributes.Native: sb.Append("Native"); break;

            case MethodImplAttributes.OPTIL: sb.Append("OPTIL"); break;

            case MethodImplAttributes.Runtime: sb.Append("Runtime"); break;
            }

            if ((flags & MethodImplAttributes.Unmanaged) != 0)
            {
                sb.Append(" | Unmanaged");
            }
            else
            {
                sb.Append(" | Managed");
            }

            if ((flags & MethodImplAttributes.ForwardRef) != 0)
            {
                sb.Append(" | ForwardRef");
            }

            if ((flags & MethodImplAttributes.PreserveSig) != 0)
            {
                sb.Append(" | PreserveSig");
            }

            if ((flags & MethodImplAttributes.InternalCall) != 0)
            {
                sb.Append(" | InternalCall");
            }

            if ((flags & MethodImplAttributes.Synchronized) != 0)
            {
                sb.Append(" | Synchronized");
            }

            if ((flags & MethodImplAttributes.NoInlining) != 0)
            {
                sb.Append(" | NoInlining");
            }

            if ((flags & MethodImplAttributes.AggressiveInlining) != 0)
            {
                sb.Append(" | AggressiveInlining");
            }

            if ((flags & MethodImplAttributes.NoOptimization) != 0)
            {
                sb.Append(" | NoOptimization");
            }

            return(sb.ToString());
        }
 public BodyState(MethodDef method, bool isBodyModified)
 {
     this.body           = method.MethodBody;
     this.implAttributes = method.ImplAttributes;
     this.isBodyModified = isBodyModified;
 }
Example #31
0
		public void SetImplementationFlags (MethodImplAttributes attributes)
		{
			if (type.is_created)
				throw not_after_created ();

			iattrs = attributes;
		}
        } // Read

        public static uint Read(this NativeReader reader, uint offset, out MethodImplAttributes value)
        {
            uint ivalue;
            offset = reader.DecodeUnsigned(offset, out ivalue);
            value = (MethodImplAttributes)ivalue;
            return offset;
        } // Read
 public BodyState(Emit.MethodBody body, MethodImplAttributes implAttributes, bool isBodyModified)
 {
     this.body           = body;
     this.implAttributes = implAttributes;
     this.isBodyModified = isBodyModified;
 }
Example #34
0
		public static unsafe bool GetMethodAttributes(IMetaDataImport mdi, uint token, out MethodAttributes dwAttr, out MethodImplAttributes dwImplFlags) {
			dwAttr = 0;
			dwImplFlags = 0;
			if (mdi == null)
				return false;
			uint dwAttr2, dwImplFlags2;
			int hr = mdi.GetMethodProps(token, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero, new IntPtr(&dwAttr2), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, new IntPtr(&dwImplFlags2));
			if (hr < 0)
				return false;
			dwAttr = (MethodAttributes)dwAttr2;
			dwImplFlags = (MethodImplAttributes)dwImplFlags2;
			return true;
		}
Example #35
0
        public IEnumerable <IAttribute> GetAttributes()
        {
            var b = new AttributeListBuilder(module);

            var metadata = module.metadata;
            var def      = metadata.GetMethodDefinition(handle);
            MethodImplAttributes implAttributes = def.ImplAttributes & ~MethodImplAttributes.CodeTypeMask;

            #region DllImportAttribute
            var info = def.GetImport();
            if ((attributes & MethodAttributes.PinvokeImpl) == MethodAttributes.PinvokeImpl && !info.Module.IsNil)
            {
                var dllImport = new AttributeBuilder(module, KnownAttribute.DllImport);
                dllImport.AddFixedArg(KnownTypeCode.String,
                                      metadata.GetString(metadata.GetModuleReference(info.Module).Name));

                var importAttrs = info.Attributes;
                if ((importAttrs & MethodImportAttributes.BestFitMappingDisable) == MethodImportAttributes.BestFitMappingDisable)
                {
                    dllImport.AddNamedArg("BestFitMapping", KnownTypeCode.Boolean, false);
                }
                if ((importAttrs & MethodImportAttributes.BestFitMappingEnable) == MethodImportAttributes.BestFitMappingEnable)
                {
                    dllImport.AddNamedArg("BestFitMapping", KnownTypeCode.Boolean, true);
                }

                CallingConvention callingConvention;
                switch (info.Attributes & MethodImportAttributes.CallingConventionMask)
                {
                case 0:
                    Debug.WriteLine($"P/Invoke calling convention not set on: {this}");
                    callingConvention = 0;
                    break;

                case MethodImportAttributes.CallingConventionCDecl:
                    callingConvention = CallingConvention.Cdecl;
                    break;

                case MethodImportAttributes.CallingConventionFastCall:
                    callingConvention = CallingConvention.FastCall;
                    break;

                case MethodImportAttributes.CallingConventionStdCall:
                    callingConvention = CallingConvention.StdCall;
                    break;

                case MethodImportAttributes.CallingConventionThisCall:
                    callingConvention = CallingConvention.ThisCall;
                    break;

                case MethodImportAttributes.CallingConventionWinApi:
                    callingConvention = CallingConvention.Winapi;
                    break;

                default:
                    throw new NotSupportedException("unknown calling convention");
                }
                if (callingConvention != CallingConvention.Winapi)
                {
                    var callingConventionType = FindInteropType(nameof(CallingConvention));
                    dllImport.AddNamedArg("CallingConvention", callingConventionType, (int)callingConvention);
                }

                CharSet charSet = CharSet.None;
                switch (info.Attributes & MethodImportAttributes.CharSetMask)
                {
                case MethodImportAttributes.CharSetAnsi:
                    charSet = CharSet.Ansi;
                    break;

                case MethodImportAttributes.CharSetAuto:
                    charSet = CharSet.Auto;
                    break;

                case MethodImportAttributes.CharSetUnicode:
                    charSet = CharSet.Unicode;
                    break;
                }
                if (charSet != CharSet.None)
                {
                    var charSetType = FindInteropType(nameof(CharSet));
                    dllImport.AddNamedArg("CharSet", charSetType, (int)charSet);
                }

                if (!info.Name.IsNil && info.Name != def.Name)
                {
                    dllImport.AddNamedArg("EntryPoint", KnownTypeCode.String, metadata.GetString(info.Name));
                }

                if ((info.Attributes & MethodImportAttributes.ExactSpelling) == MethodImportAttributes.ExactSpelling)
                {
                    dllImport.AddNamedArg("ExactSpelling", KnownTypeCode.Boolean, true);
                }

                if ((implAttributes & MethodImplAttributes.PreserveSig) == MethodImplAttributes.PreserveSig)
                {
                    implAttributes &= ~MethodImplAttributes.PreserveSig;
                }
                else
                {
                    dllImport.AddNamedArg("PreserveSig", KnownTypeCode.Boolean, false);
                }

                if ((info.Attributes & MethodImportAttributes.SetLastError) == MethodImportAttributes.SetLastError)
                {
                    dllImport.AddNamedArg("SetLastError", KnownTypeCode.Boolean, true);
                }

                if ((info.Attributes & MethodImportAttributes.ThrowOnUnmappableCharDisable) == MethodImportAttributes.ThrowOnUnmappableCharDisable)
                {
                    dllImport.AddNamedArg("ThrowOnUnmappableChar", KnownTypeCode.Boolean, false);
                }
                if ((info.Attributes & MethodImportAttributes.ThrowOnUnmappableCharEnable) == MethodImportAttributes.ThrowOnUnmappableCharEnable)
                {
                    dllImport.AddNamedArg("ThrowOnUnmappableChar", KnownTypeCode.Boolean, true);
                }

                b.Add(dllImport.Build());
            }
            #endregion

            #region PreserveSigAttribute
            if (implAttributes == MethodImplAttributes.PreserveSig)
            {
                b.Add(KnownAttribute.PreserveSig);
                implAttributes = 0;
            }
            #endregion

            #region MethodImplAttribute
            if (implAttributes != 0)
            {
                b.Add(KnownAttribute.MethodImpl,
                      new TopLevelTypeName("System.Runtime.CompilerServices", nameof(MethodImplOptions)),
                      (int)implAttributes
                      );
            }
            #endregion

            b.Add(def.GetCustomAttributes(), symbolKind);
            b.AddSecurityAttributes(def.GetDeclarativeSecurityAttributes());

            return(b.Build());
        }
Example #36
0
 public void SetImplementationFlags(MethodImplAttributes attributes)
 {
     m_methodBuilder.SetImplementationFlags(attributes);
 }
Example #37
0
 public EditedMethodBodyUpdater(Lazy <IMethodAnnotations> methodAnnotations, ModuleDocumentNode modNode, MethodDef originalMethod, Emit.MethodBody newBody, MethodImplAttributes newImplAttributes, CustomAttribute[] newCustomAttributes, DeclSecurity[] newDeclSecurities)
 {
     this.methodAnnotations = methodAnnotations;
     this.ownerNode         = modNode.Context.DocumentTreeView.FindNode(originalMethod);
     if (ownerNode == null)
     {
         throw new InvalidOperationException();
     }
     this.method            = originalMethod;
     this.originalBodyState = new BodyState(originalMethod, methodAnnotations.Value.IsBodyModified(method));
     this.newBodyState      = new BodyState(newBody, newImplAttributes, newCustomAttributes, newDeclSecurities, true);
 }
Example #38
0
		public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
		{
			if (customBuilder == null)
				throw new ArgumentNullException ("customBuilder");

			switch (customBuilder.Ctor.ReflectedType.FullName) {
				case "System.Runtime.CompilerServices.MethodImplAttribute":
					byte[] data = customBuilder.Data;
					int impla; // the (stupid) ctor takes a short or an int ... 
					impla = (int)data [2];
					impla |= ((int)data [3]) << 8;
					iattrs |= (MethodImplAttributes)impla;
					return;

				case "System.Runtime.InteropServices.DllImportAttribute":
					CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
					bool preserveSig = true;

					/*
					 * It would be easier to construct a DllImportAttribute from
					 * the custom attribute builder, but the DllImportAttribute 
					 * does not contain all the information required here, ie.
					 * - some parameters, like BestFitMapping has three values
					 *   ("on", "off", "missing"), but DllImportAttribute only
					 *   contains two (on/off).
					 * - PreserveSig is true by default, while it is false by
					 *   default in DllImportAttribute.
					 */

					pi_dll = (string)attr.ctorArgs[0];
					if (pi_dll == null || pi_dll.Length == 0)
						throw new ArgumentException ("DllName cannot be empty");

					native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;

					for (int i = 0; i < attr.namedParamNames.Length; ++i) {
						string name = attr.namedParamNames [i];
						object value = attr.namedParamValues [i];

						if (name == "CallingConvention")
							native_cc = (CallingConvention)value;
						else if (name == "CharSet")
							charset = (CharSet)value;
						else if (name == "EntryPoint")
							pi_entry = (string)value;
						else if (name == "ExactSpelling")
							ExactSpelling = (bool)value;
						else if (name == "SetLastError")
							SetLastError = (bool)value;
						else if (name == "PreserveSig")
							preserveSig = (bool)value;
					else if (name == "BestFitMapping")
						BestFitMapping = (bool)value;
					else if (name == "ThrowOnUnmappableChar")
						ThrowOnUnmappableChar = (bool)value;
					}

					attrs |= MethodAttributes.PinvokeImpl;
					if (preserveSig)
						iattrs |= MethodImplAttributes.PreserveSig;
					return;

				case "System.Runtime.InteropServices.PreserveSigAttribute":
					iattrs |= MethodImplAttributes.PreserveSig;
					return;
				case "System.Runtime.CompilerServices.SpecialNameAttribute":
					attrs |= MethodAttributes.SpecialName;
					return;
				case "System.Security.SuppressUnmanagedCodeSecurityAttribute":
					attrs |= MethodAttributes.HasSecurity;
					break;
			}

			if (cattrs != null) {
				CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
				cattrs.CopyTo (new_array, 0);
				new_array [cattrs.Length] = customBuilder;
				cattrs = new_array;
			} else {
				cattrs = new CustomAttributeBuilder [1];
				cattrs [0] = customBuilder;
			}
		}
Example #39
0
		internal void SetDllImportPseudoCustomAttribute(string dllName, string entryName, CallingConvention? nativeCallConv, CharSet? nativeCharSet,
			bool? bestFitMapping, bool? throwOnUnmappableChar, bool? setLastError, bool? preserveSig, bool? exactSpelling)
		{
			const short NoMangle = 0x0001;
			const short CharSetMask = 0x0006;
			const short CharSetNotSpec = 0x0000;
			const short CharSetAnsi = 0x0002;
			const short CharSetUnicode = 0x0004;
			const short CharSetAuto = 0x0006;
			const short SupportsLastError = 0x0040;
			const short CallConvMask = 0x0700;
			const short CallConvWinapi = 0x0100;
			const short CallConvCdecl = 0x0200;
			const short CallConvStdcall = 0x0300;
			const short CallConvThiscall = 0x0400;
			const short CallConvFastcall = 0x0500;
			// non-standard flags
			const short BestFitOn = 0x0010;
			const short BestFitOff = 0x0020;
			const short CharMapErrorOn = 0x1000;
			const short CharMapErrorOff = 0x2000;
			short flags = CharSetNotSpec | CallConvWinapi;
			if (bestFitMapping.HasValue)
			{
				flags |= bestFitMapping.Value ? BestFitOn : BestFitOff;
			}
			if (throwOnUnmappableChar.HasValue)
			{
				flags |= throwOnUnmappableChar.Value ? CharMapErrorOn : CharMapErrorOff;
			}
			if (nativeCallConv.HasValue)
			{
				flags &= ~CallConvMask;
				switch (nativeCallConv.Value)
				{
					case System.Runtime.InteropServices.CallingConvention.Cdecl:
						flags |= CallConvCdecl;
						break;
					case System.Runtime.InteropServices.CallingConvention.FastCall:
						flags |= CallConvFastcall;
						break;
					case System.Runtime.InteropServices.CallingConvention.StdCall:
						flags |= CallConvStdcall;
						break;
					case System.Runtime.InteropServices.CallingConvention.ThisCall:
						flags |= CallConvThiscall;
						break;
					case System.Runtime.InteropServices.CallingConvention.Winapi:
						flags |= CallConvWinapi;
						break;
				}
			}
			if (nativeCharSet.HasValue)
			{
				flags &= ~CharSetMask;
				switch (nativeCharSet.Value)
				{
					case CharSet.Ansi:
					case CharSet.None:
						flags |= CharSetAnsi;
						break;
					case CharSet.Auto:
						flags |= CharSetAuto;
						break;
					case CharSet.Unicode:
						flags |= CharSetUnicode;
						break;
				}
			}
			if (exactSpelling.HasValue && exactSpelling.Value)
			{
				flags |= NoMangle;
			}
			if (!preserveSig.HasValue || preserveSig.Value)
			{
				implFlags |= MethodImplAttributes.PreserveSig;
			}
			if (setLastError.HasValue && setLastError.Value)
			{
				flags |= SupportsLastError;
			}
			ImplMapTable.Record rec = new ImplMapTable.Record();
			rec.MappingFlags = flags;
			rec.MemberForwarded = pseudoToken;
			rec.ImportName = this.ModuleBuilder.Strings.Add(entryName ?? name);
			rec.ImportScope = this.ModuleBuilder.ModuleRef.FindOrAddRecord(dllName == null ? 0 : this.ModuleBuilder.Strings.Add(dllName));
			this.ModuleBuilder.ImplMap.AddRecord(rec);
		}
Example #40
0
 public void SetImplementationFlags(MethodImplAttributes attributes)
 {
     throw new NotSupportedException();
 }
Example #41
0
		public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
		{
			Universe u = this.ModuleBuilder.universe;
			Type type = customBuilder.Constructor.DeclaringType;
			if (type == u.System_Runtime_InteropServices_DllImportAttribute)
			{
				attributes |= MethodAttributes.PinvokeImpl;
				SetDllImportPseudoCustomAttribute(customBuilder.DecodeBlob(this.Module.Assembly));
			}
			else if (type == u.System_Runtime_CompilerServices_MethodImplAttribute)
			{
				SetMethodImplAttribute(customBuilder.DecodeBlob(this.Module.Assembly));
			}
			else if (type == u.System_Runtime_InteropServices_PreserveSigAttribute)
			{
				implFlags |= MethodImplAttributes.PreserveSig;
			}
			else if (type == u.System_Runtime_CompilerServices_SpecialNameAttribute)
			{
				attributes |= MethodAttributes.SpecialName;
			}
			else
			{
				if (type == u.System_Security_SuppressUnmanagedCodeSecurityAttribute)
				{
					attributes |= MethodAttributes.HasSecurity;
				}
				this.ModuleBuilder.SetCustomAttribute(pseudoToken, customBuilder);
			}
		}
Example #42
0
 internal static extern void SetMethodImpl(RuntimeModule module, int tkMethod, MethodImplAttributes MethodImplAttributes);
Example #43
0
 private bool GetMethodCodeTypeAttribute(MethodImplAttributes attribute)
 {
     return(((uint)ImplAttributes).GetMaskedAttribute((uint)MethodImplAttributes.CodeTypeMask,
                                                      (uint)attribute));
 }
Example #44
0
 private static void AddString(StringBuilder buffer, MethodImplAttributes source, MethodImplAttributes flag, string stringified)
 {
     // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
     if ((source & flag) != 0)
     {
         buffer.Append(' ').Append(stringified);
     }
 }
 public MethodRow CreateMethodRow(RVA _rVA, MethodImplAttributes _implFlags, MethodAttributes _flags, uint _name, uint _signature, uint _paramList)
 {
     MethodRow row = new MethodRow ();
     row.RVA = _rVA;
     row.ImplFlags = _implFlags;
     row.Flags = _flags;
     row.Name = _name;
     row.Signature = _signature;
     row.ParamList = _paramList;
     return row;
 }
Example #46
0
 bool GetFlagValue(MethodImplAttributes flag) => (ImplAttributes & flag) != 0;
Example #47
0
 public CorMethodInfo(CorType ownerType, uint token, string name, MethodSig methodSig, MethodAttributes attrs, MethodImplAttributes implAttrs, bool compilerGeneratedAttribute)
 {
     OwnerType                  = ownerType;
     Token                      = token;
     Name                       = name;
     MethodSig                  = methodSig;
     MethodAttributes           = attrs;
     MethodImplAttributes       = implAttrs;
     CompilerGeneratedAttribute = compilerGeneratedAttribute;
 }
Example #48
0
        public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
        {
            if (customBuilder == null)
            {
                throw new ArgumentNullException("customBuilder");
            }

            switch (customBuilder.Ctor.ReflectedType.FullName)
            {
            case "System.Runtime.CompilerServices.MethodImplAttribute":
                byte[] data = customBuilder.Data;
                int    impla;                      // the (stupid) ctor takes a short or an int ...
                impla   = (int)data [2];
                impla  |= ((int)data [3]) << 8;
                iattrs |= (MethodImplAttributes)impla;
                return;

            case "System.Runtime.InteropServices.DllImportAttribute":
                CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr(customBuilder);
                bool preserveSig = true;

                /*
                 * It would be easier to construct a DllImportAttribute from
                 * the custom attribute builder, but the DllImportAttribute
                 * does not contain all the information required here, ie.
                 * - some parameters, like BestFitMapping has three values
                 *   ("on", "off", "missing"), but DllImportAttribute only
                 *   contains two (on/off).
                 * - PreserveSig is true by default, while it is false by
                 *   default in DllImportAttribute.
                 */

                pi_dll = (string)attr.ctorArgs[0];
                if (pi_dll == null || pi_dll.Length == 0)
                {
                    throw new ArgumentException("DllName cannot be empty");
                }

                native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;

                for (int i = 0; i < attr.namedParamNames.Length; ++i)
                {
                    string name  = attr.namedParamNames [i];
                    object value = attr.namedParamValues [i];

                    if (name == "CallingConvention")
                    {
                        native_cc = (CallingConvention)value;
                    }
                    else if (name == "CharSet")
                    {
                        charset = (CharSet)value;
                    }
                    else if (name == "EntryPoint")
                    {
                        pi_entry = (string)value;
                    }
                    else if (name == "ExactSpelling")
                    {
                        ExactSpelling = (bool)value;
                    }
                    else if (name == "SetLastError")
                    {
                        SetLastError = (bool)value;
                    }
                    else if (name == "PreserveSig")
                    {
                        preserveSig = (bool)value;
                    }
                    else if (name == "BestFitMapping")
                    {
                        BestFitMapping = (bool)value;
                    }
                    else if (name == "ThrowOnUnmappableChar")
                    {
                        ThrowOnUnmappableChar = (bool)value;
                    }
                }

                attrs |= MethodAttributes.PinvokeImpl;
                if (preserveSig)
                {
                    iattrs |= MethodImplAttributes.PreserveSig;
                }
                return;

            case "System.Runtime.InteropServices.PreserveSigAttribute":
                iattrs |= MethodImplAttributes.PreserveSig;
                return;

            case "System.Runtime.CompilerServices.SpecialNameAttribute":
                attrs |= MethodAttributes.SpecialName;
                return;

            case "System.Security.SuppressUnmanagedCodeSecurityAttribute":
                attrs |= MethodAttributes.HasSecurity;
                break;
            }

            if (cattrs != null)
            {
                CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
                cattrs.CopyTo(new_array, 0);
                new_array [cattrs.Length] = customBuilder;
                cattrs = new_array;
            }
            else
            {
                cattrs     = new CustomAttributeBuilder [1];
                cattrs [0] = customBuilder;
            }
        }
Example #49
0
		public void SetImplementationFlags (MethodImplAttributes attributes)
		{
			RejectIfCreated ();
			iattrs = attributes;
		}
Example #50
0
        internal void SetDllImportPseudoCustomAttribute(string dllName, string entryName, CallingConvention?nativeCallConv, CharSet?nativeCharSet,
                                                        bool?bestFitMapping, bool?throwOnUnmappableChar, bool?setLastError, bool?preserveSig, bool?exactSpelling)
        {
            const short NoMangle          = 0x0001;
            const short CharSetMask       = 0x0006;
            const short CharSetNotSpec    = 0x0000;
            const short CharSetAnsi       = 0x0002;
            const short CharSetUnicode    = 0x0004;
            const short CharSetAuto       = 0x0006;
            const short SupportsLastError = 0x0040;
            const short CallConvMask      = 0x0700;
            const short CallConvWinapi    = 0x0100;
            const short CallConvCdecl     = 0x0200;
            const short CallConvStdcall   = 0x0300;
            const short CallConvThiscall  = 0x0400;
            const short CallConvFastcall  = 0x0500;
            // non-standard flags
            const short BestFitOn       = 0x0010;
            const short BestFitOff      = 0x0020;
            const short CharMapErrorOn  = 0x1000;
            const short CharMapErrorOff = 0x2000;
            short       flags           = CharSetNotSpec | CallConvWinapi;

            if (bestFitMapping.HasValue)
            {
                flags |= bestFitMapping.Value ? BestFitOn : BestFitOff;
            }
            if (throwOnUnmappableChar.HasValue)
            {
                flags |= throwOnUnmappableChar.Value ? CharMapErrorOn : CharMapErrorOff;
            }
            if (nativeCallConv.HasValue)
            {
                flags &= ~CallConvMask;
                switch (nativeCallConv.Value)
                {
                case System.Runtime.InteropServices.CallingConvention.Cdecl:
                    flags |= CallConvCdecl;
                    break;

                case System.Runtime.InteropServices.CallingConvention.FastCall:
                    flags |= CallConvFastcall;
                    break;

                case System.Runtime.InteropServices.CallingConvention.StdCall:
                    flags |= CallConvStdcall;
                    break;

                case System.Runtime.InteropServices.CallingConvention.ThisCall:
                    flags |= CallConvThiscall;
                    break;

                case System.Runtime.InteropServices.CallingConvention.Winapi:
                    flags |= CallConvWinapi;
                    break;
                }
            }
            if (nativeCharSet.HasValue)
            {
                flags &= ~CharSetMask;
                switch (nativeCharSet.Value)
                {
                case CharSet.Ansi:
                case CharSet.None:
                    flags |= CharSetAnsi;
                    break;

                case CharSet.Auto:
                    flags |= CharSetAuto;
                    break;

                case CharSet.Unicode:
                    flags |= CharSetUnicode;
                    break;
                }
            }
            if (exactSpelling.HasValue && exactSpelling.Value)
            {
                flags |= NoMangle;
            }
            if (!preserveSig.HasValue || preserveSig.Value)
            {
                implFlags |= MethodImplAttributes.PreserveSig;
            }
            if (setLastError.HasValue && setLastError.Value)
            {
                flags |= SupportsLastError;
            }
            ImplMapTable.Record rec = new ImplMapTable.Record();
            rec.MappingFlags    = flags;
            rec.MemberForwarded = pseudoToken;
            rec.ImportName      = this.ModuleBuilder.Strings.Add(entryName ?? name);
            rec.ImportScope     = this.ModuleBuilder.ModuleRef.FindOrAddRecord(dllName == null ? 0 : this.ModuleBuilder.Strings.Add(dllName));
            this.ModuleBuilder.ImplMap.AddRecord(rec);
        }
Example #51
0
		public void SetImplementationFlags(MethodImplAttributes attributes)
		{
			methodBuilder.SetImplementationFlags(attributes);
		}
Example #52
0
 public void SetImplementationFlags(MethodImplAttributes attributes)
 {
     implFlags = attributes;
 }
 public void SetImplementationFlags(MethodImplAttributes attributes)
 {
     ConstructorBuilder.SetImplementationFlags(attributes);
 }
Example #54
0
 bool GetFlagValue(MethodImplAttributes flag)
 {
     return((ImplAttributes & flag) != 0);
 }
Example #55
0
        (string methodName, DkmClrCompilationResultFlags flags) AddMethod(TypeSig type, int index, bool isLocal)
        {
            var methodName = methodNamePrefix + methodNameIndex++.ToString();

            var callConv = CallingConvention.Default;

            if (sourceMethod.MethodSig.Generic)
            {
                callConv |= CallingConvention.Generic;
            }
            var methodSig = new MethodSig(callConv, sourceMethod.MethodSig.GenParamCount);

            methodSig.RetType = generatedModule.Import(type.RemovePinnedAndModifiers());
            if (methodSig.RetType.IsByRef)
            {
                methodSig.RetType = methodSig.RetType.Next.RemovePinnedAndModifiers();
            }

            if (lastMethodSig != null)
            {
                foreach (var p in lastMethodSig.Params)
                {
                    methodSig.Params.Add(p);
                }
            }
            else
            {
                if (sourceMethod.MethodSig.HasThis)
                {
                    methodSig.Params.Add(generatedModule.Import(sourceMethod.DeclaringType).ToTypeSig());
                }
                foreach (var p in sourceMethod.MethodSig.Params)
                {
                    methodSig.Params.Add(generatedModule.Import(p));
                }
            }

            const MethodImplAttributes methodImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            const MethodAttributes     methodFlags     = MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.ReuseSlot;
            var method = new MethodDefUser(methodName, methodSig, methodImplFlags, methodFlags);

            getLocalsType.Methods.Add(method);

            foreach (var gp in sourceMethod.GenericParameters)
            {
                method.GenericParameters.Add(Clone(gp));
            }

            var body = new CilBody();

            method.Body     = body;
            body.InitLocals = true;
            if (sourceMethod.Body != null)
            {
                foreach (var l in sourceMethod.Body.Variables)
                {
                    body.Variables.Add(new Local(generatedModule.Import(l.Type), l.Name));
                }
            }
            body.Instructions.Add(CreateLoadVariable(method, body.Variables, index, isLocal));
            if (type.RemovePinnedAndModifiers().GetElementType() == ElementType.ByRef)
            {
                body.Instructions.Add(LoadIndirect(type.RemovePinnedAndModifiers().Next.RemovePinnedAndModifiers()));
            }
            body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            lastMethodSig = methodSig;
            var flags = DkmClrCompilationResultFlags.None;

            if (methodSig.RetType.RemovePinnedAndModifiers().GetElementType() == ElementType.Boolean)
            {
                flags |= DkmClrCompilationResultFlags.BoolResult;
            }
            return(methodName, flags);
        }
        public static void Dump(Assembly asm)
        {
            const MethodImplAttributes BadFlags = MethodImplAttributes.InternalCall | MethodImplAttributes.Native | MethodImplAttributes.Unmanaged;
            bool   TypeNeedsPlugs = false;
            bool   firstParam     = true;
            string str            = "";
            string genParams      = "";
            string curDir         = Application.StartupPath + "\\PlugTemplates\\" + asm.GetName().Name + "\\";

            if (!Directory.Exists(Application.StartupPath + "\\PlugTemplates\\"))
            {
                Directory.CreateDirectory(Application.StartupPath + "\\PlugTemplates\\");
            }
            StreamWriter strm = null; // Only set to null to appease the compiler.

            foreach (Type t in asm.GetTypes())
            {
                if (t.BaseType != null && t.BaseType.FullName != "System.MulticastDelegate")
                {
                    foreach (MethodInfo m in t.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly))
                    {
                        if ((m.GetMethodImplementationFlags() & BadFlags) != 0 || (m.Attributes & MethodAttributes.PinvokeImpl) != 0)
                        {
                            if (!TypeNeedsPlugs)
                            {
                                if (!Directory.Exists(curDir))
                                {
                                    Directory.CreateDirectory(curDir);
                                }
                                if (t.Namespace != null)
                                {
                                    if (!Directory.Exists(curDir + t.Namespace.Replace('.', '\\') + "\\"))
                                    {
                                        Directory.CreateDirectory(curDir + t.Namespace.Replace('.', '\\') + "\\");
                                    }
                                }
                                genParams = "";
                                str       = "";
                                if (t.IsGenericTypeDefinition)
                                {
                                    genParams  = "<";
                                    str        = "<"; // This will be used for the typeof target.
                                    firstParam = true;
                                    foreach (Type T in t.GetGenericArguments())
                                    {
                                        if (!firstParam)
                                        {
                                            genParams += ", ";
                                            str       += ", ";
                                        }
                                        genParams += T.Name;
                                        str       += "object";
                                    }
                                    genParams += ">";
                                    str       += ">";
                                }
                                if (t.Namespace != null)
                                {
                                    strm = new StreamWriter(curDir + t.Namespace.Replace('.', '\\') + "\\" + t.Name + "Impl.cs");
                                }
                                else
                                {
                                    strm = new StreamWriter(curDir + "\\" + t.Name + "Impl.cs");
                                }
                                strm.WriteLine("namespace Cosmos.Plugs");
                                strm.WriteLine("{");
                                strm.WriteLine("\t[Cosmos.IL2CPU.Plugs.Plug(Target = typeof(" + t.Namespace + "." + t.Name + str + "), TargetFramework = Cosmos.IL2CPU.Plugs.FrameworkVersion.v4_0)]");
                                strm.WriteLine("\tpublic static class " + t.FullName.Replace('.', '_') + "Impl" + genParams);
                                strm.WriteLine("\t{");
                                TypeNeedsPlugs = true;
                            }
                            strm.WriteLine();
                            str        = "";
                            firstParam = true;
                            if (!m.IsStatic)
                            {
                                if (t.IsValueType && !t.IsEnum) // aka, a struct, instance members are references.
                                {
                                    str += "ref " + t.FullName.Replace('&', '*') + " aThis";
                                }
                                else // Something else, instance members aren't references.
                                {
                                    str += t.FullName.Replace('&', '*') + " aThis";
                                }
                                firstParam = false;
                            }
                            if (m.ContainsGenericParameters)
                            {
                                foreach (ParameterInfo p in m.GetParameters())
                                {
                                    if (!firstParam)
                                    {
                                        str += ", ";
                                    }
                                    if (p.ParameterType.IsGenericType || p.ParameterType.IsGenericParameter || p.ParameterType.IsGenericTypeDefinition)
                                    {
                                        str += p.ParameterType.Name + " " + p.Name;
                                    }
                                    else
                                    {
                                        if (p.ParameterType.FullName != null)
                                        {
                                            str += p.ParameterType.FullName.Replace('&', '*') + " " + p.Name;
                                        }
                                        else
                                        {
                                            str += p.ParameterType.Name.Replace('&', '*') + " " + p.Name;
                                        }
                                    }
                                    firstParam = false;
                                }
                            }
                            else
                            {
                                foreach (ParameterInfo p in m.GetParameters())
                                {
                                    if (!firstParam)
                                    {
                                        str += ", ";
                                    }
                                    str       += p.ParameterType.FullName.Replace('&', '*') + " " + p.Name;
                                    firstParam = false;
                                }
                            }
                            if (m.ReturnType.IsGenericParameter || m.ReturnType.IsGenericType)
                            {
                                strm.WriteLine("\t\tpublic static " + m.ReturnType.Name + " " + m.Name + "(" + str + ")");
                            }
                            else
                            {
                                strm.WriteLine("\t\tpublic static " + m.ReturnType.FullName.Replace('&', '*') + " " + m.Name + "(" + str + ")");
                            }
                            strm.WriteLine("\t\t{");
                            strm.WriteLine("\t\t\tthrow new System.NotImplementedException(\"Method '" + t.FullName + "." + m.Name + "' has not been implemented!\");");
                            strm.WriteLine("\t\t}");
                        }
                    }
                    if (TypeNeedsPlugs)
                    {
                        strm.WriteLine("\t}");
                        strm.WriteLine("}");
                        strm.Flush();
                        strm.Close();
                    }
                    TypeNeedsPlugs = false;
                }
            }
        }
    internal MyConstructorBuilder()
    {
        try
        {
// <Snippet1>
            MethodBuilder myMethodBuilder = null;
            AppDomain     myCurrentDomain = AppDomain.CurrentDomain;
            // Create assembly in current CurrentDomain.
            AssemblyName myAssemblyName = new AssemblyName();
            myAssemblyName.Name = "TempAssembly";
            // Create a dynamic assembly.
            myAssemblyBuilder = myCurrentDomain.DefineDynamicAssembly
                                    (myAssemblyName, AssemblyBuilderAccess.Run);
            // Create a dynamic module in the assembly.
            myModuleBuilder = myAssemblyBuilder.DefineDynamicModule("TempModule", true);
            FieldInfo myFieldInfo2 =
                myModuleBuilder.DefineUninitializedData("myField", 2, FieldAttributes.Public);
            // Create a type in the module.
            TypeBuilder  myTypeBuilder   = myModuleBuilder.DefineType("TempClass", TypeAttributes.Public);
            FieldBuilder myGreetingField = myTypeBuilder.DefineField("Greeting",
                                                                     typeof(String), FieldAttributes.Public);
            Type[] myConstructorArgs = { typeof(String) };
            // Define a constructor of the dynamic class.
            ConstructorBuilder myConstructor = myTypeBuilder.DefineConstructor(
                MethodAttributes.Public, CallingConventions.Standard, myConstructorArgs);
            // Set the method implementation flags for the constructor.
            myConstructor.SetImplementationFlags(MethodImplAttributes.PreserveSig | MethodImplAttributes.Runtime);
            // Get the method implementation flags for the constructor.
            MethodImplAttributes myMethodAttributes = myConstructor.GetMethodImplementationFlags();
            Type myAttributeType = typeof(MethodImplAttributes);
            int  myAttribValue   = (int)myMethodAttributes;
            if (!myAttributeType.IsEnum)
            {
                Console.WriteLine("This is not an Enum");
            }
            // Display the field info names of the retrieved method implementation flags.
            FieldInfo[] myFieldInfo = myAttributeType.GetFields(BindingFlags.Public | BindingFlags.Static);
            Console.WriteLine("The Field info names of the MethodImplAttributes for the constructor are:");
            for (int i = 0; i < myFieldInfo.Length; i++)
            {
                int myFieldValue = (Int32)myFieldInfo[i].GetValue(null);
                if ((myFieldValue & myAttribValue) == myFieldValue)
                {
                    Console.WriteLine("   " + myFieldInfo[i].Name);
                }
            }
// </Snippet1>
            // Add a method to the type.
            myMethodBuilder = myTypeBuilder.DefineMethod
                                  ("HelloWorld", MethodAttributes.Public, null, null);
            // Generate IL for the method.
            ILGenerator myILGenerator2 = myMethodBuilder.GetILGenerator();
            myILGenerator2.EmitWriteLine("Hello World from global");
            myILGenerator2.Emit(OpCodes.Ret);
            myModuleBuilder.CreateGlobalFunctions();
            myType1 = myTypeBuilder.CreateType();
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("The following exception has occurred : " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("The following exception has occurred : " + ex.Message);
        }
    }
Example #58
0
        private static MethodBuilder AddPropertyChangedEvent(TypeBuilder tb)
        {
            var                        eventHandlerType    = typeof(PropertyChangedEventHandler);
            var                        eventArgsConstrInfo = typeof(PropertyChangedEventArgs).GetConstructor(new[] { typeof(string) });
            var                        invokeDelegate      = typeof(PropertyChangedEventHandler).GetMethod("Invoke");
            const string               eventName           = "PropertyChanged";
            const MethodAttributes     eventMethodAttr     = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final | MethodAttributes.SpecialName;
            const MethodImplAttributes eventMethodImpAtr   = MethodImplAttributes.Managed | MethodImplAttributes.Synchronized;

            var fieldBuilder = tb.DefineField(eventName, eventHandlerType, FieldAttributes.Private);

            var eventBuilder = tb.DefineEvent(eventName, EventAttributes.None, eventHandlerType);

            var addMethodBuilder = tb.DefineMethod("add_" + eventName, eventMethodAttr, null, new[] { eventHandlerType });

            addMethodBuilder.SetImplementationFlags(eventMethodImpAtr);
            addMethodBuilder.DefineParameter(1, ParameterAttributes.None, "value");

            var combineInfo = typeof(Delegate).GetMethod("Combine", new[] { typeof(Delegate), typeof(Delegate) });

            var addIL = addMethodBuilder.GetILGenerator();

            addIL.Emit(OpCodes.Ldarg_0);
            addIL.Emit(OpCodes.Ldarg_0);
            addIL.Emit(OpCodes.Ldfld, fieldBuilder);
            addIL.Emit(OpCodes.Ldarg_1);
            addIL.Emit(OpCodes.Call, combineInfo);
            addIL.Emit(OpCodes.Castclass, eventHandlerType);
            addIL.Emit(OpCodes.Stfld, fieldBuilder);
            addIL.Emit(OpCodes.Ret);

            var removeMethodBuilder = tb.DefineMethod("remove_" + eventName,
                                                      eventMethodAttr, null, new[] { eventHandlerType });

            removeMethodBuilder.SetImplementationFlags(eventMethodImpAtr);
            removeMethodBuilder.DefineParameter(1, ParameterAttributes.None, "value");

            var removeInfo = typeof(Delegate).GetMethod("Remove", new[] { typeof(Delegate), typeof(Delegate) });

            var remIL = removeMethodBuilder.GetILGenerator();

            remIL.Emit(OpCodes.Ldarg_0);
            remIL.Emit(OpCodes.Ldarg_0);
            remIL.Emit(OpCodes.Ldfld, fieldBuilder);
            remIL.Emit(OpCodes.Ldarg_1);
            remIL.Emit(OpCodes.Call, removeInfo);
            remIL.Emit(OpCodes.Castclass, eventHandlerType);
            remIL.Emit(OpCodes.Stfld, fieldBuilder);
            remIL.Emit(OpCodes.Ret);

            eventBuilder.SetAddOnMethod(addMethodBuilder);
            eventBuilder.SetRemoveOnMethod(removeMethodBuilder);

            var onExecute = tb.DefineMethod("On" + eventName,
                                            MethodAttributes.Private | MethodAttributes.HideBySig,
                                            null, new[] { typeof(string) });

            onExecute.DefineParameter(1, ParameterAttributes.None, "propName");

            var exeIL         = onExecute.GetILGenerator();
            var lblDelegateOk = exeIL.DefineLabel();

            exeIL.DeclareLocal(typeof(PropertyChangedEventHandler));
            exeIL.Emit(OpCodes.Nop);
            exeIL.Emit(OpCodes.Ldarg_0);
            exeIL.Emit(OpCodes.Ldfld, fieldBuilder);
            exeIL.Emit(OpCodes.Stloc_0);
            exeIL.Emit(OpCodes.Ldloc_0);
            exeIL.Emit(OpCodes.Ldnull);
            exeIL.Emit(OpCodes.Ceq);
            exeIL.Emit(OpCodes.Brtrue, lblDelegateOk);
            exeIL.Emit(OpCodes.Ldloc_0);
            exeIL.Emit(OpCodes.Ldarg_0);
            exeIL.Emit(OpCodes.Ldarg_1);
            exeIL.Emit(OpCodes.Newobj, eventArgsConstrInfo);
            exeIL.Emit(OpCodes.Callvirt, invokeDelegate);
            exeIL.MarkLabel(lblDelegateOk);
            exeIL.Emit(OpCodes.Ret);

            return(onExecute);
        }
Example #59
0
 public void SetImplementationFlags(MethodImplAttributes attributes)
 {
     RejectIfCreated();
     iattrs = attributes;
 }
Example #60
0
 public EditedMethodBody(MethodDef originalMethod, Emit.MethodBody newBody, MethodImplAttributes implAttributes)
 {
     OriginalMethod = originalMethod;
     NewBody        = newBody;
     ImplAttributes = implAttributes;
 }