/// <summary> /// Creates a new instance of the class. /// </summary> /// <param name="type">The attribute type.</param> /// <param name="attribute">The CCI attribute.</param> internal ScriptAttribute(ICustomAttribute attribute) { if (attribute == null) { throw new InvalidOperationException(); } var typeRef = attribute.Type as INamedTypeReference; if (typeRef == null) { throw new InvalidOperationException("Attribute type must be a named type."); } var type = ScriptDomain.CurrentDomain.ResolveType(typeRef); if (type == null) { throw new InvalidOperationException("Unable to resolve type for attribute: " + typeRef.Name); } _type = type; _cciAttribute = attribute; _arguments = _cciAttribute.Arguments .Select(a => GetConstantValue(a)).ToArray(); _namedArgs = _cciAttribute.NamedArguments.ToDictionary(a => a.ArgumentName.Value, a => GetConstantValue(a)); }
internal PrivateImplementationDetails( CommonPEModuleBuilder moduleBuilder, string moduleName, int submissionSlotIndex, ITypeReference systemObject, ITypeReference systemValueType, ITypeReference systemInt8Type, ITypeReference systemInt16Type, ITypeReference systemInt32Type, ITypeReference systemInt64Type, ICustomAttribute compilerGeneratedAttribute) { Debug.Assert(systemObject != null); Debug.Assert(systemValueType != null); _moduleBuilder = moduleBuilder; _systemObject = systemObject; _systemValueType = systemValueType; _systemInt8Type = systemInt8Type; _systemInt16Type = systemInt16Type; _systemInt32Type = systemInt32Type; _systemInt64Type = systemInt64Type; _compilerGeneratedAttribute = compilerGeneratedAttribute; var isNetModule = moduleBuilder.OutputKind == OutputKind.NetModule; _name = GetClassName(moduleName, submissionSlotIndex, isNetModule); }
public virtual void PrintAttribute(IReference target, ICustomAttribute attribute, bool newLine, string targetType) { this.sourceEmitterOutput.Write("[", newLine); if (targetType != null) { this.sourceEmitterOutput.Write(targetType); this.sourceEmitterOutput.Write(": "); } this.PrintTypeReferenceName(attribute.Constructor.ContainingType); if (attribute.NumberOfNamedArguments > 0 || IteratorHelper.EnumerableIsNotEmpty(attribute.Arguments)) { this.sourceEmitterOutput.Write("("); bool first = true; foreach (var argument in attribute.Arguments) { if (first) first = false; else this.sourceEmitterOutput.Write(", "); this.Traverse(argument); } foreach (var namedArgument in attribute.NamedArguments) { if (first) first = false; else this.sourceEmitterOutput.Write(", "); this.Traverse(namedArgument); } this.sourceEmitterOutput.Write(")"); } this.sourceEmitterOutput.Write("]"); if (newLine) this.sourceEmitterOutput.WriteLine(""); }
public static bool IsEditorBrowseableStateNever(this ICustomAttribute attribute) { if (attribute.Type.FullName() != typeof(EditorBrowsableAttribute).FullName) { return(false); } if (attribute.Arguments == null || attribute.Arguments.Count() != 1) { return(false); } IMetadataConstant singleArgument = attribute.Arguments.Single() as IMetadataConstant; if (singleArgument == null || !(singleArgument.Value is int)) { return(false); } if (EditorBrowsableState.Never != (EditorBrowsableState)singleArgument.Value) { return(false); } return(true); }
/// <summary> /// Creates a new instance of the class. /// </summary> /// <param name="type">The attribute type.</param> /// <param name="attribute">The CCI attribute.</param> internal ScriptAttribute(ICustomAttribute attribute) { if (attribute == null) throw new InvalidOperationException(); var typeRef = attribute.Type as INamedTypeReference; if (typeRef == null) { throw new InvalidOperationException("Attribute type must be a named type."); } var type = ScriptDomain.CurrentDomain.ResolveType(typeRef); if (type == null) { throw new InvalidOperationException("Unable to resolve type for attribute: " + typeRef.Name); } _type = type; _cciAttribute = attribute; _arguments = _cciAttribute.Arguments .Select(a => GetConstantValue(a)).ToArray(); _namedArgs = _cciAttribute.NamedArguments.ToDictionary(a => a.ArgumentName.Value, a => GetConstantValue(a)); }
public static bool IsObsoleteWithUsageTreatedAsCompilationError(this ICustomAttribute attribute) { if (attribute.Type.FullName() != typeof(ObsoleteAttribute).FullName) { return(false); } if (attribute.Arguments == null || attribute.Arguments.Count() != 2) { return(false); } IMetadataConstant messageArgument = attribute.Arguments.ElementAt(0) as IMetadataConstant; IMetadataConstant errorArgument = attribute.Arguments.ElementAt(1) as IMetadataConstant; if (messageArgument == null || errorArgument == null) { return(false); } if (!(messageArgument.Value is string && errorArgument.Value is bool)) { return(false); } return((bool)errorArgument.Value); }
public virtual bool Include(ICustomAttribute attribute) { if (this.ExcludeAttributes) { return(false); } // Ignore attributes not visible outside the assembly var attributeDef = attribute.Type.GetDefinitionOrNull(); if (attributeDef != null && !attributeDef.IsVisibleOutsideAssembly()) { return(false); } // Ignore attributes with typeof argument of a type invisible outside the assembly foreach (var arg in attribute.Arguments.OfType <IMetadataTypeOf>()) { var typeDef = arg.TypeToGet.GetDefinitionOrNull(); if (typeDef == null) { continue; } if (!typeDef.IsVisibleOutsideAssembly()) { return(false); } } return(true); }
/// <summary> /// Used for retrieving applied source security attributes, i.e. attributes derived from well-known SecurityAttribute. /// </summary> public IEnumerable <SecurityAttribute> GetSecurityAttributes <T>(T[] customAttributes) where T : ICustomAttribute { Debug.Assert(customAttributes != null); Debug.Assert(_lazyPathsForPermissionSetFixup == null || _lazySecurityActions != null && _lazyPathsForPermissionSetFixup.Length == _lazySecurityActions.Length); if (_lazySecurityActions != null) { Debug.Assert(_lazySecurityActions != null); Debug.Assert(_lazySecurityActions.Length == customAttributes.Length); for (int i = 0; i < customAttributes.Length; i++) { if (_lazySecurityActions[i] != 0) { var action = (DeclarativeSecurityAction)_lazySecurityActions[i]; ICustomAttribute attribute = customAttributes[i]; /* * if (_lazyPathsForPermissionSetFixup?[i] != null) * { * attribute = new PermissionSetAttributeWithFileReference(attribute, _lazyPathsForPermissionSetFixup[i]); * } * * yield return new ecurityAttribute(action, attribute);*/ throw new Exception("@!"); } } } throw new Exception("@!"); }
public virtual bool Include(ICustomAttribute attribute) { if (ExcludeAttributes) { return(false); } // Exclude attributes not visible outside the assembly. var attributeDef = attribute.Type.GetDefinitionOrNull(); if (attributeDef != null && !TypeHelper.IsVisibleToFriendAssemblies(attributeDef)) { return(false); } // Exclude attributes with typeof() argument of a type invisible to friend assemblies. foreach (var arg in attribute.Arguments.OfType <IMetadataTypeOf>()) { var typeDef = arg.TypeToGet.GetDefinitionOrNull(); if (typeDef != null && !TypeHelper.IsVisibleToFriendAssemblies(typeDef)) { return(false); } } // Otherwise... return(true); }
public void Test_FromBaseWithInterface() { ICustomAttribute attribute = (ICustomAttribute)AttributeUtility.GetCustomAttribute(_basePropertyWithSingleAttribute, typeof(ICustomAttribute), true); Assert.That(attribute, Is.Not.Null); }
/// <summary> /// /// </summary> /// <param name="customAttributeData"></param> /// <returns></returns> public IEnumerable<ICustomAttribute> GetCustomAttributes(IList<CustomAttributeData> customAttributeData) { int n = customAttributeData.Count; ICustomAttribute[] customAttributes = new ICustomAttribute[n]; for (int i = 0; i < n; i++) customAttributes[i] = this.GetCustomAttribute(customAttributeData[i]); return IteratorHelper.GetReadonly(customAttributes); }
public virtual bool Include(ICustomAttribute attribute) { // Include all FakeCustomAttribute because they cannot be annotated and they have simple arguments. if (attribute is FakeCustomAttribute) { return(true); } // Exclude leftover [CompilerGenerated] annotations (should exist only on event and property accessors). if (string.Equals(CompilerGeneratedTypeName, attribute.Type.FullName(), StringComparison.Ordinal)) { return(false); } // Exclude attributes with typeof() argument of a compiler-generated type. foreach (var arg in attribute.Arguments.OfType <IMetadataTypeOf>()) { var typeDef = arg.TypeToGet.GetDefinitionOrNull(); if (typeDef != null && !IsNotMarkedWithAttribute(typeDef)) { return(false); } } return(IsNotMarkedWithAttribute(attribute.Type.ResolvedType)); }
public static ITypeDefinition /*?*/ GetTypeDefinitionFromAttribute(IEnumerable <ICustomAttribute> attributes, string attributeName) { ICustomAttribute foundAttribute = null; foreach (ICustomAttribute attribute in attributes) { if (TypeHelper.GetTypeName(attribute.Type) == attributeName) { foundAttribute = attribute; break; } } if (foundAttribute == null) { return(null); } List <IMetadataExpression> args = new List <IMetadataExpression>(foundAttribute.Arguments); if (args.Count < 1) { return(null); } IMetadataTypeOf abstractTypeMD = args[0] as IMetadataTypeOf; if (abstractTypeMD == null) { return(null); } ITypeReference referencedTypeReference = Microsoft.Cci.MutableContracts.ContractHelper.Unspecialized(abstractTypeMD.TypeToGet); ITypeDefinition referencedTypeDefinition = referencedTypeReference.ResolvedType; return(referencedTypeDefinition); }
public static object GetAttributeArgumentValue <TType>(this ICustomAttribute attribute, object defaultValue = null) { object result = defaultValue; if (attribute != null) { object argument = attribute.Arguments.FirstOrDefault(); if (argument is IMetadataCreateArray argumentArray) { TType[] array = new TType[argumentArray.Sizes.Single()]; int i = 0; foreach (IMetadataExpression value in argumentArray.Initializers) { array[i++] = (TType)(value as IMetadataConstant).Value; } result = array; } else if (argument is IMetadataConstant value) { result = (TType)value.Value; } } return(result); }
private void WriteSkipLine() { writer.Write("["); if (attr_class != null) { writer.WriteKeyword(attr_class); writer.Write(": "); } bool first = true; foreach (AttrPair pair in attrs) { if (attr_proc != null && !attr_proc(pair.Key, pair.Value)) { continue; } ICustomAttribute attr = pair.Value; if (first) { first = false; } else { writer.Write(", "); } this.WriteCustomAttribute(attr); } writer.Write("]"); }
public override bool Include(ICustomAttribute attribute) { if (_attributeDocIds.Contains(attribute.DocId())) return false; return base.Include(attribute); }
private void LinkVector(IType type, ICustomAttribute attr) { var vectorType = type.Data as VectorType; if (vectorType != null) { return; } string param = VectorType.GetVectorParam(attr); if (param == null) { return; } var paramType = FindType(param); if (paramType == null) { throw new InvalidOperationException(string.Format("Unable to find Vector param type: {0}", param)); } vectorType = new VectorType(type, paramType); type.Data = vectorType; }
public bool Include(ICustomAttribute attribute) { string typeId = attribute.DocId(); string removeUsages = "RemoveUsages:" + typeId; // special case: attribute usage can be removed without removing // the attribute itself if (_docIds.Contains(removeUsages)) { return(false); } if (_excludeMembers) { foreach (var argument in attribute.Arguments) { // if the argument is an excluded type if (!IncludeTypeReference(argument.Type)) { return(false); } // if the argument is typeof of an excluded type IMetadataTypeOf typeOf = argument as IMetadataTypeOf; if (typeOf != null && !IncludeTypeReference(typeOf.TypeToGet)) { return(false); } } } // include so long as it isn't in the exclude list. return(!_docIds.Contains(typeId)); }
private IEnumerable <Instruction> GetAttributeInstanceInstructions( ILProcessor processor, ICustomAttribute attribute, MethodDefinition method, VariableDefinition attributeVariableDefinition, VariableDefinition methodVariableDefinition) { var getMethodFromHandleRef = this._referenceFinder.GetMethodReference(typeof(MethodBase), md => md.Name == "GetMethodFromHandle" && md.Parameters.Count == 2); var getTypeof = this._referenceFinder.GetMethodReference(typeof(Type), md => md.Name == "GetTypeFromHandle"); var ctor = this._referenceFinder.GetMethodReference(typeof(Activator), md => md.Name == "CreateInstance" && md.Parameters.Count == 1); /* * // Code size 23 (0x17) * .maxstack 1 * .locals init ([0] class SimpleTest.IntersectMethodsMarkedByAttribute i) * IL_0000: nop * IL_0001: ldtoken SimpleTest.IntersectMethodsMarkedByAttribute * IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) * IL_000b: call object [mscorlib]System.Activator::CreateInstance(class [mscorlib]System.Type) * IL_0010: castclass SimpleTest.IntersectMethodsMarkedByAttribute * IL_0015: stloc.0 * IL_0016: ret */ return(new List <Instruction> { processor.Create(OpCodes.Nop), processor.Create(OpCodes.Ldtoken, method), processor.Create(OpCodes.Ldtoken, method.DeclaringType), processor.Create(OpCodes.Call, getMethodFromHandleRef), // Push method onto the stack, GetMethodFromHandle, result on stack processor.Create(OpCodes.Stloc_S, methodVariableDefinition), // Store method in __fody$method processor.Create(OpCodes.Nop), processor.Create(OpCodes.Ldtoken, attribute.AttributeType), processor.Create(OpCodes.Call, getTypeof), processor.Create(OpCodes.Call, ctor), processor.Create(OpCodes.Castclass, attribute.AttributeType), processor.Create(OpCodes.Stloc_S, attributeVariableDefinition), /* * * * processor.Create(OpCodes.Ldloc_S, methodVariableDefinition), * processor.Create(OpCodes.Ldtoken, attribute.AttributeType), * processor.Create(OpCodes.Call, getTypeFromHandleRef), // Push method + attribute onto the stack, GetTypeFromHandle, result on stack * processor.Create(OpCodes.Ldc_I4_0), * processor.Create(OpCodes.Callvirt, getCustomAttributesRef), // Push false onto the stack (result still on stack), GetCustomAttributes * processor.Create(OpCodes.Ldc_I4_0), * processor.Create(OpCodes.Ldelem_Ref), // Get 0th index from result * processor.Create(OpCodes.Castclass, attribute.AttributeType), * processor.Create(OpCodes.Stloc_S, attributeVariableDefinition) // Cast to attribute stor in __fody$attribute */ }); }
public override void TraverseChildren(ICustomAttribute customAttribute) { if (!_filter.Include(customAttribute)) { return; } base.TraverseChildren(customAttribute); }
public override void Visit(ICustomAttribute customAttribute) { if (Process(customAttribute)) { visitor.Visit(customAttribute); } base.Visit(customAttribute); }
public virtual bool Include(ICustomAttribute attribute) { if (this.ExcludeAttributes) return false; // Always return the custom attributes if ExcludeAttributes is not set // the PublicOnly mainly concerns the types and members. return true; }
public override bool Include(ICustomAttribute attribute) { if (_attributeDocIds.Contains(attribute.DocId())) { return(false); } return(base.Include(attribute)); }
private bool IncludeAttribute(ICustomAttribute attribute) { if (ExcludeSpecialAttribute(attribute)) { return(false); } return(_filter.Include(attribute)); }
/// <inheritdoc/> public void AddCustomAttribute(ICustomAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } readOnly.Assert(false); customAttributes.Add(attribute); }
//============================================================ // Util //============================================================ private static string GetCustomAttributeName(ICustomAttribute iCustomAttribute) { string name = new TypeRef(iCustomAttribute.Constructor.DeclaringType).Name; if (name.EndsWith("Attribute")) { name = name.Substring(0, name.Length - 9); } return(name); }
private void CheckIfAttributeUsedOnRule(ICustomAttribute attribute, ICustomAttributeProvider provider) { TypeDefinition td = (provider as TypeDefinition); if (td == null || !IsRule(td)) { Runner.Report(td, Severity.Medium, Confidence.High, attribute.AttributeType.GetFullName() + " can be used on rules only"); } }
public bool Include(ICustomAttribute attribute) { string typeId = attribute.DocId(); string removeUsages = "RemoveUsages:" + typeId; if (_docIds.Contains(removeUsages)) return false; return _docIds.Contains(typeId); }
public static string FullName(this ICustomAttribute attribute) { FakeCustomAttribute fca = attribute as FakeCustomAttribute; if (fca != null) { return(fca.FullTypeName); } return(attribute.Type.FullName()); }
public static string DocId(this ICustomAttribute attribute) { FakeCustomAttribute fca = attribute as FakeCustomAttribute; if (fca != null) { return(fca.DocId); } return(attribute.Type.DocId()); }
public virtual bool Include(ICustomAttribute attribute) { if (this.ExcludeAttributes) { return(false); } // Always return the custom attributes if ExcludeAttributes is not set // the PublicOnly mainly concerns the types and members. return(true); }
public static ICustomAttribute AddCustomAttribute(this IBaseInfo baseInfo, ICustomAttribute attribute) { for (int index = 0; index < attribute.Name.Split(';').Length; index++) { string s = attribute.Name.Split(';')[index]; var theValue = attribute.Value.Split(';')[index]; baseInfo.AddAttribute(new ModelDefaultAttribute(s, theValue)); } return(attribute); }
private void WriteICustomAttributeNamedArguments(ICustomAttribute attribute) { if (attribute.HasFields) { this.WriteCustomAttributeNamedArguments(0x53, attribute.Fields); } if (attribute.HasProperties) { this.WriteCustomAttributeNamedArguments(0x54, attribute.Properties); } }
private static UTF8String GetEntryPointFromAttribute(ICustomAttribute exportAttribute) { var valueFromAttribute = exportAttribute?.Properties.FirstOrDefault(x => x.Name == "EntryPoint")?.Value as UTF8String; if (string.IsNullOrEmpty(valueFromAttribute)) { return(null); } return(valueFromAttribute); }
private void CheckIfAttributeUsedOnRulesProperty(ICustomAttribute attribute, ICustomAttributeProvider provider) { PropertyDefinition property = (provider as PropertyDefinition); if (property == null || !IsRule(property.DeclaringType) || !property.GetMethod.IsPublic || !property.SetMethod.IsPublic) { Runner.Report(provider, Severity.High, Confidence.High, attribute.AttributeType.GetFullName() + " should be used only on rules' public properties"); } }
/// <summary> /// /// </summary> /// <param name="customAttributeData"></param> /// <returns></returns> public IEnumerable <ICustomAttribute> GetCustomAttributes(IList <CustomAttributeData> customAttributeData) { int n = customAttributeData.Count; ICustomAttribute[] customAttributes = new ICustomAttribute[n]; for (int i = 0; i < n; i++) { customAttributes[i] = this.GetCustomAttribute(customAttributeData[i]); } return(IteratorHelper.GetReadonly(customAttributes)); }
static string GetPropertyString (ICustomAttribute attribute, string name) { if (!attribute.HasProperties) return String.Empty; foreach (var namedArg in attribute.Properties) { if (namedArg.Name == name) { return (namedArg.Argument.Value as string); } } return String.Empty; }
static bool TryGetPropertyArgument (ICustomAttribute attribute, string name, out CustomAttributeArgument argument) { foreach (var namedArg in attribute.Properties) { if (namedArg.Name == name) { argument = namedArg.Argument; return true; } } argument = default (CustomAttributeArgument); return false; }
public bool Include(ICustomAttribute attribute) { string typeId = attribute.DocId(); string removeUsages = "RemoveUsages:" + typeId; // special case: attribute usage can be removed without removing // the attribute itself if (_docIds.Contains(removeUsages)) return false; // include so long as it isn't in the exclude list. return !_docIds.Contains(typeId); }
public string GetString(ICustomAttribute attribute, int indentLevel = -1) { EnsureStringWriter(); _string.Clear(); if (indentLevel != -1) _stringWriter.SyntaxtWriter.IndentLevel = indentLevel; _stringWriter.WriteAttribute(attribute); return _string.ToString(); }
public IEnumerable<SyntaxToken> GetTokenList(ICustomAttribute attribute, int indentLevel = -1) { EnsureTokenWriter(); _tokenizer.ClearTokens(); if (indentLevel != -1) _tokenizer.IndentLevel = indentLevel; _tokenWriter.WriteAttribute(attribute); return _tokenizer.ToTokenList(); }
/// <summary> /// Tries to find an attribue by name /// </summary> /// <param name="attributes"></param> /// <param name="attributeName"></param> /// <param name="attribute"></param> /// <returns></returns> public static bool TryGetAttributeByName( IEnumerable<ICustomAttribute> attributes, string attributeName, out ICustomAttribute attribute) { Contract.Requires(!String.IsNullOrEmpty(attributeName)); Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out attribute) != null); if (attributes == null) { attribute = null; return false; } foreach (var a in attributes) { if (AttributeMatchesByName(a, attributeName)) { attribute = a; return true; } } attribute = null; return false; }
public void WriteAttribute(ICustomAttribute attribute, string prefix = null, SecurityAction action = SecurityAction.ActionNil) { if (!string.IsNullOrEmpty(prefix)) { Write(prefix); WriteSymbol(":"); } WriteTypeName(attribute.Constructor.ContainingType, noSpace: true); // Should we strip Attribute from name? if (attribute.NumberOfNamedArguments > 0 || attribute.Arguments.Any() || action != SecurityAction.ActionNil) { WriteSymbol("("); bool first = true; if (action != SecurityAction.ActionNil) { Write("System.Security.Permissions.SecurityAction." + action.ToString()); first = false; } foreach (IMetadataExpression arg in attribute.Arguments) { if (!first) WriteSymbol(",", true); WriteMetadataExpression(arg); first = false; } foreach (IMetadataNamedArgument namedArg in attribute.NamedArguments) { if (!first) WriteSymbol(",", true); WriteIdentifier(namedArg.ArgumentName); WriteSymbol("="); WriteMetadataExpression(namedArg.ArgumentValue); first = false; } WriteSymbol(")"); } }
public virtual bool Include(ICustomAttribute attribute) { if (this.ExcludeAttributes) return false; // Ignore attributes not visible outside the assembly var attributeDef = attribute.Type.GetDefinitionOrNull(); if (attributeDef != null && !attributeDef.IsVisibleOutsideAssembly()) return false; // Ignore attributes with typeof argument of a type invisible outside the assembly foreach(var arg in attribute.Arguments.OfType<IMetadataTypeOf>()) { var typeDef = arg.TypeToGet.GetDefinitionOrNull(); if (typeDef == null) continue; if (!typeDef.IsVisibleOutsideAssembly()) return false; } return true; }
/// <summary> /// Traverses the children of the custom attribute. /// </summary> public virtual void TraverseChildren(ICustomAttribute customAttribute) { Contract.Requires(customAttribute != null); this.Traverse(customAttribute.Arguments); if (this.stopTraversal) return; this.Traverse(customAttribute.Constructor); if (this.stopTraversal) return; this.Traverse(customAttribute.NamedArguments); }
internal SecurityAttributeDecoder20(PEFileToObjectModel peFileToObjectModel, MemoryReader signatureMemoryReader, SecurityAttribute securityAttribute) : base(peFileToObjectModel, signatureMemoryReader) { this.SecurityAttributes = Enumerable<ICustomAttribute>.Empty; byte prolog = this.SignatureMemoryReader.ReadByte(); if (prolog != SerializationType.SecurityAttribute20Start) return; int numberOfAttributes = this.SignatureMemoryReader.ReadCompressedUInt32(); var securityCustomAttributes = new ICustomAttribute[numberOfAttributes]; for (int i = 0; i < numberOfAttributes; ++i) { var secAttr = this.ReadSecurityAttribute(securityAttribute); if (secAttr == null) { // MDError... return; } securityCustomAttributes[i] = secAttr; } this.SecurityAttributes = IteratorHelper.GetReadonly(securityCustomAttributes); }
internal CustomAttributeDecoder(PEFileToObjectModel peFileToObjectModel, MemoryReader signatureMemoryReader, uint customAttributeRowId, IMethodReference attributeConstructor) : base(peFileToObjectModel, signatureMemoryReader) { this.CustomAttribute = Dummy.CustomAttribute; ushort prolog = this.SignatureMemoryReader.ReadUInt16(); if (prolog != SerializationType.CustomAttributeStart) return; int len = attributeConstructor.ParameterCount; IMetadataExpression[]/*?*/ exprList = len == 0 ? null : new IMetadataExpression[len]; int i = 0; foreach (var parameter in attributeConstructor.Parameters) { var parameterType = parameter.Type; if (parameterType is Dummy) { // Error... return; } ExpressionBase/*?*/ argument = this.ReadSerializedValue(parameterType); if (argument == null) { // Error... this.decodeFailed = true; return; } exprList[i++] = argument; } IMetadataNamedArgument[]/*?*/ namedArgumentArray = null; if (2 <= (int)this.SignatureMemoryReader.RemainingBytes) { ushort numOfNamedArgs = this.SignatureMemoryReader.ReadUInt16(); if (numOfNamedArgs > 0) { namedArgumentArray = new IMetadataNamedArgument[numOfNamedArgs]; for (i = 0; i < numOfNamedArgs; ++i) { if (0 >= (int)this.SignatureMemoryReader.RemainingBytes) break; bool isField = this.SignatureMemoryReader.ReadByte() == SerializationType.Field; ITypeReference/*?*/ memberType = this.GetFieldOrPropType(); if (memberType == null) { // Error... return; } string/*?*/ memberStr = this.GetSerializedString(); if (memberStr == null) return; IName memberName = this.PEFileToObjectModel.NameTable.GetNameFor(memberStr); ExpressionBase/*?*/ value = this.ReadSerializedValue(memberType); if (value == null) { // Error... return; } ITypeReference/*?*/ moduleTypeRef = attributeConstructor.ContainingType; if (moduleTypeRef == null) { // Error... return; } FieldOrPropertyNamedArgumentExpression namedArg = new FieldOrPropertyNamedArgumentExpression(memberName, moduleTypeRef, isField, memberType, value); namedArgumentArray[i] = namedArg; } } } this.CustomAttribute = peFileToObjectModel.ModuleReader.metadataReaderHost.Rewrite(peFileToObjectModel.Module, new CustomAttribute(peFileToObjectModel, customAttributeRowId, attributeConstructor, exprList, namedArgumentArray)); }
public override void TraverseChildren(ICustomAttribute customAttribute) { // Different uses of custom attributes must print them directly based on context //base.TraverseChildren(customAttribute); }
public override void Visit(ICustomAttribute attribute) { Visit(attribute.Type); // For some reason the base visitor doesn't visit the attribute type base.Visit(attribute); }
/// <summary> /// Performs some computation with the given custom attribute. /// </summary> public void Visit(ICustomAttribute customAttribute) { if (customAttribute.Constructor is Dummy) this.ReportError(MetadataError.IncompleteNode, customAttribute, "Constructor"); else if (customAttribute.Type is Dummy) this.ReportError(MetadataError.IncompleteNode, customAttribute, "Type"); else { if (!TypeHelper.TypesAreEquivalent(customAttribute.Constructor.ContainingType, customAttribute.Type)) this.ReportError(MetadataError.CustomAttributeTypeIsNotConstructorContainer, customAttribute); if (customAttribute.Constructor.ResolvedMethod != Dummy.Method) { if (!customAttribute.Constructor.ResolvedMethod.IsConstructor) this.ReportError(MetadataError.CustomAttributeConstructorIsBadReference, customAttribute); if (!IteratorHelper.EnumerableHasLength(customAttribute.Arguments, customAttribute.Constructor.ResolvedMethod.ParameterCount)) { if (this.validator.currentSecurityAttribute == null || customAttribute.Constructor.ResolvedMethod.ParameterCount != 1 || IteratorHelper.EnumerableIsNotEmpty(customAttribute.Arguments)) this.ReportError(MetadataError.EnumerationCountIsInconsistentWithCountProperty, customAttribute, "Arguments"); } //TODO: check that args match the types of the construtor param } } if (!IteratorHelper.EnumerableHasLength(customAttribute.NamedArguments, customAttribute.NumberOfNamedArguments)) this.ReportError(MetadataError.EnumerationCountIsInconsistentWithCountProperty, customAttribute, "NamedArguments"); //TODO: check that named args match the types of the attribute field/property. }
public virtual bool Include(ICustomAttribute attribute) { return true; }
/// <summary> /// Provides the host with an opportunity to substitute a custom attribute with another during metadata reading. /// This avoids the cost of rewriting the entire unit in order to make such changes. /// </summary> /// <param name="containingUnit">The unit that contains the custom attribute.</param> /// <param name="customAttribute">The custom attribute to rewrite (fix up).</param> /// <returns> /// Usually the value in customAttribute, but occassionally another custom attribute. /// </returns> public ICustomAttribute Rewrite(IUnit containingUnit, ICustomAttribute customAttribute) { Contract.Requires(containingUnit != null); Contract.Requires(customAttribute != null); Contract.Ensures(Contract.Result<ICustomAttribute>() != null); throw new NotImplementedException(); }
public virtual void onMetadataElement(ICustomAttribute customAttribute) { }
/// <summary> /// Traverses the custom attribute. /// </summary> public void Traverse(ICustomAttribute customAttribute) { Contract.Requires(customAttribute != null); if (this.preorderVisitor != null) this.preorderVisitor.Visit(customAttribute); if (this.stopTraversal) return; this.TraverseChildren(customAttribute); if (this.stopTraversal) return; if (this.postorderVisitor != null) this.postorderVisitor.Visit(customAttribute); }
//^ ensures this.path.Count == old(this.path.Count); /// <summary> /// Performs some computation with the given custom attribute. /// </summary> /// <param name="customAttribute"></param> public virtual void Visit(ICustomAttribute customAttribute) { if (this.stopTraversal) return; //^ int oldCount = this.path.Count; this.path.Push(customAttribute); this.Visit(customAttribute.Arguments); this.Visit(customAttribute.Constructor); this.Visit(customAttribute.NamedArguments); //^ assume this.path.Count == oldCount+1; //True because all of the virtual methods of this class promise not decrease this.path.Count. this.path.Pop(); }
private IEnumerable<Instruction> GetAttributeInstanceInstructions( ILProcessor processor, ICustomAttribute attribute, MethodDefinition method, VariableDefinition attributeVariableDefinition, VariableDefinition methodVariableDefinition) { var getMethodFromHandleRef = this._referenceFinder.GetMethodReference(typeof(MethodBase), md => md.Name == "GetMethodFromHandle" && md.Parameters.Count == 2); var getTypeof = this._referenceFinder.GetMethodReference(typeof(Type), md => md.Name == "GetTypeFromHandle"); var ctor = this._referenceFinder.GetMethodReference(typeof(Activator), md => md.Name == "CreateInstance" && md.Parameters.Count == 1); /* // Code size 23 (0x17) .maxstack 1 .locals init ([0] class SimpleTest.IntersectMethodsMarkedByAttribute i) IL_0000: nop IL_0001: ldtoken SimpleTest.IntersectMethodsMarkedByAttribute IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000b: call object [mscorlib]System.Activator::CreateInstance(class [mscorlib]System.Type) IL_0010: castclass SimpleTest.IntersectMethodsMarkedByAttribute IL_0015: stloc.0 IL_0016: ret */ return new List<Instruction> { processor.Create(OpCodes.Nop), processor.Create(OpCodes.Ldtoken, method), processor.Create(OpCodes.Ldtoken, method.DeclaringType), processor.Create(OpCodes.Call, getMethodFromHandleRef), // Push method onto the stack, GetMethodFromHandle, result on stack processor.Create(OpCodes.Stloc_S, methodVariableDefinition), // Store method in __fody$method processor.Create(OpCodes.Nop), processor.Create(OpCodes.Ldtoken, attribute.AttributeType), processor.Create(OpCodes.Call,getTypeof), processor.Create(OpCodes.Call,ctor), processor.Create(OpCodes.Castclass, attribute.AttributeType), processor.Create(OpCodes.Stloc_S, attributeVariableDefinition), /* * processor.Create(OpCodes.Ldloc_S, methodVariableDefinition), processor.Create(OpCodes.Ldtoken, attribute.AttributeType), processor.Create(OpCodes.Call, getTypeFromHandleRef), // Push method + attribute onto the stack, GetTypeFromHandle, result on stack processor.Create(OpCodes.Ldc_I4_0), processor.Create(OpCodes.Callvirt, getCustomAttributesRef), // Push false onto the stack (result still on stack), GetCustomAttributes processor.Create(OpCodes.Ldc_I4_0), processor.Create(OpCodes.Ldelem_Ref), // Get 0th index from result processor.Create(OpCodes.Castclass, attribute.AttributeType), processor.Create(OpCodes.Stloc_S, attributeVariableDefinition) // Cast to attribute stor in __fody$attribute */ }; }
/// <summary> /// Provides the host with an opportunity to substitute a custom attribute with another during metadata reading. /// This avoids the cost of rewriting the entire unit in order to make such changes. /// </summary> /// <param name="containingUnit">The unit that contains the custom attribute.</param> /// <param name="customAttribute">The custom attribute to rewrite (fix up).</param> /// <returns> /// Usually the value in customAttribute, but occassionally another custom attribute. /// </returns> public virtual ICustomAttribute Rewrite(IUnit containingUnit, ICustomAttribute customAttribute) { return customAttribute; }
public void Visit(ICustomAttribute customAttribute) { Contract.Assume(false); }
/// <summary> /// Determine if the specified attribute is of a special type, and if so return a code representing it. /// This is usefull for types not alread in IPlatformType /// </summary> public static SpecialAttribute GetAttributeType(ICustomAttribute attr) { // This seems like a big hack // Perhaps I should add this as a PlatformType and use AttributeHelper.Contains instead? // There's got to be a cleaner way to do this? var type = attr.Type; var typeName = TypeHelper.GetTypeName(type); var attrUnit = TypeHelper.GetDefiningUnitReference(type); var mscorlibUnit = TypeHelper.GetDefiningUnitReference(type.PlatformType.SystemObject); // mscorlib if (UnitHelper.UnitsAreEquivalent(attrUnit, mscorlibUnit) || (attrUnit != null && mscorlibUnit != null && attrUnit.ResolvedUnit == mscorlibUnit.ResolvedUnit)) { switch (typeName) { case "System.FlagsAttribute": return SpecialAttribute.Flags; case "System.Runtime.CompilerServices.FixedBufferAttribute": return SpecialAttribute.FixedBuffer; case "System.ParamArrayAttribute": return SpecialAttribute.ParamArray; case "System.Reflection.DefaultMemberAttribute": return SpecialAttribute.DefaultMemberAttribute; case "System.Reflection.AssemblyKeyFileAttribute": return SpecialAttribute.AssemblyKeyFile; case "System.Reflection.AssemblyDelaySignAttribute": return SpecialAttribute.AssemblyDelaySign; } } else if (attrUnit != null && attrUnit.Name.Value == "System.Core") { switch (typeName) { case "System.Runtime.CompilerServices.ExtensionAttribute": return SpecialAttribute.Extension; } } return SpecialAttribute.None; }
/// <summary> /// Performs some computation with the given custom attribute. /// </summary> public virtual void Visit(ICustomAttribute customAttribute) { }