Exemple #1
0
        public static ITypeParameter[] Create(MetadataModule module, ITypeDefinition copyFromOuter, IEntity owner, GenericParameterHandleCollection handles)
        {
            if (handles.Count == 0)
            {
                return(Empty <ITypeParameter> .Array);
            }
            var outerTps = copyFromOuter.TypeParameters;
            var tps      = new ITypeParameter[handles.Count];
            int i        = 0;

            foreach (var handle in handles)
            {
                if (i < outerTps.Count)
                {
                    tps[i] = outerTps[i];
                }
                else
                {
                    tps[i] = Create(module, owner, i, handle);
                }
                i++;
            }
            return(tps);
        }
        void CollectNamespaces(IEntity entity, MetadataModule module, CodeMappingInfo mappingInfo = null)
        {
            if (entity == null || entity.MetadataToken.IsNil)
            {
                return;
            }
            if (mappingInfo == null)
            {
                mappingInfo = CSharpDecompiler.GetCodeMappingInfo(entity.ParentModule.PEFile, entity.MetadataToken);
            }
            switch (entity)
            {
            case ITypeDefinition td:
                namespaces.Add(td.Namespace);
                HandleAttributes(td.GetAttributes());
                HandleTypeParameters(td.TypeParameters);

                foreach (var baseType in td.DirectBaseTypes)
                {
                    CollectNamespacesForTypeReference(baseType);
                }

                foreach (var nestedType in td.NestedTypes)
                {
                    CollectNamespaces(nestedType, module, mappingInfo);
                }

                foreach (var field in td.Fields)
                {
                    CollectNamespaces(field, module, mappingInfo);
                }

                foreach (var property in td.Properties)
                {
                    CollectNamespaces(property, module, mappingInfo);
                }

                foreach (var @event in td.Events)
                {
                    CollectNamespaces(@event, module, mappingInfo);
                }

                foreach (var method in td.Methods)
                {
                    CollectNamespaces(method, module, mappingInfo);
                }
                break;

            case IField field:
                HandleAttributes(field.GetAttributes());
                CollectNamespacesForTypeReference(field.ReturnType);
                break;

            case IMethod method:
                HandleAttributes(method.GetAttributes());
                HandleAttributes(method.GetReturnTypeAttributes());
                CollectNamespacesForTypeReference(method.ReturnType);
                foreach (var param in method.Parameters)
                {
                    HandleAttributes(param.GetAttributes());
                    CollectNamespacesForTypeReference(param.Type);
                }
                HandleTypeParameters(method.TypeParameters);
                var reader = module.PEFile.Reader;
                var parts  = mappingInfo.GetMethodParts((MethodDefinitionHandle)method.MetadataToken).ToList();
                foreach (var part in parts)
                {
                    HandleOverrides(part.GetMethodImplementations(module.metadata), module);
                    var methodDef = module.metadata.GetMethodDefinition(part);
                    if (method.HasBody)
                    {
                        MethodBodyBlock body;
                        try {
                            body = reader.GetMethodBody(methodDef.RelativeVirtualAddress);
                        } catch (BadImageFormatException) {
                            continue;
                        }
                        CollectNamespacesFromMethodBody(body, module);
                    }
                }
                break;

            case IProperty property:
                HandleAttributes(property.GetAttributes());
                CollectNamespaces(property.Getter, module, mappingInfo);
                CollectNamespaces(property.Setter, module, mappingInfo);
                break;

            case IEvent @event:
                HandleAttributes(@event.GetAttributes());
                CollectNamespaces(@event.AddAccessor, module, mappingInfo);
                CollectNamespaces(@event.RemoveAccessor, module, mappingInfo);
                break;
            }
        }
        public static void CollectNamespaces(IEntity entity, MetadataModule module, HashSet <string> namespaces)
        {
            var collector = new RequiredNamespaceCollector(namespaces);

            collector.CollectNamespaces(entity, module);
        }
        void CollectNamespacesFromMethodBody(MethodBodyBlock method, MetadataModule module)
        {
            var metadata     = module.metadata;
            var instructions = method.GetILReader();

            if (!method.LocalSignature.IsNil)
            {
                ImmutableArray <IType> localSignature;
                try {
                    localSignature = module.DecodeLocalSignature(method.LocalSignature, genericContext);
                } catch (BadImageFormatException) {
                    // Issue #1211: ignore invalid local signatures
                    localSignature = ImmutableArray <IType> .Empty;
                }
                foreach (var type in localSignature)
                {
                    CollectNamespacesForTypeReference(type);
                }
            }

            foreach (var region in method.ExceptionRegions)
            {
                if (region.CatchType.IsNil)
                {
                    continue;
                }
                IType ty;
                try {
                    ty = module.ResolveType(region.CatchType, genericContext);
                } catch (BadImageFormatException) {
                    continue;
                }
                CollectNamespacesForTypeReference(ty);
            }

            while (instructions.RemainingBytes > 0)
            {
                ILOpCode opCode;
                try {
                    opCode = instructions.DecodeOpCode();
                } catch (BadImageFormatException) {
                    return;
                }
                switch (opCode.GetOperandType())
                {
                case OperandType.Field:
                case OperandType.Method:
                case OperandType.Sig:
                case OperandType.Tok:
                case OperandType.Type:
                    var handle = MetadataTokenHelpers.EntityHandleOrNil(instructions.ReadInt32());
                    if (handle.IsNil)
                    {
                        break;
                    }
                    switch (handle.Kind)
                    {
                    case HandleKind.TypeDefinition:
                    case HandleKind.TypeReference:
                    case HandleKind.TypeSpecification:
                        IType type;
                        try {
                            type = module.ResolveType(handle, genericContext);
                        } catch (BadImageFormatException) {
                            break;
                        }
                        CollectNamespacesForTypeReference(type);
                        break;

                    case HandleKind.FieldDefinition:
                    case HandleKind.MethodDefinition:
                    case HandleKind.MethodSpecification:
                    case HandleKind.MemberReference:
                        IMember member;
                        try {
                            member = module.ResolveEntity(handle, genericContext) as IMember;
                        } catch (BadImageFormatException) {
                            break;
                        }
                        CollectNamespacesForMemberReference(member);
                        break;

                    case HandleKind.StandaloneSignature:
                        StandaloneSignature sig;
                        try {
                            sig = metadata.GetStandaloneSignature((StandaloneSignatureHandle)handle);
                        } catch (BadImageFormatException) {
                            break;
                        }
                        if (sig.GetKind() == StandaloneSignatureKind.Method)
                        {
                            MethodSignature <IType> methodSig;
                            try {
                                methodSig = module.DecodeMethodSignature((StandaloneSignatureHandle)handle, genericContext);
                            } catch (BadImageFormatException) {
                                break;
                            }
                            CollectNamespacesForTypeReference(methodSig.ReturnType);
                            foreach (var paramType in methodSig.ParameterTypes)
                            {
                                CollectNamespacesForTypeReference(paramType);
                            }
                        }
                        break;
                    }
                    break;

                default:
                    try {
                        instructions.SkipOperand(opCode);
                    } catch (BadImageFormatException) {
                        return;
                    }
                    break;
                }
            }
        }
 void HandleOverrides(ImmutableArray <MethodImplementationHandle> immutableArray, MetadataModule module)
 {
     foreach (var h in immutableArray)
     {
         var methodImpl = module.metadata.GetMethodImplementation(h);
         CollectNamespacesForTypeReference(module.ResolveType(methodImpl.Type, genericContext));
         CollectNamespacesForMemberReference(module.ResolveMethod(methodImpl.MethodBody, genericContext));
         CollectNamespacesForMemberReference(module.ResolveMethod(methodImpl.MethodDeclaration, genericContext));
     }
 }
Exemple #6
0
 public MetadataModuleFixture()
 {
     this.route          = new RouteDescription("NamedDescription", "GET", "/things", ctx => true, typeof(object));
     this.metadataModule = new FakeNancyMetadataModule();
 }
 public AttributeBuilder(MetadataModule module, KnownAttribute attributeType)
     : this(module, module.GetAttributeType(attributeType))
 {
 }
Exemple #8
0
 public MetadataModuleFixture()
 {
     this.route          = new RouteDescription("NamedDescription", "GET", "/things", ctx => true);
     this.metadataModule = new FakeLegacyNancyMetadataModule();
 }
 public MetadataModuleFixture()
 {
     this.route = new RouteDescription("NamedDescription", "GET", "/things", ctx => true);
     this.metadataModule = new FakeNancyMetadataModule();
 }
Exemple #10
0
        internal static (IType returnType, IParameter[] parameters, ModifiedType returnTypeModifier) DecodeSignature(
            MetadataModule module, IParameterizedMember owner,
            MethodSignature <IType> signature, ParameterHandleCollection?parameterHandles,
            Nullability nullableContext, TypeSystemOptions typeSystemOptions,
            CustomAttributeHandleCollection?returnTypeAttributes = null)
        {
            var metadata = module.metadata;
            int i        = 0;

            IParameter[] parameters = new IParameter[signature.RequiredParameterCount
                                                     + (signature.Header.CallingConvention == SignatureCallingConvention.VarArgs ? 1 : 0)];
            IType parameterType;

            if (parameterHandles != null)
            {
                foreach (var parameterHandle in parameterHandles)
                {
                    var par = metadata.GetParameter(parameterHandle);
                    if (par.SequenceNumber == 0)
                    {
                        // "parameter" holds return type attributes.
                        // Note: for properties, the attributes normally stored on a method's return type
                        // are instead stored as normal attributes on the property.
                        // So MetadataProperty provides a non-null value for returnTypeAttributes,
                        // which then should be preferred over the attributes on the accessor's parameters.
                        if (returnTypeAttributes == null)
                        {
                            returnTypeAttributes = par.GetCustomAttributes();
                        }
                    }
                    else if (i < par.SequenceNumber && par.SequenceNumber <= signature.RequiredParameterCount)
                    {
                        // "Successive rows of the Param table that are owned by the same method shall be
                        // ordered by increasing Sequence value - although gaps in the sequence are allowed"
                        Debug.Assert(par.SequenceNumber <= signature.ParameterTypes.Length);
                        Debug.Assert(par.SequenceNumber <= parameters.Length);
                        // Fill gaps in the sequence with non-metadata parameters:
                        while (i < par.SequenceNumber - 1)
                        {
                            parameterType = ApplyAttributeTypeVisitor.ApplyAttributesToType(
                                signature.ParameterTypes[i], module.Compilation, null, metadata, typeSystemOptions, nullableContext);
                            parameters[i] = new DefaultParameter(parameterType, name: string.Empty, owner,
                                                                 referenceKind: parameterType.Kind == TypeKind.ByReference ? ReferenceKind.Ref : ReferenceKind.None);
                            i++;
                        }
                        parameterType = ApplyAttributeTypeVisitor.ApplyAttributesToType(
                            signature.ParameterTypes[i], module.Compilation,
                            par.GetCustomAttributes(), metadata, typeSystemOptions, nullableContext);
                        parameters[i] = new MetadataParameter(module, owner, parameterType, parameterHandle);
                        i++;
                    }
                }
            }
            while (i < signature.RequiredParameterCount)
            {
                parameterType = ApplyAttributeTypeVisitor.ApplyAttributesToType(
                    signature.ParameterTypes[i], module.Compilation, null, metadata, typeSystemOptions, nullableContext);
                parameters[i] = new DefaultParameter(parameterType, name: string.Empty, owner,
                                                     referenceKind: parameterType.Kind == TypeKind.ByReference ? ReferenceKind.Ref : ReferenceKind.None);
                i++;
            }
            if (signature.Header.CallingConvention == SignatureCallingConvention.VarArgs)
            {
                parameters[i] = new DefaultParameter(SpecialType.ArgList, name: string.Empty, owner);
                i++;
            }
            Debug.Assert(i == parameters.Length);
            var returnType = ApplyAttributeTypeVisitor.ApplyAttributesToType(signature.ReturnType,
                                                                             module.Compilation, returnTypeAttributes, metadata, typeSystemOptions, nullableContext,
                                                                             isSignatureReturnType: true);

            return(returnType, parameters, signature.ReturnType as ModifiedType);
        }
Exemple #11
0
 public static void CollectAttributeNamespaces(MetadataModule module, HashSet <string> namespaces)
 {
     HandleAttributes(module.GetAssemblyAttributes(), namespaces);
     HandleAttributes(module.GetModuleAttributes(), namespaces);
 }
Exemple #12
0
        private static void GetAssemblyILCode(ReflectionDisassembler disassembler, string assemblyPath, MetadataModule module, ITextOutput output)
        {
            output.WriteLine("// " + assemblyPath);
            output.WriteLine();
            var peFile   = module.PEFile;
            var metadata = peFile.Metadata;

            disassembler.WriteAssemblyReferences(metadata);
            if (metadata.IsAssembly)
            {
                disassembler.WriteAssemblyHeader(peFile);
            }
            output.WriteLine();
            disassembler.WriteModuleHeader(peFile);
        }
Exemple #13
0
        private static ReflectionDisassembler CreateDisassembler(string assemblyPath, MetadataModule module, ITextOutput textOutput)
        {
            var dis = new ReflectionDisassembler(textOutput, CancellationToken.None)
            {
                DetectControlStructure  = true,
                ShowSequencePoints      = false,
                ShowMetadataTokens      = true,
                ExpandMemberDefinitions = true,
            };
            var resolver = new UniversalAssemblyResolver(assemblyPath,
                                                         throwOnError: true,
                                                         targetFramework: module.PEFile.Reader.DetectTargetFrameworkId());

            dis.AssemblyResolver = resolver;
            dis.DebugInfo        = null;

            return(dis);
        }
 internal МетаданныеМодуль(УзелМетаданных родитель, MetadataModule metadata) : base(родитель.Корень(), родитель, metadata.Name, metadata.FullName, metadata.Title)
 {
 }
Exemple #15
0
        internal static (IType, IParameter[]) DecodeSignature(MetadataModule module, IParameterizedMember owner, MethodSignature <IType> signature, ParameterHandleCollection?parameterHandles, Nullability nullableContext)
        {
            var metadata = module.metadata;
            int i        = 0;
            CustomAttributeHandleCollection?returnTypeAttributes = null;

            IParameter[] parameters = new IParameter[signature.RequiredParameterCount
                                                     + (signature.Header.CallingConvention == SignatureCallingConvention.VarArgs ? 1 : 0)];
            IType parameterType;

            if (parameterHandles != null)
            {
                foreach (var parameterHandle in parameterHandles)
                {
                    var par = metadata.GetParameter(parameterHandle);
                    if (par.SequenceNumber == 0)
                    {
                        // "parameter" holds return type attributes
                        returnTypeAttributes = par.GetCustomAttributes();
                    }
                    else if (par.SequenceNumber > 0 && i < signature.RequiredParameterCount)
                    {
                        // "Successive rows of the Param table that are owned by the same method shall be
                        // ordered by increasing Sequence value - although gaps in the sequence are allowed"
                        Debug.Assert(i < par.SequenceNumber);
                        // Fill gaps in the sequence with non-metadata parameters:
                        while (i < par.SequenceNumber - 1)
                        {
                            parameterType = ApplyAttributeTypeVisitor.ApplyAttributesToType(
                                signature.ParameterTypes[i], module.Compilation, null, metadata, module.TypeSystemOptions, nullableContext);
                            parameters[i] = new DefaultParameter(parameterType, name: string.Empty, owner,
                                                                 referenceKind: parameterType.Kind == TypeKind.ByReference ? ReferenceKind.Ref : ReferenceKind.None);
                            i++;
                        }
                        parameterType = ApplyAttributeTypeVisitor.ApplyAttributesToType(
                            signature.ParameterTypes[i], module.Compilation,
                            par.GetCustomAttributes(), metadata, module.TypeSystemOptions, nullableContext);
                        parameters[i] = new MetadataParameter(module, owner, parameterType, parameterHandle);
                        i++;
                    }
                }
            }
            while (i < signature.RequiredParameterCount)
            {
                parameterType = ApplyAttributeTypeVisitor.ApplyAttributesToType(
                    signature.ParameterTypes[i], module.Compilation, null, metadata, module.TypeSystemOptions, nullableContext);
                parameters[i] = new DefaultParameter(parameterType, name: string.Empty, owner,
                                                     referenceKind: parameterType.Kind == TypeKind.ByReference ? ReferenceKind.Ref : ReferenceKind.None);
                i++;
            }
            if (signature.Header.CallingConvention == SignatureCallingConvention.VarArgs)
            {
                parameters[i] = new DefaultParameter(SpecialType.ArgList, name: string.Empty, owner);
                i++;
            }
            Debug.Assert(i == parameters.Length);
            var returnType = ApplyAttributeTypeVisitor.ApplyAttributesToType(signature.ReturnType,
                                                                             module.Compilation, returnTypeAttributes, metadata, module.TypeSystemOptions, nullableContext);

            return(returnType, parameters);
        }
Exemple #16
0
 public static bool AllowsDecimalConstants(MetadataModule module)
 {
     return((module.TypeSystemOptions & TypeSystemOptions.DecimalConstants) == TypeSystemOptions.DecimalConstants);
 }
        internal MetadataTypeDefinition(MetadataModule module, TypeDefinitionHandle handle)
        {
            Debug.Assert(module != null);
            Debug.Assert(!handle.IsNil);
            this.module = module;
            this.handle = handle;
            var metadata = module.metadata;
            var td       = metadata.GetTypeDefinition(handle);

            this.attributes   = td.Attributes;
            this.fullTypeName = td.GetFullTypeName(metadata);
            // Find DeclaringType + KnownTypeCode:
            if (fullTypeName.IsNested)
            {
                this.DeclaringTypeDefinition = module.GetDefinition(td.GetDeclaringType());

                // Create type parameters:
                this.TypeParameters = MetadataTypeParameter.Create(module, this.DeclaringTypeDefinition, this, td.GetGenericParameters());
            }
            else
            {
                // Create type parameters:
                this.TypeParameters = MetadataTypeParameter.Create(module, this, td.GetGenericParameters());

                var topLevelTypeName = fullTypeName.TopLevelTypeName;
                for (int i = 0; i < KnownTypeReference.KnownTypeCodeCount; i++)
                {
                    var ktr = KnownTypeReference.Get((KnownTypeCode)i);
                    if (ktr != null && ktr.TypeName == topLevelTypeName)
                    {
                        this.KnownTypeCode = (KnownTypeCode)i;
                        break;
                    }
                }
            }
            // Find type kind:
            if ((attributes & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface)
            {
                this.Kind = TypeKind.Interface;
            }
            else if (td.IsEnum(metadata, out var underlyingType))
            {
                this.Kind = TypeKind.Enum;
                this.EnumUnderlyingType = module.Compilation.FindType(underlyingType.ToKnownTypeCode());
            }
            else if (td.IsValueType(metadata))
            {
                if (KnownTypeCode == KnownTypeCode.Void)
                {
                    this.Kind = TypeKind.Void;
                }
                else
                {
                    this.Kind        = TypeKind.Struct;
                    this.IsByRefLike = td.GetCustomAttributes().HasKnownAttribute(metadata, KnownAttribute.IsByRefLike);
                    this.IsReadOnly  = td.GetCustomAttributes().HasKnownAttribute(metadata, KnownAttribute.IsReadOnly);
                }
            }
            else if (td.IsDelegate(metadata))
            {
                this.Kind = TypeKind.Delegate;
            }
            else
            {
                this.Kind = TypeKind.Class;
                this.HasExtensionMethods = this.IsStatic &&
                                           (module.TypeSystemOptions & TypeSystemOptions.ExtensionMethods) == TypeSystemOptions.ExtensionMethods &&
                                           td.GetCustomAttributes().HasKnownAttribute(metadata, KnownAttribute.Extension);
            }
        }
Exemple #18
0
 public static bool IsDecimalConstant(MetadataModule module, CustomAttributeHandleCollection attributeHandles)
 {
     return(attributeHandles.HasKnownAttribute(module.metadata, KnownAttribute.DecimalConstant));
 }
 public AttributeListBuilder(MetadataModule module, int capacity)
 {
     Debug.Assert(module != null);
     this.module     = module;
     this.attributes = new List <IAttribute>(capacity);
 }
Exemple #20
0
 public DecompilerException(MetadataModule module, IEntity decompiledEntity, Exception innerException, string message = null)
     : base((message ?? "Error decompiling " + decompiledEntity?.FullName) + Environment.NewLine, innerException)
 {
     this.Module           = module;
     this.DecompiledEntity = decompiledEntity;
 }