Exemple #1
0
        /// <summary>
        /// Checks whether a custom attribute exists
        /// </summary>
        /// <param name="provider">Custom attribute provider</param>
        /// <param name="namespace">Namespace of custom attribute</param>
        /// <param name="name">Name of custom attribute</param>
        /// <returns></returns>
        public static bool IsDefined(this IHasCustomAttribute provider, UTF8String @namespace, UTF8String name)
        {
            if (provider == null || provider.CustomAttributes.Count == 0)
            {
                return(false);
            }
            foreach (var ca in provider.CustomAttributes)
            {
                if (ca.AttributeType is TypeRef tr)
                {
                    if (tr.Namespace == @namespace && tr.Name == name)
                    {
                        return(true);
                    }
                    continue;
                }

                if (ca.AttributeType is TypeDef td)
                {
                    if (td.Namespace == @namespace && td.Name == name)
                    {
                        return(true);
                    }
                    continue;
                }
            }
            return(false);
        }
Exemple #2
0
        void CheckCustomAttributes(IDnSpyFile file, IHasCustomAttribute hca, object parent)
        {
            var res = options.Filter.GetResultAttributes(hca);

            if (!res.IsMatch)
            {
                return;
            }
            foreach (var ca in hca.CustomAttributes)
            {
                foreach (var o in ca.ConstructorArguments)
                {
                    if (CheckCA(file, hca, parent, o))
                    {
                        return;
                    }
                }
                foreach (var o in ca.NamedArguments)
                {
                    if (CheckCA(file, hca, parent, o.Argument))
                    {
                        return;
                    }
                }
            }
        }
 private static string FetchAttributeSignature(IHasCustomAttribute mod)
 {
     var confuserAttrib = mod.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == "ConfusedByAttribute");
     if (confuserAttrib == null || !confuserAttrib.HasConstructorArguments)
         return null;
     return confuserAttrib.ConstructorArguments[0].Value.ToString();
 }
Exemple #4
0
 private void AddCustomAttributes(MetadataToken ownerToken, IHasCustomAttribute provider)
 {
     foreach (var attribute in provider.CustomAttributes)
     {
         AddCustomAttribute(ownerToken, attribute);
     }
 }
        string TypeToString(ConvertTypeOptions options, ITypeDefOrRef type, IHasCustomAttribute typeAttributes = null)
        {
            AstType astType = AstBuilder.ConvertType(null, null, type, typeAttributes, options);

            StringWriter w = new StringWriter();

            if (type.TryGetByRefSig() != null)
            {
                ParamDef pd = typeAttributes as ParamDef;
                if (pd != null && (!pd.IsIn && pd.IsOut))
                {
                    w.Write("out ");
                }
                else
                {
                    w.Write("ref ");
                }

                if (astType is ComposedType && ((ComposedType)astType).PointerRank > 0)
                {
                    ((ComposedType)astType).PointerRank--;
                }
            }

            astType.AcceptVisitor(new CSharpOutputVisitor(w, FormattingOptionsFactory.CreateAllman()));
            return(w.ToString());
        }
Exemple #6
0
        void CheckCustomAttributes(IDsDocument file, IHasCustomAttribute hca, object parent)
        {
            var res = options.Filter.GetResultAttributes(hca);

            if (!res.IsMatch)
            {
                return;
            }
            foreach (var ca in hca.CustomAttributes)
            {
                options.CancellationToken.ThrowIfCancellationRequested();
                foreach (var o in ca.ConstructorArguments)
                {
                    options.CancellationToken.ThrowIfCancellationRequested();
                    if (CheckCA(file, hca, parent, o))
                    {
                        return;
                    }
                }
                foreach (var o in ca.NamedArguments)
                {
                    options.CancellationToken.ThrowIfCancellationRequested();
                    if (CheckCA(file, hca, parent, o.Argument))
                    {
                        return;
                    }
                }
            }
        }
Exemple #7
0
        string TypeToString(ITypeDefOrRef type, bool includeNamespace, IHasCustomAttribute typeAttributes = null)
        {
            var output = new StringBuilderDecompilerOutput();

            TypeToString(output, type, includeNamespace, typeAttributes);
            return(output.ToString());
        }
 protected void CopyCustomAttributes(IHasCustomAttribute source, IHasCustomAttribute dest)
 {
     foreach (var sourceCustomAttribute in source.CustomAttributes)
     {
         dest.CustomAttributes.Add(Clone(sourceCustomAttribute));
     }
 }
Exemple #9
0
 private void AddCustomAttributes(IHasCustomAttribute provider)
 {
     foreach (var attribute in provider.CustomAttributes)
     {
         AddCustomAttribute(attribute);
     }
 }
Exemple #10
0
 private void AddCustomAttributes(MetadataToken ownerToken, IHasCustomAttribute provider)
 {
     for (int i = 0; i < provider.CustomAttributes.Count; i++)
     {
         AddCustomAttribute(ownerToken, provider.CustomAttributes[i]);
     }
 }
Exemple #11
0
		public override void WriteToolTip(ITextOutput output, IMemberRef member, IHasCustomAttribute typeAttributes)
		{
			if (!(member is ITypeDefOrRef) && Write(output, member))
				return;

			base.WriteToolTip(output, member, typeAttributes);
		}
Exemple #12
0
        public static CustomAttribute Find(this IHasCustomAttribute provider, UTF8String ns, UTF8String name)
        {
            if (provider == null || provider.CustomAttributes.Count == 0)
            {
                return(null);
            }
            foreach (var ca in provider.CustomAttributes)
            {
                var tr = ca.AttributeType as TypeRef;
                if (tr != null)
                {
                    if (tr.Namespace == ns && tr.Name == name)
                    {
                        return(ca);
                    }
                    continue;
                }

                var td = ca.AttributeType as TypeDef;
                if (td != null)
                {
                    if (td.Namespace == ns && td.Name == name)
                    {
                        return(ca);
                    }
                    continue;
                }
            }
            return(null);
        }
Exemple #13
0
        public override string TypeToString(ITypeDefOrRef t, bool includeNamespace, IHasCustomAttribute attributeProvider = null)
        {
            PlainTextOutput output = new PlainTextOutput();

            t.WriteTo(output, includeNamespace ? ILNameSyntax.TypeName : ILNameSyntax.ShortTypeName);
            return(output.ToString());
        }
Exemple #14
0
        /// <summary>
        /// Converts a type reference into a string. This method is used by the member tree node for parameter and return types.
        /// </summary>
        public string TypeToString(ITypeDefOrRef type, bool includeNamespace, IHasCustomAttribute typeAttributes = null)
        {
            var writer = new StringWriter();
            var output = new PlainTextOutput(writer);

            TypeToString(output, type, includeNamespace, typeAttributes);
            return(writer.ToString());
        }
Exemple #15
0
 static CustomAttribute GetJsonContainerAttribute(IHasCustomAttribute attrs)
 {
     foreach (var attr in attrs.CustomAttributes) {
         if (JsonContainers.Contains(attr.TypeFullName))
             return attr;
     }
     return null;
 }
		IEnumerable<ProtectionSettingsInfo> ReadInfos(IHasCustomAttribute item) {
			foreach (var attr in ReadObfuscationAttributes(item)) {
				ProtectionSettingsInfo info;
				if (!string.IsNullOrEmpty(attr.FeatureName))
					yield return AddRule(attr, null);
				else if (ToInfo(attr, out info))
					yield return info;
			}
		}
        private static string FetchAttributeSignature(IHasCustomAttribute mod)
        {
            var confuserAttrib = mod.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == "ConfusedByAttribute");

            if (confuserAttrib == null || !confuserAttrib.HasConstructorArguments)
            {
                return(null);
            }
            return(confuserAttrib.ConstructorArguments[0].Value.ToString());
        }
        public override FileTreeNodeFilterResult GetResultAttributes(IHasCustomAttribute hca)
        {
            bool isMatch = (flags & VisibleMembersFlags.Attributes) != 0;

            if (!isMatch)
            {
                return(new FileTreeNodeFilterResult(FilterType.Hide, isMatch));
            }
            return(new FileTreeNodeFilterResult(FilterType.Visible, isMatch));
        }
 IEnumerable <ProtectionSettingsInfo> ReadInfos(IHasCustomAttribute item)
 {
     foreach (var attr in ReadObfuscationAttributes(item))
     {
         ProtectionSettingsInfo info;
         if (ToInfo(attr, out info))
         {
             yield return(info);
         }
     }
 }
 private static CustomAttribute GetJsonContainerAttribute(IHasCustomAttribute attrs)
 {
     foreach (var attr in attrs.CustomAttributes)
     {
         if (JsonContainers.Contains(attr.TypeFullName))
         {
             return(attr);
         }
     }
     return(null);
 }
Exemple #21
0
        internal IList <CustomAttribute> GetCustomAttributeCollection(IHasCustomAttribute owner)
        {
            EnsureCustomAttributesInitialized();
            var result = new OwnedCollection <IHasCustomAttribute, CustomAttribute>(owner);

            foreach (uint rid in _customAttributes.GetValues(owner.MetadataToken))
            {
                var attribute = (CustomAttribute)LookupMember(new MetadataToken(TableIndex.CustomAttribute, rid));
                result.Add(attribute);
            }

            return(result);
        }
 internal static ModificationKind?GetModificationKind(this IHasCustomAttribute definition)
 {
     if (definition.CustomAttributes.Find(Dependency) != null || definition.CustomAttributes.Find(Mixin) != null)
     {
         return(ModificationKind.FailIfMissing);
     }
     else if (definition.CustomAttributes.Find(Inject) != null)
     {
         return(ModificationKind.FailIfPresent);
     }
     else if (definition.CustomAttributes.Find(CompilerGenerated) != null || definition is IMemberDef member && member.DeclaringType?.CustomAttributes?.Find(CompilerGenerated) != null)
     {
         return(ModificationKind.CreateIfMissing);
     }
Exemple #23
0
 public static bool IsCompilerGenerated(this IHasCustomAttribute provider)
 {
     if (provider != null && provider.HasCustomAttributes)
     {
         foreach (CustomAttribute a in provider.CustomAttributes)
         {
             if (a.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute")
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Exemple #24
0
        static bool TryGetCAWrite(IHasCustomAttribute hca, IMemberRef member, bool isField, [NotNullWhen(true)] out CustomAttribute?customAttribute)
        {
            customAttribute = null;
            TypeSig?memberType;

            if (isField)
            {
                memberType = ((IField)member).FieldSig?.GetFieldType();
            }
            else
            {
                var property = (PropertyDef)member;
                var propSig  = property.PropertySig;
                if (propSig is null || propSig.Params.Count != 0)
                {
                    return(false);
                }
                memberType = propSig?.GetRetType();
            }
            foreach (var ca in hca.GetCustomAttributes())
            {
                if (!new SigComparer().Equals(ca.AttributeType.GetScopeType(), member.DeclaringType))
                {
                    continue;
                }
                var namedArgs = ca.NamedArguments;
                for (int i = 0; i < namedArgs.Count; i++)
                {
                    var namedArg = namedArgs[i];
                    if (namedArg.IsField != isField)
                    {
                        continue;
                    }
                    if (namedArg.Name != member.Name)
                    {
                        continue;
                    }
                    if (!new SigComparer().Equals(namedArg.Type, memberType))
                    {
                        continue;
                    }

                    customAttribute = ca;
                    return(true);
                }
            }

            return(false);
        }
Exemple #25
0
        private void AddPatchAttributeToMethod(ModuleDef module, IHasCustomAttribute target, Tuple <int, int> opcodesRange)
        {
            UpdateExistingPatchAttributes(target, opcodesRange);

            var patchAttribute = module.Types.FirstOrDefault(t => t.FullName == typeof(PatchAttribute).FullName);

            if (patchAttribute != null)
            {
                target.CustomAttributes.Add(new CustomAttribute(patchAttribute.FindMethod(".ctor"), new List <CAArgument>
                {
                    new CAArgument(module.CorLibTypes.String, _patchName),
                    new CAArgument(module.CorLibTypes.Int32, opcodesRange.Item1),
                    new CAArgument(module.CorLibTypes.Int32, opcodesRange.Item2)
                }));
            }
        }
Exemple #26
0
        /// <summary>
        /// Finds all custom attributes that were assigned to a metadata member that match a particular namespace and name.
        /// </summary>
        /// <param name="self">The metadata member.</param>
        /// <param name="ns">The namespace of the attribute type.</param>
        /// <param name="name">The name of the attribute type.</param>
        /// <returns>The matching attributes.</returns>
        public static IEnumerable <CustomAttribute> FindCustomAttributes(this IHasCustomAttribute self, string ns, string name)
        {
            for (int i = 0; i < self.CustomAttributes.Count; i++)
            {
                var attribute     = self.CustomAttributes[i];
                var declaringType = attribute.Constructor?.DeclaringType;
                if (declaringType is null)
                {
                    continue;
                }

                if (declaringType.IsTypeOf(ns, name))
                {
                    yield return(attribute);
                }
            }
        }
Exemple #27
0
		void CheckCustomAttributes(IDsDocument file, IHasCustomAttribute hca, object parent) {
			var res = options.Filter.GetResultAttributes(hca);
			if (!res.IsMatch)
				return;
			foreach (var ca in hca.CustomAttributes) {
				options.CancellationToken.ThrowIfCancellationRequested();
				foreach (var o in ca.ConstructorArguments) {
					options.CancellationToken.ThrowIfCancellationRequested();
					if (CheckCA(file, hca, parent, o))
						return;
				}
				foreach (var o in ca.NamedArguments) {
					options.CancellationToken.ThrowIfCancellationRequested();
					if (CheckCA(file, hca, parent, o.Argument))
						return;
				}
			}
		}
Exemple #28
0
		bool CheckCA(IDsDocument file, IHasCustomAttribute hca, object parent, CAArgument o) {
			var value = o.Value;
			var u = value as UTF8String;
			if (!ReferenceEquals(u, null))
				value = u.String;
			if (!IsMatch(null, value))
				return false;
			options.OnMatch(new SearchResult {
				Context = options.Context,
				Object = hca,
				NameObject = hca,
				ObjectImageReference = GetImageReference(hca),
				LocationObject = parent is string ? new NamespaceSearchResult((string)parent) : parent,
				LocationImageReference = GetImageReference(parent),
				Document = file,
			});
			return true;
		}
 // Remove the attribute Xenocode adds that has an invalid ctor
 void removeInvalidAttributes(IHasCustomAttribute hca)
 {
     if (!CanRemoveTypes)
     {
         return;
     }
     if (hca == null)
     {
         return;
     }
     for (int i = hca.CustomAttributes.Count - 1; i >= 0; i--)
     {
         var ca = hca.CustomAttributes[i];
         if (ca.Constructor == null)
         {
             hca.CustomAttributes.RemoveAt(i);
         }
     }
 }
Exemple #30
0
        /// <summary>
        /// Determines whether a metadata member is assigned an attributes that match a particular namespace and name.
        /// </summary>
        /// <param name="self">The metadata member.</param>
        /// <param name="ns">The namespace of the attribute type.</param>
        /// <param name="name">The name of the attribute type.</param>
        /// <returns>The matching attributes.</returns>
        public static bool HasCustomAttribute(this IHasCustomAttribute self, string ns, string name)
        {
            // Note: we are not using the FindCustomAttributes to avoid allocations.

            for (int i = 0; i < self.CustomAttributes.Count; i++)
            {
                var attribute     = self.CustomAttributes[i];
                var declaringType = attribute.Constructor?.DeclaringType;
                if (declaringType is null)
                {
                    continue;
                }

                if (declaringType.IsTypeOf(ns, name))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #31
0
        private void UpdateExistingPatchAttributes(IHasCustomAttribute target, Tuple <int, int> opcodesRange)
        {
            var patchAttributes = target.CustomAttributes.Where(a => a.TypeFullName == typeof(PatchAttribute).FullName).ToList();

            foreach (var attr in patchAttributes.Where(a => a.HasConstructorArguments && a.ConstructorArguments.Count >= 2))
            {
                var fromArgument = attr.ConstructorArguments[1];
                if (_injectionPoint == InjectionPoint.Prefix)
                {
                    attr.ConstructorArguments[1] = new CAArgument(fromArgument.Type, (int)fromArgument.Value + opcodesRange.Item2);
                }
                // update only attributes where fromIndex >= this.fromIndex + this.instructionsCount
                else if (_injectionPoint == InjectionPoint.Postfix)
                {
                    if ((int)fromArgument.Value >= opcodesRange.Item1 + opcodesRange.Item2)
                    {
                        attr.ConstructorArguments[1] = new CAArgument(fromArgument.Type, (int)fromArgument.Value + opcodesRange.Item2);
                    }
                }
            }
        }
Exemple #32
0
        string TypeToString(ConvertTypeOptions options, ITypeDefOrRef type, IHasCustomAttribute typeAttributes = null)
        {
            var          envProvider = new ILSpyEnvironmentProvider();
            var          converter   = new CSharpToVBConverterVisitor(envProvider);
            var          astType     = AstBuilder.ConvertType(null, null, type, typeAttributes, options);
            StringWriter w           = new StringWriter();

            if (type.TryGetByRefSig() != null)
            {
                w.Write("ByRef ");
                if (astType is NRefactory.CSharp.ComposedType && ((NRefactory.CSharp.ComposedType)astType).PointerRank > 0)
                {
                    ((NRefactory.CSharp.ComposedType)astType).PointerRank--;
                }
            }

            var vbAstType = astType.AcceptVisitor(converter, null);

            vbAstType.AcceptVisitor(new OutputVisitor(w, new VBFormattingOptions()), null);
            return(w.ToString());
        }
Exemple #33
0
 /// <summary>
 /// Converts a member signature to a string.
 /// This is used for displaying the tooltip on a member reference.
 /// </summary>
 public virtual void WriteToolTip(ITextOutput output, IMemberRef member, IHasCustomAttribute typeAttributes)
 {
     if (member is ITypeDefOrRef)
     {
         TypeToString(output, (ITypeDefOrRef)member, true, typeAttributes);
     }
     else if (member is GenericParam)
     {
         var gp = (GenericParam)member;
         output.Write(IdentifierEscaper.Escape(gp.Name), TextTokenHelper.GetTextTokenType(gp));
         output.WriteSpace();
         output.Write("in", TextTokenType.Text);
         output.WriteSpace();
         WriteToolTip(output, gp.Owner, typeAttributes);
     }
     else
     {
         //TODO: This should be escaped but since it contains whitespace, parens, etc,
         //		we can't pass it to IdentifierEscaper.Escape().
         output.Write(member.ToString(), TextTokenHelper.GetTextTokenType(member));
     }
 }
Exemple #34
0
        private void CloneCustomAttributes(IHasCustomAttribute source, IHasCustomAttribute newOwner)
        {
            foreach (var attribute in source.CustomAttributes)
            {
                var signature = new CustomAttributeSignature();

                foreach (var argument in attribute.Signature.FixedArguments)
                {
                    signature.FixedArguments.Add(CloneAttributeArgument(argument));
                }

                foreach (var argument in attribute.Signature.NamedArguments)
                {
                    signature.NamedArguments.Add(new CustomAttributeNamedArgument(argument.ArgumentMemberType,
                                                                                  _importer.ImportTypeSignature(argument.ArgumentType), argument.MemberName,
                                                                                  CloneAttributeArgument(argument.Argument)));
                }

                var newAttribute = new CustomAttribute((ICustomAttributeType)_importer.ImportReference(attribute.Constructor), signature);
                newOwner.CustomAttributes.Add(newAttribute);
            }
        }
Exemple #35
0
		/// <summary>
		/// Converts a type reference into a string. This method is used by the member tree node for parameter and return types.
		/// </summary>
		public string TypeToString(ITypeDefOrRef type, bool includeNamespace, IHasCustomAttribute typeAttributes = null)
		{
			var writer = new StringWriter();
			var output = new PlainTextOutput(writer);
			TypeToString(output, type, includeNamespace, typeAttributes);
			return writer.ToString();
		}
Exemple #36
0
		public virtual void WriteToolTip(ITextColorWriter output, IMemberRef member, IHasCustomAttribute typeAttributes) =>
			new SimpleCSharpPrinter(output, SimplePrinterFlags.Default).WriteToolTip(member);
		public virtual DocumentTreeNodeFilterResult GetResultAttributes(IHasCustomAttribute hca) => new DocumentTreeNodeFilterResult();
        private void ResolveCustomAttributes(MosaUnit.MutatorBase unit, IHasCustomAttribute obj)
        {
            foreach (var attr in obj.CustomAttributes)
            {
                MosaType type = metadata.Loader.GetType(attr.AttributeType.ToTypeSig());
                MethodDef ctor = ((IMethodDefOrRef)attr.Constructor).ResolveMethod();
                MosaMethod mosaCtor = null;
                foreach (var method in type.Methods)
                {
                    var desc = method.GetUnderlyingObject<UnitDesc<MethodDef, MethodSig>>();
                    if (desc.Token.Token == ctor.MDToken)
                    {
                        mosaCtor = method;
                        break;
                    }
                }
                if (mosaCtor == null)
                    throw new AssemblyLoadException();

                var values = new MosaCustomAttribute.Argument[attr.ConstructorArguments.Count];
                for (int i = 0; i < values.Length; i++)
                    values[i] = ToMosaCAArgument(attr.ConstructorArguments[i]);

                var namedArgs = new MosaCustomAttribute.NamedArgument[attr.NamedArguments.Count];
                for (int i = 0; i < namedArgs.Length; i++)
                {
                    var namedArg = attr.NamedArguments[i];
                    namedArgs[i] = new MosaCustomAttribute.NamedArgument(namedArg.Name, namedArg.IsField, ToMosaCAArgument(namedArg.Argument));
                }

                unit.CustomAttributes.Add(new MosaCustomAttribute(mosaCtor, values, namedArgs));
            }
        }
        static IEnumerable<ObfuscationAttributeInfo> ReadObfuscationAttributes(IHasCustomAttribute item)
        {
            var ret = new List<ObfuscationAttributeInfo>();
            for (int i = item.CustomAttributes.Count - 1; i >= 0; i--) {
                var ca = item.CustomAttributes[i];
                if (ca.TypeFullName != "System.Reflection.ObfuscationAttribute")
                    continue;

                var info = new ObfuscationAttributeInfo();
                bool strip = true;
                foreach (var prop in ca.Properties) {
                    switch (prop.Name) {
                        case "ApplyToMembers":
                            Debug.Assert(prop.Type.ElementType == ElementType.Boolean);
                            info.ApplyToMembers = (bool)prop.Value;
                            break;

                        case "Exclude":
                            Debug.Assert(prop.Type.ElementType == ElementType.Boolean);
                            info.Exclude = (bool)prop.Value;
                            break;

                        case "StripAfterObfuscation":
                            Debug.Assert(prop.Type.ElementType == ElementType.Boolean);
                            strip = (bool)prop.Value;
                            break;

                        case "Feature":
                            Debug.Assert(prop.Type.ElementType == ElementType.String);
                            string feature = (UTF8String)prop.Value;
                            int sepIndex = feature.IndexOf(':');
                            if (sepIndex == -1) {
                                info.FeatureName = "";
                                info.FeatureValue = feature;
                            }
                            else {
                                info.FeatureName = feature.Substring(0, sepIndex);
                                info.FeatureValue = feature.Substring(sepIndex + 1);
                            }
                            break;

                        default:
                            throw new NotSupportedException("Unsupported property: " + prop.Name);
                    }
                }
                if (strip)
                    item.CustomAttributes.RemoveAt(i);

                ret.Add(info);
            }
            ret.Reverse();
            return ret;
        }
 // Remove the attribute Xenocode adds that has an invalid ctor
 void removeInvalidAttributes(IHasCustomAttribute hca)
 {
     if (!CanRemoveTypes)
         return;
     if (hca == null)
         return;
     for (int i = hca.CustomAttributes.Count - 1; i >= 0; i--) {
         var ca = hca.CustomAttributes[i];
         if (ca.Constructor == null)
             hca.CustomAttributes.RemoveAt(i);
     }
 }
Exemple #41
0
        public override void WriteToolTip(ITextOutput output, IMemberRef member, IHasCustomAttribute typeAttributes)
        {
            if (!(member is ITypeDefOrRef) && Write(output, member))
                return;

            base.WriteToolTip(output, member, typeAttributes);
        }
Exemple #42
0
        private void ResolveCustomAttributes(MosaUnit.MutatorBase unit, IHasCustomAttribute obj)
        {
            // TODO: More detail parsing
            foreach (var attr in obj.CustomAttributes)
            {
                MosaType type = metadata.Loader.GetType(attr.AttributeType.ToTypeSig());
                MethodDef ctor = ((IMethodDefOrRef)attr.Constructor).ResolveMethod();
                MosaMethod mosaCtor = null;
                foreach (var method in type.Methods)
                {
                    var desc = method.GetUnderlyingObject<UnitDesc<MethodDef, MethodSig>>();
                    if (desc.Token.Token == ctor.MDToken)
                    {
                        mosaCtor = method;
                        break;
                    }
                }
                if (mosaCtor == null)
                    throw new AssemblyLoadException();

                object[] values = new object[attr.ConstructorArguments.Count];
                for (int i = 0; i < values.Length; i++)
                {
                    if (attr.ConstructorArguments[i].Value is UTF8String)
                        values[i] = ((UTF8String)attr.ConstructorArguments[i].Value).String;
                    else
                        values[i] = attr.ConstructorArguments[i].Value;
                }
                unit.CustomAttributes.Add(new MosaCustomAttribute(mosaCtor, values));
            }
        }
Exemple #43
0
		/// <summary>
		/// Converts a member signature to a string.
		/// This is used for displaying the tooltip on a member reference.
		/// </summary>
		public virtual void WriteToolTip(ITextOutput output, IMemberRef member, IHasCustomAttribute typeAttributes)
		{
			if (member is ITypeDefOrRef)
				TypeToString(output, (ITypeDefOrRef)member, true, typeAttributes);
			else if (member is GenericParam) {
				var gp = (GenericParam)member;
				output.Write(IdentifierEscaper.Escape(gp.Name), TextTokenHelper.GetTextTokenType(gp));
				output.WriteSpace();
				output.Write("in", TextTokenType.Text);
				output.WriteSpace();
				WriteToolTip(output, gp.Owner, typeAttributes);
			}
			else {
				//TODO: This should be escaped but since it contains whitespace, parens, etc,
				//		we can't pass it to IdentifierEscaper.Escape().
				output.Write(member.ToString(), TextTokenHelper.GetTextTokenType(member));
			}
		}
		public override DocumentTreeNodeFilterResult GetResultAttributes(IHasCustomAttribute hca) {
			bool isMatch = (flags & VisibleMembersFlags.Attributes) != 0;
			if (!isMatch)
				return new DocumentTreeNodeFilterResult(FilterType.Hide, isMatch);
			return new DocumentTreeNodeFilterResult(FilterType.Visible, isMatch);
		}
 IEnumerable<ProtectionSettingsInfo> ReadInfos(IHasCustomAttribute item)
 {
     foreach (var attr in ReadObfuscationAttributes(item)) {
         ProtectionSettingsInfo info;
         if (ToInfo(attr, out info))
             yield return info;
     }
 }
 IEnumerable<ProtectionSettingsInfo> ReadInfos(IHasCustomAttribute item)
 {
     foreach (var attr in ReadObfuscationAttributes(item)) {
         ProtectionSettingsInfo info;
         if (!string.IsNullOrEmpty(attr.FeatureName))
             yield return AddRule(attr, null);
         else if (ToInfo(attr, out info))
             yield return info;
     }
 }
        static IEnumerable<ObfuscationAttributeInfo> ReadObfuscationAttributes(IHasCustomAttribute item)
        {
            var ret = new List<Tuple<int?, ObfuscationAttributeInfo>>();
            for (int i = item.CustomAttributes.Count - 1; i >= 0; i--) {
                var ca = item.CustomAttributes[i];
                if (ca.TypeFullName != "System.Reflection.ObfuscationAttribute")
                    continue;

                var info = new ObfuscationAttributeInfo();
                int? order = null;

                info.Owner = item;
                bool strip = true;
                foreach (var prop in ca.Properties) {
                    switch (prop.Name) {
                        case "ApplyToMembers":
                            Debug.Assert(prop.Type.ElementType == ElementType.Boolean);
                            info.ApplyToMembers = (bool)prop.Value;
                            break;

                        case "Exclude":
                            Debug.Assert(prop.Type.ElementType == ElementType.Boolean);
                            info.Exclude = (bool)prop.Value;
                            break;

                        case "StripAfterObfuscation":
                            Debug.Assert(prop.Type.ElementType == ElementType.Boolean);
                            strip = (bool)prop.Value;
                            break;

                        case "Feature":
                            Debug.Assert(prop.Type.ElementType == ElementType.String);
                            string feature = (UTF8String)prop.Value;

                            var match = OrderPattern.Match(feature);
                            if (match.Success) {
                                var orderStr = match.Groups[1].Value;
                                var f = match.Groups[2].Value;
                                int o;
                                if (!int.TryParse(orderStr, out o))
                                    throw new NotSupportedException(string.Format("Failed to parse feature '{0}' in {1} ", feature, item));
                                order = o;
                                feature = f;
                            }

                            int sepIndex = feature.IndexOf(':');
                            if (sepIndex == -1) {
                                info.FeatureName = "";
                                info.FeatureValue = feature;
                            }
                            else {
                                info.FeatureName = feature.Substring(0, sepIndex);
                                info.FeatureValue = feature.Substring(sepIndex + 1);
                            }
                            break;

                        default:
                            throw new NotSupportedException("Unsupported property: " + prop.Name);
                    }
                }
                if (strip)
                    item.CustomAttributes.RemoveAt(i);

                ret.Add(Tuple.Create(order, info));
            }
            ret.Reverse();
            return ret.OrderBy(pair => pair.Item1).Select(pair => pair.Item2);
        }
        public override string TypeToString(ITypeDefOrRef type, bool includeNamespace, IHasCustomAttribute typeAttributes = null)
        {
            ConvertTypeOptions options = ConvertTypeOptions.IncludeTypeParameterDefinitions;
            if (includeNamespace)
                options |= ConvertTypeOptions.IncludeNamespace;

            return TypeToString(options, type, typeAttributes);
        }
Exemple #49
0
        void WriteToolTip(ITextOutput output, TypeSig type, GenericParamContext gpContext, IHasCustomAttribute typeAttributes)
        {
            var gsig = type.RemovePinnedAndModifiers() as GenericSig;
            var gp = GetGenericParam(gsig, gpContext);
            if (gp != null) {
                output.Write(IdentifierEscaper.Escape(gp.Name), gsig.IsMethodVar ? TextTokenType.MethodGenericParameter : TextTokenType.TypeGenericParameter);
                return;
            }

            WriteToolTip(output, type.ToTypeDefOrRef(), typeAttributes);
        }
Exemple #50
0
		public virtual void TypeToString(ITextOutput output, ITypeDefOrRef type, bool includeNamespace, IHasCustomAttribute typeAttributes = null)
		{
			if (type == null)
				return;
			if (includeNamespace)
				output.Write(IdentifierEscaper.Escape(type.FullName), TextTokenHelper.GetTextTokenType(type));
			else
				output.Write(IdentifierEscaper.Escape(type.Name), TextTokenHelper.GetTextTokenType(type));
		}
Exemple #51
0
        void WriteToolTip(ITextOutput output, ITypeDefOrRef type, IHasCustomAttribute typeAttributes = null)
        {
            if (type == null)
                return;

            WriteToolTipType(output, type, TOOLTIP_USE_NAMESPACES, true, typeAttributes);
        }
		bool HasExtensionAttribute(IHasCustomAttribute p) => p.CustomAttributes.Find("System.Runtime.CompilerServices.ExtensionAttribute") != null;
Exemple #53
0
 void CheckCustomAttributes(IDnSpyFile file, IHasCustomAttribute hca, object parent)
 {
     var res = options.Filter.GetResultAttributes(hca);
     if (!res.IsMatch)
         return;
     foreach (var ca in hca.CustomAttributes) {
         foreach (var o in ca.ConstructorArguments) {
             if (CheckCA(file, hca, parent, o))
                 return;
         }
         foreach (var o in ca.NamedArguments) {
             if (CheckCA(file, hca, parent, o.Argument))
                 return;
         }
     }
 }
Exemple #54
0
		string TypeToString(ITypeDefOrRef type, bool includeNamespace, IHasCustomAttribute typeAttributes = null) {
			var output = new StringBuilderDecompilerOutput();
			TypeToString(output, type, includeNamespace, typeAttributes);
			return output.ToString();
		}
Exemple #55
0
		public override void TypeToString(ITextOutput output, ITypeDefOrRef t, bool includeNamespace, IHasCustomAttribute attributeProvider = null)
		{
			t.WriteTo(output, includeNamespace ? ILNameSyntax.TypeName : ILNameSyntax.ShortTypeName);
		}
Exemple #56
0
		protected virtual void TypeToString(IDecompilerOutput output, ITypeDefOrRef type, bool includeNamespace, IHasCustomAttribute typeAttributes = null) {
			if (type == null)
				return;
			if (includeNamespace)
				output.Write(IdentifierEscaper.Escape(type.FullName), MetadataTextColorProvider.GetColor(type));
			else
				output.Write(IdentifierEscaper.Escape(type.Name), MetadataTextColorProvider.GetColor(type));
		}
        string TypeToString(ConvertTypeOptions options, ITypeDefOrRef type, IHasCustomAttribute typeAttributes = null)
        {
            AstType astType = AstBuilder.ConvertType(null, null, type, typeAttributes, options);

            StringWriter w = new StringWriter();
            if (type.TryGetByRefSig() != null) {
                ParamDef pd = typeAttributes as ParamDef;
                if (pd != null && (!pd.IsIn && pd.IsOut))
                    w.Write("out ");
                else
                    w.Write("ref ");

                if (astType is ComposedType && ((ComposedType)astType).PointerRank > 0)
                    ((ComposedType)astType).PointerRank--;
            }

            astType.AcceptVisitor(new CSharpOutputVisitor(w, FormattingOptionsFactory.CreateAllman()));
            return w.ToString();
        }
Exemple #58
0
		protected override void TypeToString(IDecompilerOutput output, ITypeDefOrRef t, bool includeNamespace, IHasCustomAttribute attributeProvider = null) =>
			t.WriteTo(output, includeNamespace ? ILNameSyntax.TypeName : ILNameSyntax.ShortTypeName);
Exemple #59
0
        private static void ReCustomAttributes(IHasCustomAttribute type, ModuleDef module)
        {

            for (int i = 0; i < type.CustomAttributes.Count; ++i)
            {
                var newattr = FindType(type.CustomAttributes[i].TypeFullName, module);
                if (newattr == null)
                    continue;

                type.CustomAttributes[i] = new CustomAttribute(newattr.FindDefaultConstructor());
            }
        }
Exemple #60
0
 /// <summary>
 /// Converts a type reference into a string. This method is used by the member tree node for parameter and return types.
 /// </summary>
 public virtual string TypeToString(ITypeDefOrRef type, bool includeNamespace, IHasCustomAttribute typeAttributes = null)
 {
     if (includeNamespace)
         return type.FullName;
     else
         return type.Name;
 }