public TestCaseMethodCompiler(TestCaseAssemblyCompiler assemblyCompiler, ICompilationSchedulerStage compilationScheduler, RuntimeType type, RuntimeMethod method) : base(assemblyCompiler, type, method, null, compilationScheduler) { // Populate the pipeline this.Pipeline.AddRange(new IMethodCompilerStage[] { new DecodingStage(), new BasicBlockBuilderStage(), new ExceptionPrologueStage(), new OperandDeterminationStage(), new StaticAllocationResolutionStage(), new CILTransformationStage(), //new CILLeakGuardStage() { MustThrowCompilationException = true }, new EdgeSplitStage(), new DominanceCalculationStage(), new PhiPlacementStage(), new EnterSSAStage(), new ConstantPropagationStage(ConstantPropagationStage.PropagationStage.PreFolding), new ConstantFoldingStage() , new ConstantPropagationStage(ConstantPropagationStage.PropagationStage.PostFolding), new LeaveSSA(), new StrengthReductionStage(), new StackLayoutStage(), new PlatformStubStage(), //new BlockReductionStage(), //new LoopAwareBlockOrderStage(), new SimpleTraceBlockOrderStage(), //new ReverseBlockOrderStage(), // reverse all the basic blocks and see if it breaks anything //new BasicBlockOrderStage() new CodeGenerationStage(), }); }
public override MethodCompilerBase CreateMethodCompiler(RuntimeType type, RuntimeMethod method) { IArchitecture arch = this.Architecture; MethodCompilerBase mc = new TestCaseMethodCompiler(this.Pipeline.Find<IAssemblyLinker>(), this.Architecture, this.Assembly, type, method); arch.ExtendMethodCompilerPipeline(mc.Pipeline); return mc; }
internal static RuntimeType AddElementTypes(SerializationInfo info, RuntimeType type) { List<int> elementTypes = new List<int>(); while(type.HasElementType) { if (type.IsSzArray) { elementTypes.Add(SzArray); } else if (type.IsArray) { elementTypes.Add(type.GetArrayRank()); elementTypes.Add(Array); } else if (type.IsPointer) { elementTypes.Add(Pointer); } else if (type.IsByRef) { elementTypes.Add(ByRef); } type = (RuntimeType)type.GetElementType(); } info.AddValue("ElementTypes", elementTypes.ToArray(), typeof(int[])); return type; }
protected string FormatRuntimeType(RuntimeType type) { if (!showTokenValues.Checked) return type.Namespace + Type.Delimiter + type.Name; return "[" + TokenToString(type.Token) + "] " + type.Namespace + Type.Delimiter + type.Name; }
public static void GetSerializationInfo( SerializationInfo info, String name, RuntimeType reflectedClass, String signature, String signature2, MemberTypes type, Type[] genericArguments) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); String assemblyName = reflectedClass.Module.Assembly.FullName; String typeName = reflectedClass.FullName; info.SetType(typeof(MemberInfoSerializationHolder)); info.AddValue("Name", name, typeof(String)); info.AddValue("AssemblyName", assemblyName, typeof(String)); info.AddValue("ClassName", typeName, typeof(String)); info.AddValue("Signature", signature, typeof(String)); info.AddValue("Signature2", signature2, typeof(String)); info.AddValue("MemberType", (int)type); info.AddValue("GenericArguments", genericArguments, typeof(Type[])); }
/// <summary> /// Initializes a new instance of the <see cref="CilGenericType"/> class. /// </summary> /// <param name="module">The module.</param> /// <param name="baseGenericType">Type of the base generic.</param> /// <param name="genericTypeInstanceSignature">The generic type instance signature.</param> /// <param name="token">The token.</param> /// <param name="typeModule">The type module.</param> public CilGenericType(ITypeModule module, RuntimeType baseGenericType, GenericInstSigType genericTypeInstanceSignature, Token token, ITypeModule typeModule) : base(module, token, baseGenericType.BaseType) { Debug.Assert(baseGenericType is CilRuntimeType); this.signature = genericTypeInstanceSignature; this.baseGenericType = baseGenericType as CilRuntimeType; base.Attributes = baseGenericType.Attributes; base.Namespace = baseGenericType.Namespace; if (this.baseGenericType.IsNested) { // TODO: find generic type ; } // TODO: if this is a nested types, add enclosing type(s) into genericArguments first this.genericArguments = signature.GenericArguments; base.Name = GetName(typeModule); ResolveMethods(); ResolveFields(); this.containsOpenGenericArguments = CheckContainsOpenGenericParameters(); }
/// <summary> /// Construct from a string /// </summary> /// <param name="s">A string representing the runtime</param> public RuntimeFramework(string s) { runtime = RuntimeType.Any; version = new Version(); string[] parts = s.Split(new char[] { '-' }); if (parts.Length == 2) { runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), parts[0], true); string vstring = parts[1]; if (vstring != "") version = new Version(vstring); } else if (char.ToLower(s[0]) == 'v') { version = new Version(s.Substring(1)); } else if (char.IsNumber(s[0])) { version = new Version(s); } else { runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), s, true); version = Environment.Version; } }
public void ConstructorIsInvoked() { RuntimeMember method = new RuntimeType(instance.GetType()).GetConstructor(0); Assert.IsNotNull(method); TypedValue result = method.Invoke(new object[] {}); Assert.AreEqual(typeof(SampleClass), result.Type); }
private static bool AttributeUsageCheck(RuntimeType attributeType, bool mustBeInheritable, object[] attributes, IList derivedAttributes) { AttributeUsageAttribute attributeUsage = null; if (mustBeInheritable) { attributeUsage = GetAttributeUsage(attributeType); if (!attributeUsage.Inherited) { return false; } } if (derivedAttributes != null) { for (int i = 0; i < derivedAttributes.Count; i++) { if (derivedAttributes[i].GetType() == attributeType) { if (attributeUsage == null) { attributeUsage = GetAttributeUsage(attributeType); } return attributeUsage.AllowMultiple; } } } return true; }
/// <summary> /// Builds the method table. /// </summary> /// <param name="type">The type.</param> public void BuildMethodTable(RuntimeType type) { // HINT: The method table is offset by a four pointers: // 1. interface dispatch table pointer // 2. type pointer - contains the type information pointer, used to realize object.GetType(). // 3. interface bitmap // 4. parent type (if any) List<string> headerlinks = new List<string>(); // 1. interface dispatch table pointer if (type.Interfaces.Count == 0) headerlinks.Add(null); else headerlinks.Add(type.FullName + @"$itable"); // 2. type pointer - contains the type information pointer, used to realize object.GetType(). headerlinks.Add(null); // TODO: GetType() // 3. interface bitmap if (type.Interfaces.Count == 0) headerlinks.Add(null); else headerlinks.Add(type.FullName + @"$ibitmap"); // 4. parent type (if any) if (type.BaseType == null) headerlinks.Add(null); else headerlinks.Add(type.BaseType + @"$mtable"); IList<RuntimeMethod> methodTable = typeLayout.GetMethodTable(type); AskLinkerToCreateMethodTable(type.FullName + @"$mtable", methodTable, headerlinks); }
public static String ComputeToString(MethodBase contextMethod, RuntimeType[] methodTypeArguments, RuntimeParameterInfo[] runtimeParametersAndReturn) { StringBuilder sb = new StringBuilder(30); sb.Append(runtimeParametersAndReturn[0].ParameterTypeString); sb.Append(' '); sb.Append(contextMethod.Name); if (methodTypeArguments.Length != 0) { String sep = ""; sb.Append('['); foreach (RuntimeType methodTypeArgument in methodTypeArguments) { sb.Append(sep); sep = ","; String name = methodTypeArgument.InternalNameIfAvailable; if (name == null) name = ToStringUtils.UnavailableType; sb.Append(methodTypeArgument.Name); } sb.Append(']'); } sb.Append('('); sb.Append(ComputeParametersString(runtimeParametersAndReturn, 1)); sb.Append(')'); return sb.ToString(); }
public Signature(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType) { SignatureStruct signature = new SignatureStruct(); GetSignature(ref signature, null, 0, fieldHandle.Value, null, declaringType); GC.KeepAlive(fieldHandle); this.m_signature = signature; }
public ExplorerMethodCompiler(ExplorerAssemblyCompiler assemblyCompiler, ICompilationSchedulerStage compilationScheduler, RuntimeType type, RuntimeMethod method, CompilerOptions compilerOptions) : base(assemblyCompiler, type, method, null, compilationScheduler) { // Populate the pipeline this.Pipeline.AddRange(new IMethodCompilerStage[] { new DecodingStage(), new BasicBlockBuilderStage(), new ExceptionPrologueStage(), new OperandDeterminationStage(), //new SingleUseMarkerStage(), //new OperandUsageAnalyzerStage(), new StaticAllocationResolutionStage(), new CILTransformationStage(), (compilerOptions.EnableSSA) ? new EdgeSplitStage() : null, (compilerOptions.EnableSSA) ? new DominanceCalculationStage() : null, (compilerOptions.EnableSSA) ? new PhiPlacementStage() : null, (compilerOptions.EnableSSA) ? new EnterSSAStage() : null, (compilerOptions.EnableSSA) ? new SSAOptimizations() : null, //(compilerOptions.EnableSSA) ? new ConstantPropagationStage(ConstantPropagationStage.PropagationStage.PreFolding) : null, //(compilerOptions.EnableSSA) ? new ConstantFoldingStage() : null, //(compilerOptions.EnableSSA) ? new ConstantPropagationStage(ConstantPropagationStage.PropagationStage.PostFolding) : null, (compilerOptions.EnableSSA) ? new LeaveSSA() : null, new StrengthReductionStage(), new StackLayoutStage(), new PlatformStubStage(), //new LoopAwareBlockOrderStage(), new SimpleTraceBlockOrderStage(), //new SimpleRegisterAllocatorStage(), new CodeGenerationStage(), }); }
internal static Attribute GetCustomAttribute(RuntimeType type) { if ((type.Attributes & TypeAttributes.Import) == TypeAttributes.AnsiClass) { return null; } return new ComImportAttribute(); }
internal static Attribute GetCustomAttribute(RuntimeType type) { if ((type.Attributes & TypeAttributes.Serializable) != TypeAttributes.Serializable) { return null; } return new SerializableAttribute(); }
internal ConstructorCallMessage(object[] callSiteActivationAttributes, object[] womAttr, object[] typeAttr, RuntimeType serverType) { this._activationType = serverType; this._activationTypeName = RemotingServices.GetDefaultQualifiedTypeName(this._activationType); this._callSiteActivationAttributes = callSiteActivationAttributes; this._womGlobalAttributes = womAttr; this._typeAttributes = typeAttr; }
private RuntimeSyntheticConstructorInfo(SyntheticMethodId syntheticMethodId, RuntimeType declaringType, RuntimeType[] runtimeParameterTypesAndReturn, InvokerOptions options, Func<Object, Object[], Object> invoker) { _syntheticMethodId = syntheticMethodId; _declaringType = declaringType; _options = options; _invoker = invoker; _runtimeParameterTypesAndReturn = runtimeParameterTypesAndReturn; }
internal RuntimeConstructorInfo(RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeType.RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, System.Reflection.BindingFlags bindingFlags) { this.m_bindingFlags = bindingFlags; this.m_reflectedTypeCache = reflectedTypeCache; this.m_declaringType = declaringType; this.m_handle = handle.Value; this.m_methodAttributes = methodAttributes; }
/// <summary> /// Initializes a new instance of the <see cref="CilRuntimeField"/> class. /// </summary> /// <param name="module">The module.</param> /// <param name="name">The name.</param> /// <param name="signature">The signature.</param> /// <param name="token">The token.</param> /// <param name="offset">The offset.</param> /// <param name="rva">The rva.</param> /// <param name="declaringType">Type of the declaring.</param> /// <param name="attributes">The attributes.</param> public CilRuntimeField(ITypeModule module, string name, FieldSignature signature, Token token, uint offset, uint rva, RuntimeType declaringType, FieldAttributes attributes) : base(module, token, declaringType) { this.Name = name; this.Signature = signature; base.Attributes = attributes; base.RVA = rva; }
internal object GetEventProvider(RuntimeType t) { object data = this.GetData(t); if (data == null) { data = this.CreateEventProvider(t); } return data; }
private string GetMethodTableForType(RuntimeType allocatedType) { if (!allocatedType.IsValueType) { return allocatedType.FullName + @"$mtable"; } return null; }
internal RuntimeConstructorInfo(RuntimeMethodHandle handle, RuntimeTypeHandle declaringTypeHandle, RuntimeType.RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, System.Reflection.BindingFlags bindingFlags) { this.m_bindingFlags = bindingFlags; this.m_handle = handle; this.m_reflectedTypeCache = reflectedTypeCache; this.m_declaringType = declaringTypeHandle.GetRuntimeType(); this.m_parameters = null; this.m_toString = null; this.m_methodAttributes = methodAttributes; }
/// <summary> /// Initializes a new instance of the <see cref="CilGenericMethod"/> class. /// </summary> /// <param name="module">The module.</param> /// <param name="genericMethod">The generic method.</param> /// <param name="signature">The signature.</param> /// <param name="declaringType">Type of the declaring.</param> public CilGenericMethod(ITypeModule module, CilRuntimeMethod genericMethod, MethodSignature signature, RuntimeType declaringType) : base(module, genericMethod.Token, declaringType) { this.Signature = signature; this.Attributes = genericMethod.Attributes; this.ImplAttributes = genericMethod.ImplAttributes; this.Rva = genericMethod.Rva; this.Parameters = genericMethod.Parameters; base.Name = genericMethod.Name; }
/// <summary> /// Creates a method compiler /// </summary> /// <param name="type">The type.</param> /// <param name="method">The method to compile.</param> /// <returns> /// An instance of a MethodCompilerBase for the given type/method pair. /// </returns> public override MethodCompilerBase CreateMethodCompiler(RuntimeType type, RuntimeMethod method) { MethodCompilerBase mc = new AotMethodCompiler( this, type, method ); this.Architecture.ExtendMethodCompilerPipeline(mc.Pipeline); return mc; }
public RuntimePseudoCustomAttributeData(RuntimeType attributeType, IList<CustomAttributeTypedArgument> constructorArguments, IList<CustomAttributeNamedArgument> namedArguments) { _attributeType = attributeType; if (constructorArguments == null) constructorArguments = Array.Empty<CustomAttributeTypedArgument>(); _constructorArguments = new ReadOnlyCollection<CustomAttributeTypedArgument>(constructorArguments); if (namedArguments == null) namedArguments = Array.Empty<CustomAttributeNamedArgument>(); _namedArguments = new ReadOnlyCollection<CustomAttributeNamedArgument>(namedArguments); return; }
/// <summary> /// Initializes a new instance of the <see cref="CilRuntimeMethod"/> class. /// </summary> /// <param name="module">The module.</param> /// <param name="name">The name.</param> /// <param name="signature">The signature.</param> /// <param name="token">The token.</param> /// <param name="declaringType">Type of the declaring.</param> /// <param name="methodAttributes">The method attributes.</param> /// <param name="methodImplAttributes">The method impl attributes.</param> /// <param name="rva">The rva.</param> public CilRuntimeMethod(ITypeModule module, string name, MethodSignature signature, Token token, RuntimeType declaringType, MethodAttributes methodAttributes, MethodImplAttributes methodImplAttributes, uint rva) : base(module, token, declaringType) { base.Attributes = methodAttributes; base.ImplAttributes = methodImplAttributes; base.Rva = rva; this.Name = name; this.Signature = signature; this.Parameters = new List<RuntimeParameter>(); }
/// <summary> /// Construct from a runtime type and version. If the version has /// two parts, it is taken as a framework version. If it has three /// or more, it is taken as a CLR version. In either case, the other /// version is deduced based on the runtime type and provided version. /// </summary> /// <param name="runtime">The runtime type of the framework</param> /// <param name="version">The version of the framework</param> public RuntimeFramework(RuntimeType runtime, Version version) { Runtime = runtime; if (version.Build < 0) InitFromFrameworkVersion(version); else InitFromClrVersion(version); DisplayName = GetDefaultDisplayName(runtime, version); }
public BootstrapJob(RuntimeType jobType, Dictionary<string, string> jobParameters) { if (jobType == null) throw new ArgumentNullException("jobType"); if (jobParameters == null) throw new ArgumentNullException("jobParameters"); JobType = jobType; JobParameters = jobParameters; }
/// <summary> /// Creates a method compiler /// </summary> /// <param name="type">The type.</param> /// <param name="method">The method to compile.</param> /// <returns> /// An instance of a MethodCompilerBase for the given type/method pair. /// </returns> public override IMethodCompiler CreateMethodCompiler(ICompilationSchedulerStage compilationScheduler, RuntimeType type, RuntimeMethod method) { IMethodCompiler mc = new AotMethodCompiler( this, compilationScheduler, type, method ); this.Architecture.ExtendMethodCompilerPipeline(mc.Pipeline); return mc; }
private void AllocateStaticFields(RuntimeType type) { foreach (RuntimeField field in type.Fields) { if (field.IsStaticField && !field.IsLiteralField) { // Assign a memory slot to the static & initialize it, if there's initial data set CreateStaticField(field); } } }
// // Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen // saves the right instantiations // private static EqualityComparer <T> CreateComparer() { Contract.Ensures(Contract.Result <EqualityComparer <T> >() != null); object result = null; RuntimeType t = (RuntimeType)typeof(T); // Specialize type byte for performance reasons if (t == typeof(byte)) { result = new ByteEqualityComparer(); } // If T implements IEquatable<T> return a GenericEqualityComparer<T> else if (typeof(IEquatable <T>).IsAssignableFrom(t)) { result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericEqualityComparer <int>), t); } else if (default(T) == null) // Reference type/Nullable { // If T is a Nullable<U> where U implements IEquatable<U> return a NullableEqualityComparer<U> if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable <>)) { RuntimeType u = (RuntimeType)t.GetGenericArguments()[0]; if (typeof(IEquatable <>).MakeGenericType(u).IsAssignableFrom(u)) { result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableEqualityComparer <int>), u); } } } // See the METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST and METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST_LONG cases in getILIntrinsicImplementation else if (t.IsEnum) { TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(t)); // Depending on the enum type, we need to special case the comparers so that we avoid boxing // Note: We have different comparers for Short and SByte because for those types we need to make sure we call GetHashCode on the actual underlying type as the // implementation of GetHashCode is more complex than for the other types. switch (underlyingTypeCode) { case TypeCode.Int16: // short result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ShortEnumEqualityComparer <short>), t); break; case TypeCode.SByte: result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(SByteEnumEqualityComparer <sbyte>), t); break; case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Byte: case TypeCode.UInt16: //ushort result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(EnumEqualityComparer <int>), t); break; case TypeCode.Int64: case TypeCode.UInt64: result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(LongEnumEqualityComparer <long>), t); break; } } return(result != null ? (EqualityComparer <T>)result : new ObjectEqualityComparer <T>()); // Fallback to ObjectEqualityComparer, which uses boxing }
private static Object nativeGetSafeUninitializedObject(RuntimeType type) { return(System.Runtime.Remoting.Activation.ActivationServices.AllocateUninitializedClassInstance(type)); }
private unsafe void Init(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] signature, Type owner, Module m, bool skipVisibility, bool transparentMethod, ref StackCrawlMark stackMark) { DynamicMethod.CheckConsistency(attributes, callingConvention); // check and store the signature if (signature != null) { m_parameterTypes = new RuntimeType[signature.Length]; for (int i = 0; i < signature.Length; i++) { if (signature[i] == null) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidTypeInSignature")); } m_parameterTypes[i] = signature[i].UnderlyingSystemType as RuntimeType; if (m_parameterTypes[i] == null || !(m_parameterTypes[i] is RuntimeType) || m_parameterTypes[i] == (RuntimeType)typeof(void)) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidTypeInSignature")); } } } else { m_parameterTypes = Array.Empty <RuntimeType>(); } // check and store the return value m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : returnType.UnderlyingSystemType as RuntimeType; if ((m_returnType == null) || !(m_returnType is RuntimeType) || m_returnType.IsByRef) { throw new NotSupportedException(Environment.GetResourceString("Arg_InvalidTypeInRetType")); } if (transparentMethod) { Debug.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods"); m_module = GetDynamicMethodsModule(); if (skipVisibility) { m_restrictedSkipVisibility = true; } } else { Debug.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set"); Debug.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly"); Debug.Assert(m == null || owner == null, "m and owner cannot both be set"); if (m != null) { m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects. } else { RuntimeType rtOwner = null; if (owner != null) { rtOwner = owner.UnderlyingSystemType as RuntimeType; } if (rtOwner != null) { if (rtOwner.HasElementType || rtOwner.ContainsGenericParameters || rtOwner.IsGenericParameter || rtOwner.IsInterface) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForDynamicMethod")); } m_typeOwner = rtOwner; m_module = rtOwner.GetRuntimeModule(); } } m_skipVisibility = skipVisibility; } // initialize remaining fields m_ilGenerator = null; m_fInitLocals = true; m_methodHandle = null; if (name == null) { throw new ArgumentNullException(nameof(name)); } #if FEATURE_APPX if (AppDomain.ProfileAPICheck) { if (m_creatorAssembly == null) { m_creatorAssembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark); } if (m_creatorAssembly != null && !m_creatorAssembly.IsFrameworkAssembly()) { m_profileAPICheck = true; } } #endif // FEATURE_APPX m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention); }
// This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it // on Marshal for more consistent API surface. public static Type GetTypeFromCLSID(Guid clsid) => RuntimeType.GetTypeFromCLSIDImpl(clsid, null, throwOnError: false);
private RuntimeBlockedTypeInfo(RuntimeType runtimeType) { _asType = runtimeType; }
public MetaMethod GetMethod(string name) => RuntimeType.GetAnyMethod(name);
/// <summary> /// Construct from a runtime type and version. If the version has /// two parts, it is taken as a framework version. If it has three /// or more, it is taken as a CLR version. In either case, the other /// version is deduced based on the runtime type and provided version. /// </summary> /// <param name="runtime">The runtime type of the framework</param> /// <param name="version">The version of the framework</param> public RuntimeFramework(RuntimeType runtime, Version version) : this(runtime, version, null) { }
internal static bool IsDefined(RuntimeType type) { return((type.Attributes & TypeAttributes.Import) != 0); }
/// <summary> /// Get all custom attributes of type <typeparamref name="TAttribute"/>. /// </summary> /// <param name="inherit">True to find inherited attribute.</param> /// <param name="condition">Optional predicate to check attribute properties.</param> /// <returns>All attributes associated with type <typeparamref name="T"/>.</returns> public static IEnumerable <TAttribute> GetAll(bool inherit = false, Predicate <TAttribute>?condition = null) => from attr in RuntimeType.GetCustomAttributes <TAttribute>(inherit) where condition is null || condition(attr) select attr;
private Exception UncachedTryResolveCaseSensitive(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, out RuntimeType result) { result = null; foreach (QScopeDefinition scopeDefinition in currentAssembly.AllScopes) { MetadataReader reader = scopeDefinition.Reader; ScopeDefinitionHandle scopeDefinitionHandle = scopeDefinition.Handle; NamespaceDefinition namespaceDefinition; if (!TryResolveNamespaceDefinitionCaseSensitive(reader, scopeDefinitionHandle, out namespaceDefinition)) { continue; } // We've successfully drilled down the namespace chain. Now look for a top-level type matching the type name. IEnumerable <TypeDefinitionHandle> candidateTypes = namespaceDefinition.TypeDefinitions; foreach (TypeDefinitionHandle candidateType in candidateTypes) { TypeDefinition typeDefinition = candidateType.GetTypeDefinition(reader); if (typeDefinition.Name.StringEquals(_name, reader)) { result = reflectionDomain.ResolveTypeDefinition(reader, candidateType); return(null); } } // No match found in this assembly - see if there's a matching type forwarder. IEnumerable <TypeForwarderHandle> candidateTypeForwarders = namespaceDefinition.TypeForwarders; foreach (TypeForwarderHandle typeForwarderHandle in candidateTypeForwarders) { TypeForwarder typeForwarder = typeForwarderHandle.GetTypeForwarder(reader); if (typeForwarder.Name.StringEquals(_name, reader)) { RuntimeAssemblyName redirectedAssemblyName = typeForwarder.Scope.ToRuntimeAssemblyName(reader); AssemblyQualifiedTypeName redirectedTypeName = new AssemblyQualifiedTypeName(this, redirectedAssemblyName); return(redirectedTypeName.TryResolve(reflectionDomain, null, /*ignoreCase: */ false, out result)); } } } { String typeName = this.ToString(); String message = SR.Format(SR.TypeLoad_TypeNotFound, typeName, currentAssembly.FullName); return(ReflectionCoreNonPortable.CreateTypeLoadException(message, typeName)); } }
public override int GetHashCode() { unchecked { return((base.GetHashCode() * 397) ^ RuntimeType.GetHashCode()); } }
private RuntimeNoMetadataNamedTypeInfo(RuntimeType runtimeType) { _asType = runtimeType; }
private String _simpleAssemblyName; // (no strong name, version, etc.) internal RemotingTypeCachedData(RuntimeType ri) { RI = ri; }
public MetaField GetField(string name) => RuntimeType.GetAnyField(name);
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result) { result = null; RuntimeType elementType; Exception typeLoadException = ElementTypeName.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out elementType); if (typeLoadException != null) { return(typeLoadException); } result = ReflectionCoreNonPortable.GetPointerType(elementType); return(null); }
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result) { result = null; RuntimeType genericType; Exception typeLoadException = GenericType.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out genericType); if (typeLoadException != null) { return(typeLoadException); } LowLevelList <RuntimeType> genericTypeArguments = new LowLevelList <RuntimeType>(); foreach (TypeName genericTypeArgumentName in GenericArguments) { RuntimeType genericTypeArgument; typeLoadException = genericTypeArgumentName.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out genericTypeArgument); if (typeLoadException != null) { return(typeLoadException); } genericTypeArguments.Add(genericTypeArgument); } result = ReflectionCoreNonPortable.GetConstructedGenericType(genericType, genericTypeArguments.ToArray()); return(null); }
/// <summary> /// Initializes a new instance of the <see cref="CilRuntimeMethod"/> class. /// </summary> /// <param name="module">The module.</param> /// <param name="name">The name.</param> /// <param name="signature">The signature.</param> /// <param name="token">The token.</param> /// <param name="declaringType">Type of the declaring.</param> /// <param name="methodAttributes">The method attributes.</param> /// <param name="methodImplAttributes">The method impl attributes.</param> /// <param name="rva">The rva.</param> public CilRuntimeMethod(ITypeModule module, string name, MethodSignature signature, Token token, RuntimeType declaringType, MethodAttributes methodAttributes, MethodImplAttributes methodImplAttributes, uint rva) : base(module, token, declaringType) { base.Attributes = methodAttributes; base.ImplAttributes = methodImplAttributes; base.Rva = rva; this.Name = name; this.Signature = signature; this.Parameters = new List <RuntimeParameter>(); }
/// <summary> /// Returns attribute associated with the type <typeparamref name="T"/>. /// </summary> /// <param name="inherit">True to find inherited attribute.</param> /// <param name="condition">Optional predicate to check attribute properties.</param> /// <returns>Attribute associated with type <typeparamref name="T"/>; or null, if attribute doesn't exist.</returns> public static TAttribute?Get(bool inherit = false, Predicate <TAttribute>?condition = null) { var attr = RuntimeType.GetCustomAttribute <TAttribute>(inherit); return(attr is null || condition is null || condition(attr) ? attr : null); }
void CheckTypeFound <T>(string typeName) { RuntimeType sample = GetType(typeName); Assert.AreEqual(typeof(T), sample.Type); }
private static int SizeOfHelper(Type t, bool throwIfNotMarshalable) { RuntimeType rttype = (RuntimeType)t; return(SizeOfHelper(new QCallTypeHandle(ref rttype), throwIfNotMarshalable)); }
internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType);
public abstract Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result);
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result) { result = null; RuntimeType declaringType; Exception typeLoadException = DeclaringType.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out declaringType); if (typeLoadException != null) { return(typeLoadException); } TypeInfo nestedTypeInfo = FindDeclaredNestedType(declaringType.GetTypeInfo(), Name, ignoreCase); if (nestedTypeInfo == null) { return(new TypeLoadException(SR.Format(SR.TypeLoad_TypeNotFound, declaringType.FullName + "+" + Name, currentAssembly.FullName))); } result = (RuntimeType)(nestedTypeInfo.AsType()); return(null); }
private void Init(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] signature, Type owner, Module m, bool skipVisibility, bool transparentMethod) { DynamicMethod.CheckConsistency(attributes, callingConvention); // check and store the signature if (signature != null) { m_parameterTypes = new RuntimeType[signature.Length]; for (int i = 0; i < signature.Length; i++) { if (signature[i] == null) { throw new ArgumentException(SR.Arg_InvalidTypeInSignature); } m_parameterTypes[i] = signature[i].UnderlyingSystemType as RuntimeType; if (m_parameterTypes[i] == null || m_parameterTypes[i] == typeof(void)) { throw new ArgumentException(SR.Arg_InvalidTypeInSignature); } } } else { m_parameterTypes = Array.Empty <RuntimeType>(); } // check and store the return value m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : returnType.UnderlyingSystemType as RuntimeType; if (m_returnType == null) { throw new NotSupportedException(SR.Arg_InvalidTypeInRetType); } if (transparentMethod) { Debug.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods"); m_module = GetDynamicMethodsModule(); if (skipVisibility) { m_restrictedSkipVisibility = true; } } else { Debug.Assert(m != null || owner != null, "Constructor should ensure that either m or owner is set"); Debug.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly"); Debug.Assert(m == null || owner == null, "m and owner cannot both be set"); if (m != null) { m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects. } else { RuntimeType rtOwner = null; if (owner != null) { rtOwner = owner.UnderlyingSystemType as RuntimeType; } if (rtOwner != null) { if (rtOwner.HasElementType || rtOwner.ContainsGenericParameters || rtOwner.IsGenericParameter || rtOwner.IsInterface) { throw new ArgumentException(SR.Argument_InvalidTypeForDynamicMethod); } m_typeOwner = rtOwner; m_module = rtOwner.GetRuntimeModule(); } } m_skipVisibility = skipVisibility; } // initialize remaining fields m_ilGenerator = null; m_fInitLocals = true; m_methodHandle = null; if (name == null) { throw new ArgumentNullException(nameof(name)); } m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention); }
private static extern Object nativeGetUninitializedObject(RuntimeType type);
object IObjectReference.GetRealObject(StreamingContext context) { // If we've already deserialized the real object, use that rather than deserializing it again if (m_realObject != null) { return(m_realObject); } // If we don't have a real type to deserialize, then this is really a SafeSerializationManager // and we don't need to rebuild the object that we're standing in for. if (m_realType == null) { return(this); } // Look for the last type in GetRealType's inheritance hierarchy which implements a critical // deserialization constructor. This will be the object that we use as the deserialization // construction type to initialize via standard ISerializable semantics // First build up the chain starting at the type below Object and working to the real type we // serialized. Stack inheritanceChain = new Stack(); RuntimeType currentType = m_realType; do { inheritanceChain.Push(currentType); currentType = currentType.BaseType as RuntimeType; }while (currentType != typeof(object)); // Now look for the first type that does not implement the ISerializable .ctor. When we find // that, previousType will point at the last type that did implement the .ctor. We require that // the .ctor we invoke also be non-transparent RuntimeConstructorInfo serializationCtor = null; RuntimeType previousType = null; do { previousType = currentType; currentType = inheritanceChain.Pop() as RuntimeType; serializationCtor = currentType.GetSerializationCtor(); }while (serializationCtor != null && serializationCtor.IsSecurityCritical); // previousType is the last type that did implement the deserialization .ctor before the first // type that did not, so we'll grab it's .ctor to use for deserialization. BCLDebug.Assert(previousType != null, "We should have at least one inheritance from the base type"); serializationCtor = ObjectManager.GetConstructor(previousType); // Allocate an instance of the final type and run the selected .ctor on that instance to get the // standard ISerializable initialization done. object deserialized = FormatterServices.GetUninitializedObject(m_realType); serializationCtor.SerializationInvoke(deserialized, m_savedSerializationInfo, context); m_savedSerializationInfo = null; m_realType = null; // Save away the real object that was deserialized so that we can fill it in later, and return // it back as the object that should result from the final deserialization. m_realObject = deserialized; return(deserialized); }
private Exception TryResolveCaseInsensitive(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, out RuntimeType result) { String fullName = this.ToString().ToLower(); LowLevelDictionary <String, QHandle> dict = GetCaseInsensitiveTypeDictionary(currentAssembly); QHandle qualifiedHandle; if (!dict.TryGetValue(fullName, out qualifiedHandle)) { result = null; return(new TypeLoadException(SR.Format(SR.TypeLoad_TypeNotFound, this.ToString(), currentAssembly.FullName))); } MetadataReader reader = qualifiedHandle.Reader; Handle typeDefOrForwarderHandle = qualifiedHandle.Handle; HandleType handleType = typeDefOrForwarderHandle.HandleType; switch (handleType) { case HandleType.TypeDefinition: { TypeDefinitionHandle typeDefinitionHandle = typeDefOrForwarderHandle.ToTypeDefinitionHandle(reader); result = reflectionDomain.ResolveTypeDefinition(reader, typeDefinitionHandle); return(null); } case HandleType.TypeForwarder: { TypeForwarder typeForwarder = typeDefOrForwarderHandle.ToTypeForwarderHandle(reader).GetTypeForwarder(reader); ScopeReferenceHandle destinationScope = typeForwarder.Scope; RuntimeAssemblyName destinationAssemblyName = destinationScope.ToRuntimeAssemblyName(reader); RuntimeAssembly destinationAssembly; Exception exception = RuntimeAssembly.TryGetRuntimeAssembly(reflectionDomain, destinationAssemblyName, out destinationAssembly); if (exception != null) { result = null; return(exception); } return(TryResolveCaseInsensitive(reflectionDomain, destinationAssembly, out result)); } default: throw new InvalidOperationException(); } }
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result) { result = null; if (AssemblyName == null) { return(TypeName.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out result)); } else { RuntimeAssembly newAssembly; Exception assemblyLoadException = RuntimeAssembly.TryGetRuntimeAssembly(reflectionDomain, AssemblyName, out newAssembly); if (assemblyLoadException != null) { return(assemblyLoadException); } return(TypeName.TryResolve(reflectionDomain, newAssembly, ignoreCase, out result)); } }
private static extern void _RunClassConstructor(RuntimeType type);
internal MarshalAsAttribute(UnmanagedType val, VarEnum safeArraySubType, RuntimeType safeArrayUserDefinedSubType, UnmanagedType arraySubType, short sizeParamIndex, int sizeConst, string marshalType, RuntimeType marshalTypeRef, string marshalCookie, int iidParamIndex) { _val = val; SafeArraySubType = safeArraySubType; SafeArrayUserDefinedSubType = safeArrayUserDefinedSubType; IidParameterIndex = iidParamIndex; ArraySubType = arraySubType; SizeParamIndex = sizeParamIndex; SizeConst = sizeConst; MarshalType = marshalType; MarshalTypeRef = marshalTypeRef; MarshalCookie = marshalCookie; }