diff options
author | Zoltan Varga <vargaz@gmail.com> | 2020-09-09 00:52:33 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-09-09 00:52:33 +0300 |
commit | 6e103e7191dcb17120032f2516cc7f8e9e04c32e (patch) | |
tree | a3ee2ea7450809dac229fc084683df3f335942ad /netcore/System.Private.CoreLib/src/System | |
parent | 427395f4c6a18466c26d0cf782bed106d05e77ae (diff) |
Remove netcore/ directory from the mono/mono repository. (#20361)
Diffstat (limited to 'netcore/System.Private.CoreLib/src/System')
123 files changed, 0 insertions, 28724 deletions
diff --git a/netcore/System.Private.CoreLib/src/System/ArgIterator.cs b/netcore/System.Private.CoreLib/src/System/ArgIterator.cs deleted file mode 100644 index 3b4d0a88050..00000000000 --- a/netcore/System.Private.CoreLib/src/System/ArgIterator.cs +++ /dev/null @@ -1,104 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System -{ - [StructLayout (LayoutKind.Auto)] - public ref struct ArgIterator - { -#pragma warning disable 169, 414 - IntPtr sig; - IntPtr args; - int next_arg; - int num_args; -#pragma warning restore 169, 414 - - [MethodImpl (MethodImplOptions.InternalCall)] - extern void Setup (IntPtr argsp, IntPtr start); - - public ArgIterator (RuntimeArgumentHandle arglist) - { - sig = IntPtr.Zero; - args = IntPtr.Zero; - next_arg = num_args = 0; - if (arglist.args == IntPtr.Zero) - throw new PlatformNotSupportedException (); - Setup (arglist.args, IntPtr.Zero); - } - - [CLSCompliant (false)] - unsafe public ArgIterator (RuntimeArgumentHandle arglist, void *ptr) - { - sig = IntPtr.Zero; - args = IntPtr.Zero; - next_arg = num_args = 0; - if (arglist.args == IntPtr.Zero) - throw new PlatformNotSupportedException (); - Setup (arglist.args, (IntPtr) ptr); - } - - public void End () - { - next_arg = num_args; - } - - public override bool Equals (object? o) - { - throw new NotSupportedException ("ArgIterator does not support Equals."); - } - - public override int GetHashCode () - { - return sig.GetHashCode (); - } - - [CLSCompliant (false)] - public TypedReference GetNextArg () - { - if (num_args == next_arg) - throw new InvalidOperationException ("Invalid iterator position."); - TypedReference result = new TypedReference (); - unsafe { - IntGetNextArg (&result); - } - return result; - } - - [MethodImpl (MethodImplOptions.InternalCall)] - extern unsafe void IntGetNextArg (void *res); - - [CLSCompliant (false)] - public TypedReference GetNextArg (RuntimeTypeHandle rth) - { - if (num_args == next_arg) - throw new InvalidOperationException ("Invalid iterator position."); - TypedReference result = new TypedReference (); - unsafe { - IntGetNextArgWithType (&result, rth.Value); - } - return result; - } - - [MethodImpl (MethodImplOptions.InternalCall)] - extern unsafe void IntGetNextArgWithType (void *res, IntPtr rth); - - public RuntimeTypeHandle GetNextArgType () - { - if (num_args == next_arg) - throw new InvalidOperationException ("Invalid iterator position."); - return new RuntimeTypeHandle (IntGetNextArgType ()); - } - - [MethodImpl (MethodImplOptions.InternalCall)] - extern IntPtr IntGetNextArgType (); - - public int GetRemainingCount () - { - return num_args - next_arg; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Array.Mono.cs b/netcore/System.Private.CoreLib/src/System/Array.Mono.cs deleted file mode 100644 index e65df0c13da..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Array.Mono.cs +++ /dev/null @@ -1,632 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Internal.Runtime.CompilerServices; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using Mono; -#if BIT64 -using nuint = System.UInt64; -#else -using nuint = System.UInt32; -#endif - -namespace System -{ - partial class Array - { - [StructLayout(LayoutKind.Sequential)] - private class RawData - { - public IntPtr Bounds; - public IntPtr Count; - public byte Data; - } - - public int Length { - [Intrinsic] - get => Length; - } - - public long LongLength { - get { - long length = GetLength (0); - - for (int i = 1; i < Rank; i++) { - length *= GetLength (i); - } - return length; - } - } - - public int Rank { - [Intrinsic] - get => Rank; - } - - public static unsafe void Clear (Array array, int index, int length) - { - if (array == null) - ThrowHelper.ThrowArgumentNullException (ExceptionArgument.array); - - int lowerBound = array.GetLowerBound (0); - int elementSize = array.GetElementSize (); - nuint numComponents = (nuint) Unsafe.As<RawData> (array).Count; - - int offset = index - lowerBound; - - if (index < lowerBound || offset < 0 || length < 0 || (uint) (offset + length) > numComponents) - ThrowHelper.ThrowIndexOutOfRangeException (); - - ref byte ptr = ref Unsafe.AddByteOffset (ref array.GetRawSzArrayData(), (uint) offset * (nuint) elementSize); - nuint byteLength = (uint) length * (nuint) elementSize; - - if (RuntimeHelpers.ObjectHasReferences (array)) - SpanHelpers.ClearWithReferences (ref Unsafe.As<byte, IntPtr> (ref ptr), byteLength / (uint)sizeof (IntPtr)); - else - SpanHelpers.ClearWithoutReferences (ref ptr, byteLength); - } - - public static void ConstrainedCopy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) - { - Copy (sourceArray, sourceIndex, destinationArray, destinationIndex, length, true); - } - - public static void Copy (Array sourceArray, Array destinationArray, int length) - { - if (sourceArray == null) - throw new ArgumentNullException ("sourceArray"); - - if (destinationArray == null) - throw new ArgumentNullException ("destinationArray"); - - Copy (sourceArray, sourceArray.GetLowerBound (0), destinationArray, - destinationArray.GetLowerBound (0), length); - } - - public static void Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) - { - Copy (sourceArray, sourceIndex, destinationArray, destinationIndex, length, false); - } - - private static void Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable) - { - if (sourceArray == null) - throw new ArgumentNullException (nameof (sourceArray)); - - if (destinationArray == null) - throw new ArgumentNullException (nameof (destinationArray)); - - if (length < 0) - throw new ArgumentOutOfRangeException (nameof (length), "Value has to be >= 0."); - - if (sourceArray.Rank != destinationArray.Rank) - throw new RankException(SR.Rank_MultiDimNotSupported); - - if (sourceIndex < 0) - throw new ArgumentOutOfRangeException (nameof (sourceIndex), "Value has to be >= 0."); - - if (destinationIndex < 0) - throw new ArgumentOutOfRangeException (nameof (destinationIndex), "Value has to be >= 0."); - - if (FastCopy (sourceArray, sourceIndex, destinationArray, destinationIndex, length)) - return; - - int source_pos = sourceIndex - sourceArray.GetLowerBound (0); - int dest_pos = destinationIndex - destinationArray.GetLowerBound (0); - - if (source_pos < 0) - throw new ArgumentOutOfRangeException (nameof (sourceIndex), "Index was less than the array's lower bound in the first dimension."); - - if (dest_pos < 0) - throw new ArgumentOutOfRangeException (nameof (destinationIndex), "Index was less than the array's lower bound in the first dimension."); - - // re-ordered to avoid possible integer overflow - if (source_pos > sourceArray.Length - length) - throw new ArgumentException (SR.Arg_LongerThanSrcArray, nameof (sourceArray)); - - if (dest_pos > destinationArray.Length - length) { - throw new ArgumentException ("Destination array was not long enough. Check destIndex and length, and the array's lower bounds", nameof (destinationArray)); - } - - Type src_type = sourceArray.GetType ().GetElementType ()!; - Type dst_type = destinationArray.GetType ().GetElementType ()!; - var dst_type_vt = dst_type.IsValueType && Nullable.GetUnderlyingType (dst_type) == null; - - bool src_is_enum = src_type.IsEnum; - bool dst_is_enum = dst_type.IsEnum; - - if (src_is_enum) - src_type = Enum.GetUnderlyingType (src_type); - if (dst_is_enum) - dst_type = Enum.GetUnderlyingType (dst_type); - - if (reliable) { - if (!dst_type.Equals (src_type) && - !(dst_type.IsPrimitive && src_type.IsPrimitive && CanChangePrimitive(ref dst_type, ref src_type, true))) { - throw new ArrayTypeMismatchException (SR.ArrayTypeMismatch_CantAssignType); - } - } else { - if (!CanAssignArrayElement (src_type, dst_type)) { - throw new ArrayTypeMismatchException (SR.ArrayTypeMismatch_CantAssignType); - } - } - - if (!Object.ReferenceEquals (sourceArray, destinationArray) || source_pos > dest_pos) { - for (int i = 0; i < length; i++) { - Object srcval = sourceArray.GetValueImpl (source_pos + i); - - if (!src_type.IsValueType && dst_is_enum) - throw new InvalidCastException (SR.InvalidCast_DownCastArrayElement); - - if (dst_type_vt && (srcval == null || (src_type == typeof (object) && srcval.GetType () != dst_type))) - throw new InvalidCastException (); - - try { - destinationArray.SetValueRelaxedImpl (srcval, dest_pos + i); - } catch (ArgumentException) { - throw CreateArrayTypeMismatchException (); - } - } - } else { - for (int i = length - 1; i >= 0; i--) { - Object srcval = sourceArray.GetValueImpl (source_pos + i); - - try { - destinationArray.SetValueRelaxedImpl (srcval, dest_pos + i); - } catch (ArgumentException) { - throw CreateArrayTypeMismatchException (); - } - } - } - } - - static ArrayTypeMismatchException CreateArrayTypeMismatchException () - { - return new ArrayTypeMismatchException (); - } - - static bool CanAssignArrayElement (Type source, Type target) - { - if (!target.IsValueType && !target.IsPointer) { - if (!source.IsValueType && !source.IsPointer) { - // Reference to reference copy - return - source.IsInterface || target.IsInterface || - source.IsAssignableFrom (target) || target.IsAssignableFrom (source); - } else { - // Value to reference copy - if (source.IsPointer) - return false; - return target.IsAssignableFrom (source); - } - } else { - if (source.IsEquivalentTo (target)) { - return true; - } else if (source.IsPointer && target.IsPointer) { - return true; - } else if (source.IsPrimitive && target.IsPrimitive) { - - // Allow primitive type widening - return CanChangePrimitive (ref source, ref target, false); - } else if (!source.IsValueType && !source.IsPointer) { - // Source is base class or interface of destination type - if (target.IsPointer) - return false; - return source.IsAssignableFrom (target); - } - } - - return false; - } - - public static unsafe Array CreateInstance (Type elementType, int length) - { - if (elementType is null) - ThrowHelper.ThrowArgumentNullException (ExceptionArgument.elementType); - if (length < 0) - ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum (); - - RuntimeType? runtimeType = elementType.UnderlyingSystemType as RuntimeType; - if (runtimeType == null) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); - - Array array = null; - InternalCreate (ref array, runtimeType._impl.Value, 1, &length, null); - GC.KeepAlive (runtimeType); - return array; - } - - public static unsafe Array CreateInstance (Type elementType, int length1, int length2) - { - if (elementType is null) - ThrowHelper.ThrowArgumentNullException (ExceptionArgument.elementType); - if (length1 < 0) - ThrowHelper.ThrowArgumentOutOfRangeException (ExceptionArgument.length1, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - if (length2 < 0) - ThrowHelper.ThrowArgumentOutOfRangeException (ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - - RuntimeType? runtimeType = elementType.UnderlyingSystemType as RuntimeType; - if (runtimeType == null) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); - - int* lengths = stackalloc int [] { length1, length2 }; - Array array = null; - InternalCreate (ref array, runtimeType._impl.Value, 2, lengths, null); - GC.KeepAlive (runtimeType); - return array; - } - - public static unsafe Array CreateInstance (Type elementType, int length1, int length2, int length3) - { - if (elementType is null) - ThrowHelper.ThrowArgumentNullException (ExceptionArgument.elementType); - if (length1 < 0) - ThrowHelper.ThrowArgumentOutOfRangeException (ExceptionArgument.length1, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - if (length2 < 0) - ThrowHelper.ThrowArgumentOutOfRangeException (ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - if (length3 < 0) - ThrowHelper.ThrowArgumentOutOfRangeException (ExceptionArgument.length3, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - - RuntimeType? runtimeType = elementType.UnderlyingSystemType as RuntimeType; - if (runtimeType == null) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); - - int* lengths = stackalloc int [] { length1, length2, length3 }; - Array array = null; - InternalCreate (ref array, runtimeType._impl.Value, 3, lengths, null); - GC.KeepAlive (runtimeType); - return array; - } - - public static unsafe Array CreateInstance (Type elementType, params int[] lengths) - { - if (elementType is null) - ThrowHelper.ThrowArgumentNullException (ExceptionArgument.elementType); - if (lengths == null) - ThrowHelper.ThrowArgumentNullException (ExceptionArgument.lengths); - if (lengths.Length == 0) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_NeedAtLeast1Rank); - - RuntimeType? runtimeType = elementType.UnderlyingSystemType as RuntimeType; - if (runtimeType == null) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); - - for (int i = 0; i < lengths.Length; i++) - if (lengths [i] < 0) - ThrowHelper.ThrowArgumentOutOfRangeException (ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - - Array array = null; - fixed (int* pLengths = &lengths [0]) - InternalCreate (ref array, runtimeType._impl.Value, lengths.Length, pLengths, null); - GC.KeepAlive (runtimeType); - return array; - } - - public static unsafe Array CreateInstance (Type elementType, int[] lengths, int[] lowerBounds) - { - if (elementType == null) - ThrowHelper.ThrowArgumentNullException (ExceptionArgument.elementType); - if (lengths == null) - ThrowHelper.ThrowArgumentNullException (ExceptionArgument.lengths); - if (lowerBounds == null) - ThrowHelper.ThrowArgumentNullException (ExceptionArgument.lowerBounds); - if (lengths.Length != lowerBounds!.Length) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_RanksAndBounds); - if (lengths.Length == 0) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_NeedAtLeast1Rank); - - for (int i = 0; i < lengths.Length; i++) - if (lengths [i] < 0) - ThrowHelper.ThrowArgumentOutOfRangeException (ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - - RuntimeType? runtimeType = elementType.UnderlyingSystemType as RuntimeType; - if (runtimeType == null) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); - - Array array = null; - fixed (int* pLengths = &lengths [0]) - fixed (int* pLowerBounds = &lowerBounds [0]) - InternalCreate (ref array, runtimeType._impl.Value, lengths.Length, pLengths, pLowerBounds); - GC.KeepAlive (runtimeType); - return array; - } - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern unsafe void InternalCreate (ref Array result, IntPtr elementType, int rank, int* lengths, int* lowerBounds); - - public object GetValue (int index) - { - if (Rank != 1) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_Need1DArray); - - var lb = GetLowerBound (0); - if (index < lb || index > GetUpperBound (0)) - throw new IndexOutOfRangeException ("Index has to be between upper and lower bound of the array."); - - if (GetType ().GetElementType ()!.IsPointer) - throw new NotSupportedException (SR.NotSupported_Type); - - return GetValueImpl (index - lb); - } - - public object GetValue (int index1, int index2) - { - if (Rank != 2) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_Need2DArray); - - int[] ind = {index1, index2}; - return GetValue (ind); - } - - public object GetValue (int index1, int index2, int index3) - { - if (Rank != 3) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_Need3DArray); - - int[] ind = {index1, index2, index3}; - return GetValue (ind); - } - - public void Initialize () - { - } - - static int IndexOfImpl<T>(T[] array, T value, int startIndex, int count) - { - return EqualityComparer<T>.Default.IndexOf (array, value, startIndex, count); - } - - static int LastIndexOfImpl<T>(T[] array, T value, int startIndex, int count) - { - return EqualityComparer<T>.Default.LastIndexOf (array, value, startIndex, count); - } - - public void SetValue (object? value, int index) - { - if (Rank != 1) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_Need1DArray); - - var lb = GetLowerBound (0); - if (index < lb || index > GetUpperBound (0)) - throw new IndexOutOfRangeException ("Index has to be >= lower bound and <= upper bound of the array."); - - if (GetType ().GetElementType ()!.IsPointer) - throw new NotSupportedException (SR.NotSupported_Type); - - SetValueImpl (value, index - lb); - } - - public void SetValue (object? value, int index1, int index2) - { - if (Rank != 2) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_Need2DArray); - - int[] ind = {index1, index2}; - SetValue (value, ind); - } - - public void SetValue (object? value, int index1, int index2, int index3) - { - if (Rank != 3) - ThrowHelper.ThrowArgumentException (ExceptionResource.Arg_Need3DArray); - - int[] ind = {index1, index2, index3}; - SetValue (value, ind); - } - - static bool TrySZBinarySearch (Array sourceArray, int sourceIndex, int count, object? value, out int retVal) - { - retVal = default; - return false; - } - - static bool TrySZIndexOf (Array sourceArray, int sourceIndex, int count, object? value, out int retVal) - { - retVal = default; - return false; - } - - static bool TrySZLastIndexOf (Array sourceArray, int sourceIndex, int count, object? value, out int retVal) - { - retVal = default; - return false; - } - - static bool TrySZReverse (Array array, int index, int count) => false; - - public int GetUpperBound (int dimension) - { - return GetLowerBound (dimension) + GetLength (dimension) - 1; - } - - [Intrinsic] - [MethodImpl (MethodImplOptions.AggressiveInlining)] - internal ref byte GetRawSzArrayData () - { - // TODO: Missing intrinsic in interpreter - return ref Unsafe.As<RawData>(this).Data; - } - - [Intrinsic] - [MethodImpl (MethodImplOptions.AggressiveInlining)] - internal ref byte GetRawArrayData () - { - // TODO: Missing intrinsic in interpreter - return ref Unsafe.As<RawData>(this).Data; - } - - [Intrinsic] - internal int GetElementSize () => GetElementSize (); - - [Intrinsic] - public bool IsPrimitive () => IsPrimitive (); - - [MethodImpl (MethodImplOptions.InternalCall)] - internal extern CorElementType GetCorElementTypeOfElementType(); - - [MethodImpl (MethodImplOptions.InternalCall)] - extern bool IsValueOfElementType(object value); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static bool CanChangePrimitive (ref Type srcType, ref Type dstType, bool reliable); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static bool FastCopy (Array source, int source_idx, Array dest, int dest_idx, int length); - - [Intrinsic] // when dimension is `0` constant - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern int GetLength (int dimension); - - [Intrinsic] // when dimension is `0` constant - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern int GetLowerBound (int dimension); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern object GetValue (params int[] indices); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern void SetValue (object? value, params int[] indices); - - // CAUTION! No bounds checking! - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void GetGenericValue_icall<T> (ref Array self, int pos, out T value); - - // CAUTION! No bounds checking! - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern object GetValueImpl (int pos); - - // CAUTION! No bounds checking! - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void SetGenericValue_icall<T> (ref Array self, int pos, ref T value); - - [Intrinsic] - void GetGenericValueImpl<T> (int pos, out T value) - { - var self = this; - GetGenericValue_icall (ref self, pos, out value); - } - - [Intrinsic] - void SetGenericValueImpl<T> (int pos, ref T value) - { - var self = this; - SetGenericValue_icall (ref self, pos, ref value); - } - - // CAUTION! No bounds checking! - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern void SetValueImpl (object? value, int pos); - - // CAUTION! No bounds checking! - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern void SetValueRelaxedImpl (object? value, int pos); - - /* - * These methods are used to implement the implicit generic interfaces - * implemented by arrays in NET 2.0. - * Only make those methods generic which really need it, to avoid - * creating useless instantiations. - */ - internal int InternalArray__ICollection_get_Count () - { - return Length; - } - - internal bool InternalArray__ICollection_get_IsReadOnly () - { - return true; - } - - internal IEnumerator<T> InternalArray__IEnumerable_GetEnumerator<T> () - { - return Length == 0 ? SZGenericArrayEnumerator<T>.Empty : new SZGenericArrayEnumerator<T> (Unsafe.As<T[]> (this)); - } - - internal void InternalArray__ICollection_Clear () - { - ThrowHelper.ThrowNotSupportedException (ExceptionResource.NotSupported_ReadOnlyCollection); - } - - internal void InternalArray__ICollection_Add<T> (T item) - { - ThrowHelper.ThrowNotSupportedException (ExceptionResource.NotSupported_FixedSizeCollection); - } - - internal bool InternalArray__ICollection_Remove<T> (T item) - { - ThrowHelper.ThrowNotSupportedException (ExceptionResource.NotSupported_FixedSizeCollection); - return default; - } - - internal bool InternalArray__ICollection_Contains<T> (T item) - { - return IndexOf ((T[])this, item, 0, Length) >= 0; - } - - internal void InternalArray__ICollection_CopyTo<T> (T[] array, int arrayIndex) - { - Copy (this, GetLowerBound (0), array, arrayIndex, Length); - } - - internal T InternalArray__IReadOnlyList_get_Item<T> (int index) - { - if ((uint)index >= (uint)Length) - ThrowHelper.ThrowArgumentOutOfRange_IndexException (); - - T value; - // Do not change this to call GetGenericValue_icall directly, due to special casing in the runtime. - GetGenericValueImpl (index, out value); - return value; - } - - internal int InternalArray__IReadOnlyCollection_get_Count () - { - return Length; - } - - internal void InternalArray__Insert<T> (int index, T item) - { - ThrowHelper.ThrowNotSupportedException (ExceptionResource.NotSupported_FixedSizeCollection); - } - - internal void InternalArray__RemoveAt (int index) - { - ThrowHelper.ThrowNotSupportedException (ExceptionResource.NotSupported_FixedSizeCollection); - } - - internal int InternalArray__IndexOf<T> (T item) - { - return IndexOf ((T[])this, item, 0, Length); - } - - internal T InternalArray__get_Item<T> (int index) - { - if ((uint)index >= (uint)Length) - ThrowHelper.ThrowArgumentOutOfRange_IndexException (); - - T value; - // Do not change this to call GetGenericValue_icall directly, due to special casing in the runtime. - GetGenericValueImpl (index, out value); - return value; - } - - internal void InternalArray__set_Item<T> (int index, T item) - { - if ((uint)index >= (uint)Length) - ThrowHelper.ThrowArgumentOutOfRange_IndexException(); - - if (this is object[] oarray) { - oarray! [index] = (object)item; - return; - } - - // Do not change this to call SetGenericValue_icall directly, due to special casing in the runtime. - SetGenericValueImpl (index, ref item); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Attribute.Mono.cs b/netcore/System.Private.CoreLib/src/System/Attribute.Mono.cs deleted file mode 100644 index 3a67f4d1b92..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Attribute.Mono.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#nullable disable -using System.Reflection; - -namespace System -{ - partial class Attribute - { - static Attribute? GetAttr (ICustomAttributeProvider element, Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException (nameof (attributeType)); - if (!attributeType.IsSubclassOf (typeof (Attribute)) && attributeType != typeof (Attribute) && attributeType != typeof (CustomAttribute)) - throw new ArgumentException (SR.Argument_MustHaveAttributeBaseClass + " " + attributeType.FullName); - - var attrs = CustomAttribute.GetCustomAttributes (element, attributeType, inherit); - if (attrs == null || attrs.Length == 0) - return null; - if (attrs.Length != 1) - throw new AmbiguousMatchException (); - return (Attribute)(attrs [0]); - } - - public static Attribute GetCustomAttribute (Assembly element, Type attributeType) => GetAttr (element, attributeType, true); - public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit) => GetAttr (element, attributeType, inherit); - public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType) => GetAttr (element, attributeType, true); - public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit) => GetAttr (element, attributeType, inherit); - public static Attribute GetCustomAttribute(Module element, Type attributeType) => GetAttr (element, attributeType, true); - public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit) => GetAttr (element, attributeType, inherit); - public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType) => GetAttr (element, attributeType, true); - public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit) => GetAttr (element, attributeType, inherit); - - public static Attribute[] GetCustomAttributes (Assembly element) => (Attribute[])CustomAttribute.GetCustomAttributes (element, true); - public static Attribute[] GetCustomAttributes (Assembly element, bool inherit) => (Attribute[])CustomAttribute.GetCustomAttributes (element, inherit); - public static Attribute[] GetCustomAttributes (Assembly element, Type attributeType) => (Attribute[])CustomAttribute.GetCustomAttributes ((ICustomAttributeProvider)element, attributeType, true); - public static Attribute[] GetCustomAttributes (Assembly element, Type attributeType, bool inherit) => (Attribute[])CustomAttribute.GetCustomAttributes ((ICustomAttributeProvider)element, attributeType, inherit); - public static Attribute[] GetCustomAttributes (MemberInfo element) => (Attribute[])CustomAttribute.GetCustomAttributes (element, true); - public static Attribute[] GetCustomAttributes (MemberInfo element, bool inherit) => (Attribute[])CustomAttribute.GetCustomAttributes (element, inherit); - public static Attribute[] GetCustomAttributes (MemberInfo element, Type attributeType) => (Attribute[])CustomAttribute.GetCustomAttributes ((ICustomAttributeProvider)element, attributeType, true); - public static Attribute[] GetCustomAttributes (MemberInfo element, Type attributeType, bool inherit) => (Attribute[])CustomAttribute.GetCustomAttributes ((ICustomAttributeProvider)element, attributeType, inherit); - public static Attribute[] GetCustomAttributes (Module element) => (Attribute[])CustomAttribute.GetCustomAttributes (element, true); - public static Attribute[] GetCustomAttributes (Module element, bool inherit) => (Attribute[])CustomAttribute.GetCustomAttributes (element, inherit); - public static Attribute[] GetCustomAttributes (Module element, Type attributeType) => (Attribute[])CustomAttribute.GetCustomAttributes ((ICustomAttributeProvider)element, attributeType, true); - public static Attribute[] GetCustomAttributes (Module element, Type attributeType, bool inherit) => (Attribute[])CustomAttribute.GetCustomAttributes ((ICustomAttributeProvider)element, attributeType, inherit); - public static Attribute[] GetCustomAttributes (ParameterInfo element) => (Attribute[])CustomAttribute.GetCustomAttributes (element, true); - public static Attribute[] GetCustomAttributes (ParameterInfo element, bool inherit) => (Attribute[])CustomAttribute.GetCustomAttributes (element, inherit); - public static Attribute[] GetCustomAttributes (ParameterInfo element, Type attributeType) => (Attribute[])CustomAttribute.GetCustomAttributes ((ICustomAttributeProvider)element, attributeType, true); - public static Attribute[] GetCustomAttributes (ParameterInfo element, Type attributeType, bool inherit) => (Attribute[])CustomAttribute.GetCustomAttributes ((ICustomAttributeProvider)element, attributeType, inherit); - - public static bool IsDefined (Assembly element, Type attributeType) => CustomAttribute.IsDefined ((ICustomAttributeProvider)element, attributeType, true); - public static bool IsDefined (Assembly element, Type attributeType, bool inherit) => CustomAttribute.IsDefined ((ICustomAttributeProvider)element, attributeType, inherit); - public static bool IsDefined (MemberInfo element, Type attributeType) => CustomAttribute.IsDefined ((ICustomAttributeProvider)element, attributeType, true); - public static bool IsDefined (MemberInfo element, Type attributeType, bool inherit) => CustomAttribute.IsDefined ((ICustomAttributeProvider)element, attributeType, inherit); - public static bool IsDefined (Module element, Type attributeType) => CustomAttribute.IsDefined ((ICustomAttributeProvider)element, attributeType, true); - public static bool IsDefined (Module element, Type attributeType, bool inherit) => CustomAttribute.IsDefined ((ICustomAttributeProvider)element, attributeType, inherit); - public static bool IsDefined (ParameterInfo element, Type attributeType) => CustomAttribute.IsDefined ((ICustomAttributeProvider)element, attributeType, true); - public static bool IsDefined (ParameterInfo element, Type attributeType, bool inherit) => CustomAttribute.IsDefined ((ICustomAttributeProvider)element, attributeType, inherit); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Buffer.Mono.cs b/netcore/System.Private.CoreLib/src/System/Buffer.Mono.cs deleted file mode 100644 index c22504abb11..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Buffer.Mono.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -#if BIT64 -using nuint = System.UInt64; -#else -using nuint = System.UInt32; -#endif - -namespace System -{ - partial class Buffer - { - static bool IsPrimitiveTypeArray (Array array) => array.IsPrimitive (); - - internal static unsafe void Memcpy (byte* dest, byte* src, int len) => Memmove (dest, src, (nuint) len); - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern unsafe void __Memmove (byte* dest, byte* src, nuint len); - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern void BulkMoveWithWriteBarrier (ref byte dmem, ref byte smem, nuint size); - - [MethodImpl(MethodImplOptions.NoInlining)] - internal static unsafe void _ZeroMemory(ref byte b, nuint byteLength) - { - fixed (byte* bytePointer = &b) { - __ZeroMemory (bytePointer, byteLength); - } - } - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern unsafe void __ZeroMemory (void* p, nuint byteLength); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.Mono.cs b/netcore/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.Mono.cs deleted file mode 100644 index 238b880dcc5..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.Mono.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Collections.Generic -{ - partial class ArraySortHelper<T> - { - public static ArraySortHelper<T> Default { get; } = new ArraySortHelper<T>(); - } - - partial class ArraySortHelper<TKey, TValue> - { - public static ArraySortHelper<TKey, TValue> Default { get; } = new ArraySortHelper<TKey, TValue>(); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Collections/Generic/Comparer.Mono.cs b/netcore/System.Private.CoreLib/src/System/Collections/Generic/Comparer.Mono.cs deleted file mode 100644 index 61d15e94618..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Collections/Generic/Comparer.Mono.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System.Collections.Generic -{ - partial class Comparer<T> - { - static volatile Comparer<T> defaultComparer; - - public static Comparer<T> Default { - get { - Comparer<T> comparer = defaultComparer; - if (comparer == null) { - comparer = CreateComparer(); - defaultComparer = comparer; - } - return comparer; - } - } - - static Comparer<T> CreateComparer() { - RuntimeType t = (RuntimeType)typeof(T); - - if (typeof(IComparable<T>).IsAssignableFrom(t)) - return (Comparer<T>)RuntimeType.CreateInstanceForAnotherGenericParameter (typeof(GenericComparer<>), t); - - // If T is a Nullable<U> where U implements IComparable<U> return a NullableComparer<U> - if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) { - RuntimeType u = (RuntimeType)t.GetGenericArguments()[0]; - if (typeof(IComparable<>).MakeGenericType (u).IsAssignableFrom (u)) - return (Comparer<T>)RuntimeType.CreateInstanceForAnotherGenericParameter (typeof(NullableComparer<>), u); - } - - if (t.IsEnum) - return (Comparer<T>)RuntimeType.CreateInstanceForAnotherGenericParameter (typeof(EnumComparer<>), t); - - // Otherwise return an ObjectComparer<T> - return new ObjectComparer<T> (); - } - } - - partial class EnumComparer<T> - { - [MethodImpl (MethodImplOptions.AggressiveInlining)] - public override int Compare (T x, T y) => JitHelpers.EnumCompareTo (x, y); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.Mono.cs b/netcore/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.Mono.cs deleted file mode 100644 index 614a9888fe8..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.Mono.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System.Collections.Generic -{ - partial class EqualityComparer<T> - { - static volatile EqualityComparer<T> defaultComparer; - - public static EqualityComparer<T> Default { - [MethodImplAttribute (MethodImplOptions.AggressiveInlining)] - get { - EqualityComparer<T> comparer = defaultComparer; - if (comparer == null) { - comparer = CreateComparer(); - defaultComparer = comparer; - } - return comparer; - } - } - - static EqualityComparer<T> CreateComparer () - { - RuntimeType t = (RuntimeType)typeof(T); - - ///////////////////////////////////////////////// - // KEEP THIS IN SYNC WITH THE DEVIRT CODE - // IN METHOD-TO-IR.C - ///////////////////////////////////////////////// - - if (t == typeof(byte)) { - return (EqualityComparer<T>)(object)(new ByteEqualityComparer()); - } - - if (typeof(IEquatable<T>).IsAssignableFrom(t)) { - return (EqualityComparer<T>)RuntimeType.CreateInstanceForAnotherGenericParameter (typeof(GenericEqualityComparer<>), t); - } - - if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) { - RuntimeType u = (RuntimeType)t.GetGenericArguments()[0]; - if (typeof(IEquatable<>).MakeGenericType(u).IsAssignableFrom(u)) { - return (EqualityComparer<T>)RuntimeType.CreateInstanceForAnotherGenericParameter (typeof(NullableEqualityComparer<>), u); - } - } - - if (t.IsEnum) { - return (EqualityComparer<T>)RuntimeType.CreateInstanceForAnotherGenericParameter (typeof(EnumEqualityComparer<>), t); - } - - return new ObjectEqualityComparer<T>(); - } - - // MONOTODO: Add specialized versions - internal virtual int IndexOf (T[] array, T value, int startIndex, int count) - { - int endIndex = startIndex + count; - for (int i = startIndex; i < endIndex; i++) { - if (Equals (array[i], value)) - return i; - } - return -1; - } - - internal virtual int LastIndexOf (T[] array, T value, int startIndex, int count) - { - int endIndex = startIndex - count + 1; - for (int i = startIndex; i >= endIndex; i--) { - if (Equals (array[i], value)) - return i; - } - return -1; - } - - } - - partial class EnumEqualityComparer<T> - { - [MethodImpl (MethodImplOptions.AggressiveInlining)] - public override bool Equals (T x, T y) => JitHelpers.EnumEquals (x, y); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Delegate.Mono.cs b/netcore/System.Private.CoreLib/src/System/Delegate.Mono.cs deleted file mode 100644 index 09fec9904ae..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Delegate.Mono.cs +++ /dev/null @@ -1,525 +0,0 @@ -// -// Authors: -// Miguel de Icaza (miguel@ximian.com) -// Daniel Stodden (stodden@in.tum.de) -// Dietmar Maurer (dietmar@ximian.com) -// Marek Safar (marek.safar@gmail.com) -// -// (C) Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// Copyright 2014 Xamarin, Inc (http://www.xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; - -namespace System -{ - /* Contains the rarely used fields of Delegate */ - sealed class DelegateData - { - public Type? target_type; - public string? method_name; - public bool curried_first_arg; - } - - [StructLayout (LayoutKind.Sequential)] - partial class Delegate - { - #region Sync with object-internals.h - IntPtr method_ptr; - IntPtr invoke_impl; - object? _target; - IntPtr method; - IntPtr delegate_trampoline; - IntPtr extra_arg; - IntPtr method_code; - IntPtr interp_method; - IntPtr interp_invoke_impl; - MethodInfo? method_info; - - // Keep a ref of the MethodInfo passed to CreateDelegate. - // Used to keep DynamicMethods alive. - MethodInfo? original_method_info; - - DelegateData data; - - bool method_is_virtual; - #endregion - - protected Delegate (object target, string method) - { - if (target is null) - throw new ArgumentNullException (nameof (target)); - - if (method is null) - throw new ArgumentNullException (nameof (method)); - - this._target = target; - this.data = new DelegateData () { - method_name = method - }; - } - - protected Delegate (Type target, string method) - { - if (target is null) - throw new ArgumentNullException (nameof (target)); - - if (target.ContainsGenericParameters) - throw new ArgumentException (SR.Arg_UnboundGenParam, nameof (target)); - - if (method is null) - throw new ArgumentNullException (nameof (method)); - - if (!target.IsRuntimeImplemented ()) - throw new ArgumentException (SR.Argument_MustBeRuntimeType, nameof (target)); - - this.data = new DelegateData () { - method_name = method, - target_type = target - }; - } - - public object? Target => GetTarget (); - - internal virtual object? GetTarget () => _target; - - public static Delegate CreateDelegate (Type type, object? firstArgument, MethodInfo method, bool throwOnBindFailure) - { - return CreateDelegate (type, firstArgument, method, throwOnBindFailure, true)!; - } - - public static Delegate? CreateDelegate (Type type, MethodInfo method, bool throwOnBindFailure) - { - return CreateDelegate (type, null, method, throwOnBindFailure, false); - } - - static Delegate? CreateDelegate (Type type, object? firstArgument, MethodInfo method, bool throwOnBindFailure, bool allowClosed) - { - if (type is null) - throw new ArgumentNullException (nameof (type)); - if (method is null) - throw new ArgumentNullException (nameof (method)); - - if (!(type is RuntimeType rtType)) - throw new ArgumentException (SR.Argument_MustBeRuntimeType, nameof (type)); - if (!(method is RuntimeMethodInfo || method is System.Reflection.Emit.DynamicMethod)) - throw new ArgumentException (SR.Argument_MustBeRuntimeMethodInfo, nameof (method)); - - if (!rtType.IsDelegate ()) - throw new ArgumentException (SR.Arg_MustBeDelegate, nameof (type)); - - if (!IsMatchingCandidate (type, firstArgument, method, allowClosed, out DelegateData? delegate_data)) { - if (throwOnBindFailure) - throw new ArgumentException (SR.Arg_DlgtTargMeth); - - return null; - } - - Delegate? d = CreateDelegate_internal (type, firstArgument, method, throwOnBindFailure); - if (d != null) { - d.original_method_info = method; - d.data = delegate_data!; - } - - return d; - } - - public static Delegate? CreateDelegate (Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure) - { - if (type is null) - throw new ArgumentNullException (nameof (type)); - if (target is null) - throw new ArgumentNullException (nameof (target)); - if (method is null) - throw new ArgumentNullException (nameof (method)); - - if (!(type is RuntimeType rtType)) - throw new ArgumentException (SR.Argument_MustBeRuntimeType, nameof (type)); - if (!rtType.IsDelegate ()) - throw new ArgumentException (SR.Arg_MustBeDelegate, nameof (type)); - - MethodInfo? info = GetCandidateMethod (type, target.GetType (), method, BindingFlags.Instance, ignoreCase); - if (info is null) { - if (throwOnBindFailure) - throw new ArgumentException (SR.Arg_DlgtTargMeth); - - return null; - } - - return CreateDelegate_internal (type, null, info, throwOnBindFailure); - } - - public static Delegate? CreateDelegate (Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure) - { - if (type is null) - throw new ArgumentNullException (nameof (type)); - if (target is null) - throw new ArgumentNullException (nameof (target)); - if (target.ContainsGenericParameters) - throw new ArgumentException (SR.Arg_UnboundGenParam, nameof (target)); - if (method is null) - throw new ArgumentNullException (nameof (method)); - - if (!(type is RuntimeType rtType)) - throw new ArgumentException (SR.Argument_MustBeRuntimeType, nameof (type)); - - if (!target.IsRuntimeImplemented ()) - throw new ArgumentException (SR.Argument_MustBeRuntimeType, nameof (target)); - if (!rtType.IsDelegate ()) - throw new ArgumentException (SR.Arg_MustBeDelegate, nameof (type)); - - MethodInfo? info = GetCandidateMethod (type, target, method, BindingFlags.Static, ignoreCase); - if (info is null) { - if (throwOnBindFailure) - throw new ArgumentException (SR.Arg_DlgtTargMeth); - - return null; - } - - return CreateDelegate_internal (type, null, info, throwOnBindFailure); - } - - static MethodInfo? GetCandidateMethod (Type type, Type target, string method, BindingFlags bflags, bool ignoreCase) - { - MethodInfo? invoke = type.GetMethod ("Invoke"); - if (invoke is null) - return null; - - ParameterInfo [] delargs = invoke.GetParametersInternal (); - Type[] delargtypes = new Type [delargs.Length]; - - for (int i = 0; i < delargs.Length; i++) - delargtypes [i] = delargs [i].ParameterType; - - /* - * since we need to walk the inheritance chain anyway to - * find private methods, adjust the bindingflags to ignore - * inherited methods - */ - BindingFlags flags = BindingFlags.ExactBinding | - BindingFlags.Public | BindingFlags.NonPublic | - BindingFlags.DeclaredOnly | bflags; - - if (ignoreCase) - flags |= BindingFlags.IgnoreCase; - - for (Type? targetType = target; targetType != null; targetType = targetType.BaseType) { - MethodInfo? mi = targetType.GetMethod (method, flags, null, delargtypes, Array.Empty<ParameterModifier>()); - - if (mi != null && IsReturnTypeMatch (invoke.ReturnType!, mi.ReturnType!)) { - return mi; - } - } - - return null; - } - - static bool IsMatchingCandidate (Type type, object? target, MethodInfo method, bool allowClosed, out DelegateData? delegateData) - { - MethodInfo? invoke = type.GetMethod ("Invoke"); - - if (invoke == null || !IsReturnTypeMatch (invoke.ReturnType!, method.ReturnType!)) { - delegateData = null; - return false; - } - - ParameterInfo[] delargs = invoke.GetParametersInternal (); - ParameterInfo[] args = method.GetParametersInternal (); - - bool argLengthMatch; - - if (target != null) { - // delegate closed over target - if (!method.IsStatic) - // target is passed as this - argLengthMatch = (args.Length == delargs.Length); - else - // target is passed as the first argument to the static method - argLengthMatch = (args.Length == delargs.Length + 1); - } else { - if (!method.IsStatic) { - // - // Net 2.0 feature. The first argument of the delegate is passed - // as the 'this' argument to the method. - // - argLengthMatch = (args.Length + 1 == delargs.Length); - - if (!argLengthMatch) - // closed over a null reference - argLengthMatch = (args.Length == delargs.Length); - } else { - argLengthMatch = (args.Length == delargs.Length); - - if (!argLengthMatch) - // closed over a null reference - argLengthMatch = args.Length == delargs.Length + 1; - } - } - - if (!argLengthMatch) { - delegateData = null; - return false; - } - - bool argsMatch; - delegateData = new DelegateData (); - - if (target != null) { - if (!method.IsStatic) { - argsMatch = IsArgumentTypeMatchWithThis (target.GetType (), method.DeclaringType!, true); - for (int i = 0; i < args.Length; i++) - argsMatch &= IsArgumentTypeMatch (delargs [i].ParameterType, args [i].ParameterType); - } else { - argsMatch = IsArgumentTypeMatch (target.GetType (), args [0].ParameterType); - for (int i = 1; i < args.Length; i++) - argsMatch &= IsArgumentTypeMatch (delargs [i - 1].ParameterType, args [i].ParameterType); - - delegateData.curried_first_arg = true; - } - } else { - if (!method.IsStatic) { - if (args.Length + 1 == delargs.Length) { - // The first argument should match this - argsMatch = IsArgumentTypeMatchWithThis (delargs [0].ParameterType, method.DeclaringType!, false); - for (int i = 0; i < args.Length; i++) - argsMatch &= IsArgumentTypeMatch (delargs [i + 1].ParameterType, args [i].ParameterType); - } else { - // closed over a null reference - argsMatch = allowClosed; - for (int i = 0; i < args.Length; i++) - argsMatch &= IsArgumentTypeMatch (delargs [i].ParameterType, args [i].ParameterType); - } - } else { - if (delargs.Length + 1 == args.Length) { - // closed over a null reference - argsMatch = !(args [0].ParameterType.IsValueType || args [0].ParameterType.IsByRef) && allowClosed; - for (int i = 0; i < delargs.Length; i++) - argsMatch &= IsArgumentTypeMatch (delargs [i].ParameterType, args [i + 1].ParameterType); - - delegateData.curried_first_arg = true; - } else { - argsMatch = true; - for (int i = 0; i < args.Length; i++) - argsMatch &= IsArgumentTypeMatch (delargs [i].ParameterType, args [i].ParameterType); - } - } - } - - return argsMatch; - } - - static bool IsReturnTypeMatch (Type delReturnType, Type returnType) - { - bool returnMatch = returnType == delReturnType; - - if (!returnMatch) { - // Delegate covariance - if (!returnType.IsValueType && delReturnType.IsAssignableFrom (returnType)) - returnMatch = true; - else - { - bool isDelArgEnum = delReturnType.IsEnum; - bool isArgEnum = returnType.IsEnum; - if (isArgEnum && isDelArgEnum) - returnMatch = Enum.GetUnderlyingType (delReturnType) == Enum.GetUnderlyingType (returnType); - else if (isDelArgEnum && Enum.GetUnderlyingType (delReturnType) == returnType) - returnMatch = true; - else if (isArgEnum && Enum.GetUnderlyingType (returnType) == delReturnType) - returnMatch = true; - } - } - - return returnMatch; - } - - static bool IsArgumentTypeMatch (Type delArgType, Type argType) - { - bool match = delArgType == argType; - - // Delegate contravariance - if (!match) { - if (!argType.IsValueType && argType.IsAssignableFrom (delArgType)) - match = true; - } - // enum basetypes - if (!match) { - if (delArgType.IsEnum && Enum.GetUnderlyingType (delArgType) == argType) - match = true; - else if (argType.IsEnum && Enum.GetUnderlyingType (argType) == delArgType) - match = true; - } - - return match; - } - - static bool IsArgumentTypeMatchWithThis (Type delArgType, Type argType, bool boxedThis) - { - bool match; - if (argType.IsValueType) - match = delArgType.IsByRef && delArgType.GetElementType () == argType || - (boxedThis && delArgType == argType); - else - match = delArgType == argType || argType.IsAssignableFrom (delArgType); - - return match; - } - - protected virtual object? DynamicInvokeImpl (object?[]? args) - { - if (Method is null) { -#nullable disable - // FIXME: This code cannot handle null argument values - Type[] mtypes = new Type [args.Length]; - for (int i = 0; i < args.Length; ++i) { - mtypes [i] = args [i].GetType (); - } - method_info = _target.GetType ().GetMethod (data.method_name, mtypes); -#nullable restore - } - - var target = _target; - - if (data is null) - data = CreateDelegateData (); - - // replace all Type.Missing with default values defined on parameters of the delegate if any - MethodInfo? invoke = GetType ().GetMethod ("Invoke"); - if (invoke != null && args != null) { - ParameterInfo[] delegateParameters = invoke.GetParameters (); - for (int i = 0; i < args.Length; i++) { - if (args [i] == Type.Missing) { - ParameterInfo dlgParam = delegateParameters [i]; - if (dlgParam.HasDefaultValue) { - args [i] = dlgParam.DefaultValue; - } - } - } - } - - if (Method.IsStatic) { - // - // The delegate is bound to _target - // - if (data.curried_first_arg) { - if (args is null) { - args = new object?[] { target }; - } else { - Array.Resize (ref args, args.Length + 1); - Array.Copy (args, 0, args, 1, args.Length - 1); - args [0] = target; - } - - target = null; - } - } else { - if (_target is null && args?.Length > 0) { - target = args [0]; - Array.Copy (args, 1, args, 0, args.Length - 1); - Array.Resize (ref args, args.Length - 1); - } - } - - return Method.Invoke (target, args); - } - - public override bool Equals (object? obj) - { - if (!(obj is Delegate d) || !InternalEqualTypes (this, obj)) - return false; - - // Do not compare method_ptr, since it can point to a trampoline - if (d._target == _target && d.Method == Method) { - if (d.data != null || data != null) { - /* Uncommon case */ - if (d.data != null && data != null) - return (d.data.target_type == data.target_type && d.data.method_name == data.method_name); - else { - if (d.data != null) - return d.data.target_type is null; - if (data != null) - return data.target_type is null; - return false; - } - } - return true; - } - - return false; - } - - public override int GetHashCode () - { - MethodInfo? m = Method; - - return (m != null ? m.GetHashCode () : GetType ().GetHashCode ()) ^ RuntimeHelpers.GetHashCode (_target); - } - - protected virtual MethodInfo GetMethodImpl () - { - if (method_info != null) - return method_info; - - if (method != IntPtr.Zero) { - if (!method_is_virtual) - method_info = (MethodInfo) RuntimeMethodInfo.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (method)); - else - method_info = GetVirtualMethod_internal (); - } - - return method_info; - } - - DelegateData CreateDelegateData () - { - DelegateData delegate_data = new DelegateData (); - if (method_info.IsStatic) { - if (_target != null) { - delegate_data.curried_first_arg = true; - } else { - MethodInfo? invoke = GetType ().GetMethod ("Invoke"); - if (invoke != null && invoke.GetParametersCount () + 1 == method_info.GetParametersCount ()) - delegate_data.curried_first_arg = true; - } - } - - return delegate_data; - } - - static bool InternalEqualTypes (object source, object value) - { - return source.GetType () == value.GetType (); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - private protected extern static MulticastDelegate AllocDelegateLike_internal (Delegate d); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern Delegate? CreateDelegate_internal (Type type, object? target, MethodInfo info, bool throwOnBindFailure); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern MethodInfo GetVirtualMethod_internal (); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs b/netcore/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs deleted file mode 100644 index 1692021801c..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System.Diagnostics -{ - public static class Debugger - { - public static readonly string DefaultCategory = ""; - - public static bool IsAttached => IsAttached_internal (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static bool IsAttached_internal (); - - [Intrinsic] - public static void Break () - { - // The JIT inserts a breakpoint on the caller. - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public static extern bool IsLogging(); - - public static bool Launch () - { - throw new NotImplementedException (); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern void Log_icall (int level, ref string category, ref string message); - - public static void Log (int level, string category, string message) - { - Log_icall (level, ref category, ref message); - } - - public static void NotifyOfCrossThreadDependency () - { - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Diagnostics/StackFrame.Mono.cs b/netcore/System.Private.CoreLib/src/System/Diagnostics/StackFrame.Mono.cs deleted file mode 100644 index 35bada2fb23..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Diagnostics/StackFrame.Mono.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Text; - -namespace System.Diagnostics -{ - partial class StackFrame - { - internal StackFrame (MonoStackFrame monoStackFrame, bool needFileInfo) - { - _method = monoStackFrame.methodBase; - _nativeOffset = monoStackFrame.nativeOffset; - _ilOffset = monoStackFrame.ilOffset; - - if (needFileInfo) { - _fileName = monoStackFrame.fileName; - _lineNumber = monoStackFrame.lineNumber; - _columnNumber = monoStackFrame.columnNumber; - } - - _isLastFrameFromForeignExceptionStackTrace = monoStackFrame.isLastFrameFromForeignException; - } - - [MethodImplAttribute (MethodImplOptions.NoInlining)] - void BuildStackFrame (int skipFrames, bool needFileInfo) - { - const int SystemDiagnosticsStackDepth = 3; - - if (skipFrames + SystemDiagnosticsStackDepth < 0 || !get_frame_info (skipFrames + SystemDiagnosticsStackDepth, needFileInfo, out var method, out var ilOffset, out var nativeOffset, out var fileName, out var line, out var column)) - return; - - _method = method; - _ilOffset = ilOffset; - _nativeOffset = nativeOffset; - - if (needFileInfo) { - _fileName = fileName; - _lineNumber = line; - _columnNumber = column; - } - } - - bool AppendStackFrameWithoutMethodBase (StringBuilder sb) => false; - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern bool get_frame_info (int skipFrames, bool needFileInfo, - out MethodBase method, out int ilOffset, out int nativeOffset, out string file, out int line, out int column); - - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Diagnostics/StackTrace.Mono.cs b/netcore/System.Private.CoreLib/src/System/Diagnostics/StackTrace.Mono.cs deleted file mode 100644 index 07d417a8c9f..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Diagnostics/StackTrace.Mono.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Diagnostics -{ - // Need our own stackframe class since the shared version has its own fields - [StructLayout (LayoutKind.Sequential)] - class MonoStackFrame - { - #region Keep in sync with object-internals.h - internal int ilOffset; - internal int nativeOffset; - // Unused - internal long methodAddress; - // Unused - internal uint methodIndex; - internal MethodBase methodBase; - internal string fileName; - internal int lineNumber; - internal int columnNumber; - // Unused - internal string internalMethodName; - #endregion - - internal bool isLastFrameFromForeignException; - } - - partial class StackTrace - { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern MonoStackFrame[] get_trace (Exception e, int skipFrames, bool needFileInfo); - - [MethodImplAttribute (MethodImplOptions.NoInlining)] - void InitializeForCurrentThread (int skipFrames, bool needFileInfo) - { - skipFrames += 2; // Current method + parent ctor - - StackFrame sf; - var frames = new List<StackFrame> (); - while (skipFrames >= 0) { - sf = new StackFrame (skipFrames, needFileInfo); - if (sf.GetMethod () == null) { - break; - } - frames.Add (sf); - skipFrames++; - } - - _stackFrames = frames.ToArray (); - _numOfFrames = _stackFrames.Length; - } - - void InitializeForException (Exception e, int skipFrames, bool needFileInfo) - { - var frames = get_trace (e, skipFrames, needFileInfo); - _numOfFrames = frames.Length; - - int foreignFrames; - MonoStackFrame[] foreignExceptions = e.foreignExceptionsFrames; - - if (foreignExceptions != null) { - foreignFrames = foreignExceptions.Length; - _numOfFrames += foreignFrames; - - _stackFrames = new StackFrame [_numOfFrames]; - - for (int i = 0; i < foreignExceptions.Length; ++i) { - _stackFrames [i] = new StackFrame (foreignExceptions [i], needFileInfo); - } - } else { - _stackFrames = new StackFrame [_numOfFrames]; - foreignFrames = 0; - } - - for (int i = 0; i < frames.Length; ++i) { - _stackFrames [foreignFrames + i] = new StackFrame (frames [i], needFileInfo); - } - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Enum.Mono.cs b/netcore/System.Private.CoreLib/src/System/Enum.Mono.cs deleted file mode 100644 index ec9c508fd36..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Enum.Mono.cs +++ /dev/null @@ -1,132 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace System -{ - partial class Enum - { - internal sealed class EnumInfo - { - public readonly bool HasFlagsAttribute; - public readonly ulong[] Values; - public readonly string[] Names; - - // Each entry contains a list of sorted pair of enum field names and values, sorted by values - public EnumInfo (bool hasFlagsAttribute, ulong[] values, string[] names) - { - HasFlagsAttribute = hasFlagsAttribute; - Values = values; - Names = names; - } - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern bool InternalHasFlag (Enum flags); - - [Intrinsic] - public bool HasFlag (Enum flag) - { - if (flag is null) - throw new ArgumentNullException (nameof (flag)); - if (!this.GetType ().IsEquivalentTo (flag.GetType ())) - throw new ArgumentException (SR.Format (SR.Argument_EnumTypeDoesNotMatch, flag.GetType (), this.GetType ())); - - return InternalHasFlag (flag); - } - - public static string? GetName (Type enumType, object value) - { - if (enumType is null) - throw new ArgumentNullException (nameof(enumType)); - - return enumType.GetEnumName (value); - } - - public static string[] GetNames (Type enumType) - { - if (enumType is null) - throw new ArgumentNullException (nameof (enumType)); - - return enumType.GetEnumNames (); - } - - public static Type GetUnderlyingType (Type enumType) - { - if (enumType is null) - throw new ArgumentNullException (nameof (enumType)); - - return enumType.GetEnumUnderlyingType (); - } - - public static Array GetValues (Type enumType) - { - if (enumType is null) - throw new ArgumentNullException (nameof (enumType)); - - return enumType.GetEnumValues (); - } - - public static bool IsDefined (Type enumType, object value) - { - if (enumType is null) - throw new ArgumentNullException (nameof (enumType)); - - return enumType.IsEnumDefined (value); - } - - internal static ulong[] InternalGetValues (RuntimeType enumType) - { - // Get all of the values - return GetEnumInfo (enumType, false).Values; - } - - internal static string[] InternalGetNames (RuntimeType enumType) - { - // Get all of the names - return GetEnumInfo (enumType, true).Names; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern bool GetEnumValuesAndNames (RuntimeType enumType, out ulong[] values, out string[] names); - - static EnumInfo GetEnumInfo (RuntimeType enumType, bool getNames = true) - { - var entry = enumType.Cache.EnumInfo; - - if (entry == null || (getNames && entry.Names == null)) { - if (!GetEnumValuesAndNames (enumType, out var values, out var names)) - Array.Sort (values, names, System.Collections.Generic.Comparer<ulong>.Default); - - bool hasFlagsAttribute = enumType.IsDefined (typeof (FlagsAttribute), inherit: false); - entry = new EnumInfo (hasFlagsAttribute, values, names); - enumType.Cache.EnumInfo = entry; - } - - return entry; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern object InternalBoxEnum (RuntimeType enumType, long value); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern CorElementType InternalGetCorElementType (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern RuntimeType InternalGetUnderlyingType (RuntimeType enumType); - - static RuntimeType ValidateRuntimeType (Type enumType) - { - if (enumType is null) - throw new ArgumentNullException (nameof (enumType)); - if (!enumType.IsEnum) - throw new ArgumentException (SR.Arg_MustBeEnum, nameof (enumType)); - if (!(enumType is RuntimeType rtType)) - throw new ArgumentException (SR.Arg_MustBeType, nameof (enumType)); - return rtType; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Environment.Mono.in b/netcore/System.Private.CoreLib/src/System/Environment.Mono.in deleted file mode 100644 index dd4c3eed22c..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Environment.Mono.in +++ /dev/null @@ -1,84 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.Globalization; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Threading; - -namespace System -{ - partial class Environment - { - const string mono_corlib_version = "@MONO_CORLIB_VERSION@"; - - public static int CurrentManagedThreadId => Thread.CurrentThread.ManagedThreadId; - - public extern static int ExitCode { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - get; - [MethodImplAttribute (MethodImplOptions.InternalCall)] - set; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern int GetProcessorCount (); - - public static string StackTrace { - [MethodImpl (MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts - get => new StackTrace (true).ToString (System.Diagnostics.StackTrace.TraceFormat.Normal); - } - - public extern static int TickCount { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - get; - } - - public extern static long TickCount64 { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - get; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static void Exit (int exitCode); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static string[] GetCommandLineArgs (); - - public static void FailFast (string message) - { - FailFast (message, null, null); - } - - public static void FailFast(string message, Exception exception) - { - FailFast (message, exception, null); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static void FailFast (string message, Exception exception, string errorSource); - } - -#region referencesource dependencies - to be removed - - partial class Environment - { - internal static string GetResourceString (string key) - { - return key; - } - - internal static string GetResourceString (string key, CultureInfo culture) - { - return key; - } - - internal static string GetResourceString (string key, params object[] values) - { - return string.Format (CultureInfo.InvariantCulture, key, values); - } - } -#endregion -} diff --git a/netcore/System.Private.CoreLib/src/System/Environment.Unix.Mono.cs b/netcore/System.Private.CoreLib/src/System/Environment.Unix.Mono.cs deleted file mode 100644 index 6b186fd13cd..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Environment.Unix.Mono.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Threading; -using Mono; - -namespace System -{ - partial class Environment - { - private static Dictionary<string, string> s_environment; - - static string GetEnvironmentVariableCore (string variable) - { - Debug.Assert(variable != null); - - if (s_environment == null) { - using (var h = RuntimeMarshal.MarshalString (variable)) { - return internalGetEnvironmentVariable_native (h.Value); - } - } - - variable = TrimStringOnFirstZero (variable); - lock (s_environment) { - s_environment.TryGetValue (variable, out string value); - return value; - } - } - - static unsafe void SetEnvironmentVariableCore (string variable, string? value) - { - Debug.Assert(variable != null); - - EnsureEnvironmentCached (); - lock (s_environment) { - variable = TrimStringOnFirstZero (variable); - value = value == null ? null : TrimStringOnFirstZero (value); - if (string.IsNullOrEmpty (value)) { - s_environment.Remove (variable); - } else { - s_environment[variable] = value; - } - } - } - - public static IDictionary GetEnvironmentVariables () - { - var results = new Hashtable(); - - EnsureEnvironmentCached(); - lock (s_environment) { - foreach (var keyValuePair in s_environment) { - results.Add(keyValuePair.Key, keyValuePair.Value); - } - } - - return results; - } - - private static string TrimStringOnFirstZero (string value) - { - int index = value.IndexOf ('\0'); - if (index >= 0) { - return value.Substring (0, index); - } - return value; - } - - private static void EnsureEnvironmentCached () - { - if (s_environment == null) { - Interlocked.CompareExchange (ref s_environment, GetSystemEnvironmentVariables (), null); - } - } - - private static Dictionary<string, string> GetSystemEnvironmentVariables () - { - var results = new Dictionary<string, string>(); - - foreach (string name in GetEnvironmentVariableNames ()) { - if (name != null) { - using (var h = RuntimeMarshal.MarshalString (name)) { - results.Add (name, internalGetEnvironmentVariable_native (h.Value)); - } - } - } - - return results; - } - - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static string internalGetEnvironmentVariable_native (IntPtr variable); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - private extern static string [] GetEnvironmentVariableNames (); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Exception.Mono.cs b/netcore/System.Private.CoreLib/src/System/Exception.Mono.cs deleted file mode 100644 index 9d1f9a402cb..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Exception.Mono.cs +++ /dev/null @@ -1,146 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.Reflection; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Text; - -namespace System -{ - [StructLayout (LayoutKind.Sequential)] - partial class Exception - { - internal readonly struct DispatchState - { - public readonly MonoStackFrame[] StackFrames; - - public DispatchState (MonoStackFrame[] stackFrames) - { - StackFrames = stackFrames; - } - } - - # region Keep in sync with MonoException in object-internals.h - string? _unused1; - internal string _message; - IDictionary _data; - Exception _innerException; - string _helpURL; - object _traceIPs; - string? _stackTraceString; - string? _remoteStackTraceString; - int _unused4; - object _dynamicMethods; // Dynamic methods referenced by the stack trace - int _HResult; - string _source; - object? _unused6; - internal MonoStackFrame[] foreignExceptionsFrames; - IntPtr[] native_trace_ips; - int caught_in_unmanaged; - #endregion - - public MethodBase? TargetSite { - get { - StackTrace st = new StackTrace (this, true); - if (st.FrameCount > 0) - return st.GetFrame (0)?.GetMethod (); - - return null; - } - } - - public virtual string? StackTrace => GetStackTrace (true); - - string? GetStackTrace (bool needFileInfo) - { - string? stackTraceString = _stackTraceString; - string? remoteStackTraceString = _remoteStackTraceString; - - if (stackTraceString != null) - return remoteStackTraceString + stackTraceString; - if (_traceIPs == null) - return remoteStackTraceString; - - return remoteStackTraceString + new StackTrace (this, needFileInfo).ToString (System.Diagnostics.StackTrace.TraceFormat.Normal); - } - - internal DispatchState CaptureDispatchState () - { - MonoStackFrame[] stackFrames; - - if (_traceIPs != null) { - stackFrames = System.Diagnostics.StackTrace.get_trace (this, 0, true); - stackFrames [stackFrames.Length - 1].isLastFrameFromForeignException = true; - - if (foreignExceptionsFrames != null) { - var combinedStackFrames = new MonoStackFrame [stackFrames.Length + foreignExceptionsFrames.Length]; - Array.Copy (foreignExceptionsFrames, 0, combinedStackFrames, 0, foreignExceptionsFrames.Length); - Array.Copy (stackFrames, 0, combinedStackFrames, foreignExceptionsFrames.Length, stackFrames.Length); - - stackFrames = combinedStackFrames; - } - } else { - stackFrames = foreignExceptionsFrames; - } - - return new DispatchState (stackFrames); - } - - internal void RestoreDispatchState (in DispatchState state) - { - foreignExceptionsFrames = state.StackFrames; - - _stackTraceString = null; - } - - [StackTraceHidden] - internal void SetCurrentStackTrace () - { - // Check to see if the exception already has a stack set in it. - if (_traceIPs != null || _stackTraceString != null || _remoteStackTraceString != null) { - ThrowHelper.ThrowInvalidOperationException (); - } - - // Store the current stack trace into the "remote" stack trace, which was originally introduced to support - // remoting of exceptions cross app-domain boundaries, and is thus concatenated into Exception.StackTrace - // when it's retrieved. - var sb = new StringBuilder (256); - new StackTrace (fNeedFileInfo: true).ToString (System.Diagnostics.StackTrace.TraceFormat.TrailingNewLine, sb); - sb.AppendLine (SR.Exception_EndStackTraceFromPreviousThrow); - _remoteStackTraceString = sb.ToString (); - } - - string? CreateSourceName () - { - var st = new StackTrace (this, fNeedFileInfo: false); - if (st.FrameCount > 0) { - StackFrame sf = st.GetFrame (0)!; - MethodBase method = sf.GetMethod (); - - Module module = method.Module; - RuntimeModule rtModule = module as RuntimeModule; - - if (rtModule == null) { - var moduleBuilder = module as System.Reflection.Emit.ModuleBuilder; - if (moduleBuilder != null) - throw new NotImplementedException (); // TODO: rtModule = moduleBuilder.InternalModule; - else - throw new ArgumentException (SR.Argument_MustBeRuntimeReflectionObject); - } - - return rtModule.GetRuntimeAssembly ().GetName ().Name; // TODO: GetSimpleName (); - } - - return null; - } - - static IDictionary CreateDataContainer () => new ListDictionaryInternal (); - - static string? SerializationWatsonBuckets => null; - string? SerializationRemoteStackTraceString => _remoteStackTraceString; - string? SerializationStackTraceString => GetStackTrace (true); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/GC.Mono.cs b/netcore/System.Private.CoreLib/src/System/GC.Mono.cs deleted file mode 100644 index e5efe52cc40..00000000000 --- a/netcore/System.Private.CoreLib/src/System/GC.Mono.cs +++ /dev/null @@ -1,268 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; -using System.Diagnostics; - -namespace System -{ - public enum GCCollectionMode - { - Default = 0, - Forced = 1, - Optimized = 2 - } - - public enum GCNotificationStatus - { - Succeeded = 0, - Failed = 1, - Canceled = 2, - Timeout = 3, - NotApplicable = 4 - } - - public static partial class GC - { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static int GetCollectionCount (int generation); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static int GetMaxGeneration (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void InternalCollect (int generation); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void RecordPressure (long bytesAllocated); - - // TODO: Move following to ConditionalWeakTable - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static void register_ephemeron_array (Ephemeron[] array); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static object get_ephemeron_tombstone (); - - internal static readonly object EPHEMERON_TOMBSTONE = get_ephemeron_tombstone (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public static extern long GetAllocatedBytesForCurrentThread (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public static extern long GetTotalAllocatedBytes (bool precise = false); - - public static void AddMemoryPressure (long bytesAllocated) - { - if (bytesAllocated <= 0) - throw new ArgumentOutOfRangeException (nameof (bytesAllocated), SR.ArgumentOutOfRange_NeedPosNum); - if (IntPtr.Size == 4 && bytesAllocated > Int32.MaxValue) - throw new ArgumentOutOfRangeException (nameof (bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); - RecordPressure (bytesAllocated); - } - - public static void RemoveMemoryPressure (long bytesAllocated) - { - if (bytesAllocated <= 0) - throw new ArgumentOutOfRangeException (nameof (bytesAllocated), SR.ArgumentOutOfRange_NeedPosNum); - if (IntPtr.Size == 4 && bytesAllocated > Int32.MaxValue) - throw new ArgumentOutOfRangeException (nameof (bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); - RecordPressure (-bytesAllocated); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public static extern int GetGeneration (object obj); - - public static void Collect (int generation) - { - Collect (generation, GCCollectionMode.Default); - } - - public static void Collect () - { - InternalCollect (MaxGeneration); - } - - public static void Collect (int generation, GCCollectionMode mode) => Collect (generation, mode, true); - - public static void Collect (int generation, GCCollectionMode mode, bool blocking) => Collect (generation, mode, blocking, false); - - public static void Collect (int generation, GCCollectionMode mode, bool blocking, bool compacting) - { - if (generation < 0) - throw new ArgumentOutOfRangeException (nameof (generation), "generation", SR.ArgumentOutOfRange_GenericPositive); - if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized)) - throw new ArgumentOutOfRangeException (nameof (mode), SR.ArgumentOutOfRange_Enum); - - InternalCollect (generation); - } - - public static int CollectionCount (int generation) - { - if (generation < 0) - throw new ArgumentOutOfRangeException (nameof (generation), SR.ArgumentOutOfRange_GenericPositive); - return GetCollectionCount (generation); - } - - [MethodImplAttribute (MethodImplOptions.NoInlining)] // disable optimizations - public static void KeepAlive (object obj) - { - } - - public static int GetGeneration (WeakReference wo) - { - object obj = wo.Target; - if (obj == null) - throw new ArgumentException (); - return GetGeneration (obj); - } - - public static int MaxGeneration { - get { - return GetMaxGeneration (); - } - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public static extern void WaitForPendingFinalizers (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern void _SuppressFinalize (object o); - - public static void SuppressFinalize (object obj) - { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - _SuppressFinalize (obj); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern void _ReRegisterForFinalize (object o); - - public static void ReRegisterForFinalize (object obj) - { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - _ReRegisterForFinalize (obj); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static long GetTotalMemory (bool forceFullCollection); - - static bool _RegisterForFullGCNotification (int maxGenerationPercentage, int largeObjectHeapPercentage) - { - throw new NotImplementedException (); - } - - static bool _CancelFullGCNotification () - { - throw new NotImplementedException (); - } - - static GCNotificationStatus _WaitForFullGCApproach (int millisecondsTimeout) - { - throw new NotImplementedException (); - } - - static GCNotificationStatus _WaitForFullGCComplete (int millisecondsTimeout) - { - throw new NotImplementedException (); - } - - public static void RegisterForFullGCNotification (int maxGenerationThreshold, int largeObjectHeapThreshold) - { - if ((maxGenerationThreshold <= 0) || (maxGenerationThreshold >= 100)) - throw new ArgumentOutOfRangeException (nameof (maxGenerationThreshold), - SR.Format (SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); - if ((largeObjectHeapThreshold <= 0) || (largeObjectHeapThreshold >= 100)) - throw new ArgumentOutOfRangeException (nameof (largeObjectHeapThreshold), - SR.Format (SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); - - if (!_RegisterForFullGCNotification (maxGenerationThreshold, largeObjectHeapThreshold)) - throw new InvalidOperationException (SR.InvalidOperation_NotWithConcurrentGC); - } - - public static void CancelFullGCNotification () - { - if (!_CancelFullGCNotification ()) - throw new InvalidOperationException (SR.InvalidOperation_NotWithConcurrentGC); - } - - public static GCNotificationStatus WaitForFullGCApproach () - { - return (GCNotificationStatus) _WaitForFullGCApproach (-1); - } - - public static GCNotificationStatus WaitForFullGCApproach (int millisecondsTimeout) - { - if (millisecondsTimeout < -1) - throw new ArgumentOutOfRangeException (nameof (millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - - return _WaitForFullGCApproach (millisecondsTimeout); - } - - public static GCNotificationStatus WaitForFullGCComplete () - { - return _WaitForFullGCComplete (-1); - } - - public static GCNotificationStatus WaitForFullGCComplete (int millisecondsTimeout) - { - if (millisecondsTimeout < -1) - throw new ArgumentOutOfRangeException (nameof (millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return _WaitForFullGCComplete (millisecondsTimeout); - } - - static bool StartNoGCRegion (long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC) - { - throw new NotImplementedException (); - } - - public static bool TryStartNoGCRegion (long totalSize) => StartNoGCRegion (totalSize, false, 0, false); - - public static bool TryStartNoGCRegion (long totalSize, long lohSize) => StartNoGCRegion (totalSize, true, lohSize, false); - - public static bool TryStartNoGCRegion (long totalSize, bool disallowFullBlockingGC) => StartNoGCRegion (totalSize, false, 0, disallowFullBlockingGC); - - public static bool TryStartNoGCRegion (long totalSize, long lohSize, bool disallowFullBlockingGC) => StartNoGCRegion (totalSize, true, lohSize, disallowFullBlockingGC); - - public static void EndNoGCRegion () - { - throw new NotImplementedException (); - } - - internal static ulong GetSegmentSize () - { - // coreclr default - return 1024 * 1024 * 16; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern void _GetGCMemoryInfo (out long highMemoryLoadThresholdBytes, - out long memoryLoadBytes, - out long totalAvailableMemoryBytes, - out long heapSizeBytes, - out long fragmentedBytes); - - public static GCMemoryInfo GetGCMemoryInfo () - { - _GetGCMemoryInfo(out long highMemoryLoadThresholdBytes, - out long memoryLoadBytes, - out long totalAvailableMemoryBytes, - out long heapSizeBytes, - out long fragmentedBytes ); - - return new GCMemoryInfo(highMemoryLoadThresholdBytes, memoryLoadBytes, totalAvailableMemoryBytes, heapSizeBytes, fragmentedBytes); - } - - internal static T[] AllocateUninitializedArray<T> (int length) - { - // Mono only does explicit zeroning if the array is to big for the nursery, but less than 1 Mb - 4 kb. - // If it is bigger than that, we grab memoroy directly from the OS which comes pre-zeroed. - // Experimentation shows that if we just skip the zeroing in this case, we do not save a measurable - // amount of time. So we just allocate the normal way here. - // Revist if we change LOS implementation. - return new T [length]; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Mono.cs b/netcore/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Mono.cs deleted file mode 100644 index 58b99e0ccc6..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Mono.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -using System.Runtime.CompilerServices; - -namespace System.Globalization -{ - internal static partial class GlobalizationMode - { - internal static bool Invariant { get; } = GetGlobalizationInvariantMode (); - - static bool GetInvariantSwitchValue () - { - var val = Environment.GetEnvironmentVariable ("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT"); - if (val != null) - return Boolean.IsTrueStringIgnoreCase (val) || val.Equals ("1"); - return false; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.Mono.cs b/netcore/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.Mono.cs deleted file mode 100644 index bdf132ea933..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.Mono.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System.Globalization -{ - partial class GlobalizationMode - { - static bool GetGlobalizationInvariantMode () - { - bool invariantEnabled = GetInvariantSwitchValue (); - if (invariantEnabled) - return true; - - LoadICU (); - return false; - } - - // Keep this in a separate method to avoid loading the native lib in invariant mode - [MethodImplAttribute (MethodImplOptions.NoInlining)] - static void LoadICU () - { - int res = Interop.Globalization.LoadICU (); - if (res == 0) { - string message = "Couldn't find a valid ICU package installed on the system. " + - "Set the configuration flag System.Globalization.Invariant to true if you want to run with no globalization support."; - Environment.FailFast (message); - } - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Windows.Mono.cs b/netcore/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Windows.Mono.cs deleted file mode 100644 index 26261423358..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Windows.Mono.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Globalization -{ - partial class GlobalizationMode - { - static bool GetGlobalizationInvariantMode () { - return GetInvariantSwitchValue (); - } - } -}
\ No newline at end of file diff --git a/netcore/System.Private.CoreLib/src/System/IO/FileLoadException.Mono.cs b/netcore/System.Private.CoreLib/src/System/IO/FileLoadException.Mono.cs deleted file mode 100644 index 0ec54d3b998..00000000000 --- a/netcore/System.Private.CoreLib/src/System/IO/FileLoadException.Mono.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.IO -{ - partial class FileLoadException - { - internal static string FormatFileLoadExceptionMessage (string fileName, int hResult) - { - return ""; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/IO/MonoIOError.cs b/netcore/System.Private.CoreLib/src/System/IO/MonoIOError.cs deleted file mode 100644 index eec82154854..00000000000 --- a/netcore/System.Private.CoreLib/src/System/IO/MonoIOError.cs +++ /dev/null @@ -1,1827 +0,0 @@ -// -// System.IO.MonoIOError.cs: Win32 error codes. Yuck. -// -// Author: -// Dan Lewis (dihlewis@yahoo.co.uk) -// -// (C) 2002 -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; - -namespace System.IO -{ - internal enum MonoIOError: int { - ERROR_SUCCESS = 0, - /* ERROR_INVALID_FUNCTION = 1, - */ ERROR_FILE_NOT_FOUND = 2, - ERROR_PATH_NOT_FOUND = 3, - ERROR_TOO_MANY_OPEN_FILES = 4, - ERROR_ACCESS_DENIED = 5, - ERROR_INVALID_HANDLE = 6, - /* ERROR_ARENA_TRASHED = 7, - ERROR_NOT_ENOUGH_MEMORY = 8, - ERROR_INVALID_BLOCK = 9, - ERROR_BAD_ENVIRONMENT = 10, - ERROR_BAD_FORMAT = 11, - ERROR_INVALID_ACCESS = 12, - ERROR_INVALID_DATA = 13, - ERROR_OUTOFMEMORY = 14, - */ ERROR_INVALID_DRIVE = 15, - /* ERROR_CURRENT_DIRECTORY = 16, - */ ERROR_NOT_SAME_DEVICE = 17, - ERROR_NO_MORE_FILES = 18, - /* ERROR_WRITE_PROTECT = 19, - ERROR_BAD_UNIT = 20, - */ - ERROR_NOT_READY = 21, - /* - ERROR_BAD_COMMAND = 22, - ERROR_CRC = 23, - ERROR_BAD_LENGTH = 24, - ERROR_SEEK = 25, - ERROR_NOT_DOS_DISK = 26, - ERROR_SECTOR_NOT_FOUND = 27, - ERROR_OUT_OF_PAPER = 28,*/ - ERROR_WRITE_FAULT = 29, - ERROR_READ_FAULT = 30, - ERROR_GEN_FAILURE = 31, - ERROR_SHARING_VIOLATION = 32, - ERROR_LOCK_VIOLATION = 33, - /* ERROR_WRONG_DISK = 34, - ERROR_SHARING_BUFFER_EXCEEDED = 36, - ERROR_HANDLE_EOF = 38, - */ ERROR_HANDLE_DISK_FULL = 39, - ERROR_NOT_SUPPORTED = 50, - /* ERROR_REM_NOT_LIST = 51, - ERROR_DUP_NAME = 52, - ERROR_BAD_NETPATH = 53, - ERROR_NETWORK_BUSY = 54, - ERROR_DEV_NOT_EXIST = 55, - ERROR_TOO_MANY_CMDS = 56, - ERROR_ADAP_HDW_ERR = 57, - ERROR_BAD_NET_RESP = 58, - ERROR_UNEXP_NET_ERR = 59, - ERROR_BAD_REM_ADAP = 60, - ERROR_PRINTQ_FULL = 61, - ERROR_NO_SPOOL_SPACE = 62, - ERROR_PRINT_CANCELLED = 63, - ERROR_NETNAME_DELETED = 64, - ERROR_NETWORK_ACCESS_DENIED = 65, - ERROR_BAD_DEV_TYPE = 66, - ERROR_BAD_NET_NAME = 67, - ERROR_TOO_MANY_NAMES = 68, - ERROR_TOO_MANY_SESS = 69, - ERROR_SHARING_PAUSED = 70, - ERROR_REQ_NOT_ACCEP = 71, - ERROR_REDIR_PAUSED = 72, - */ ERROR_FILE_EXISTS = 80, - ERROR_CANNOT_MAKE = 82, - /* ERROR_FAIL_I24 = 83, - ERROR_OUT_OF_STRUCTURES = 84, - ERROR_ALREADY_ASSIGNED = 85, - ERROR_INVALID_PASSWORD = 86, - */ ERROR_INVALID_PARAMETER = 87, - /* ERROR_NET_WRITE_FAULT = 88, - ERROR_NO_PROC_SLOTS = 89, - ERROR_TOO_MANY_SEMAPHORES = 100, - ERROR_EXCL_SEM_ALREADY_OWNED = 101, - ERROR_SEM_IS_SET = 102, - ERROR_TOO_MANY_SEM_REQUESTS = 103, - ERROR_INVALID_AT_INTERRUPT_TIME = 104, - ERROR_SEM_OWNER_DIED = 105, - ERROR_SEM_USER_LIMIT = 106, - ERROR_DISK_CHANGE = 107, - ERROR_DRIVE_LOCKED = 108, - */ ERROR_BROKEN_PIPE = 109, - /* ERROR_OPEN_FAILED = 110, - ERROR_BUFFER_OVERFLOW = 111, - ERROR_DISK_FULL = 112, - ERROR_NO_MORE_SEARCH_HANDLES = 113, - ERROR_INVALID_TARGET_HANDLE = 114, - ERROR_INVALID_CATEGORY = 117, - ERROR_INVALID_VERIFY_SWITCH = 118, - ERROR_BAD_DRIVER_LEVEL = 119, - ERROR_CALL_NOT_IMPLEMENTED = 120, - ERROR_SEM_TIMEOUT = 121, - ERROR_INSUFFICIENT_BUFFER = 122, - */ ERROR_INVALID_NAME = 123, - /* ERROR_INVALID_LEVEL = 124, - ERROR_NO_VOLUME_LABEL = 125, - ERROR_MOD_NOT_FOUND = 126, - ERROR_PROC_NOT_FOUND = 127, - ERROR_WAIT_NO_CHILDREN = 128, - ERROR_CHILD_NOT_COMPLETE = 129, - ERROR_DIRECT_ACCESS_HANDLE = 130, - ERROR_NEGATIVE_SEEK = 131, - ERROR_SEEK_ON_DEVICE = 132, - ERROR_IS_JOIN_TARGET = 133, - ERROR_IS_JOINED = 134, - ERROR_IS_SUBSTED = 135, - ERROR_NOT_JOINED = 136, - ERROR_NOT_SUBSTED = 137, - ERROR_JOIN_TO_JOIN = 138, - ERROR_SUBST_TO_SUBST = 139, - ERROR_JOIN_TO_SUBST = 140, - ERROR_SUBST_TO_JOIN = 141, - ERROR_BUSY_DRIVE = 142, - ERROR_SAME_DRIVE = 143, - ERROR_DIR_NOT_ROOT = 144, - */ - ERROR_DIR_NOT_EMPTY = 145, - /* - ERROR_IS_SUBST_PATH = 146, - ERROR_IS_JOIN_PATH = 147, - ERROR_PATH_BUSY = 148, - ERROR_IS_SUBST_TARGET = 149, - ERROR_SYSTEM_TRACE = 150, - ERROR_INVALID_EVENT_COUNT = 151, - ERROR_TOO_MANY_MUXWAITERS = 152, - ERROR_INVALID_LIST_FORMAT = 153, - ERROR_LABEL_TOO_LONG = 154, - ERROR_TOO_MANY_TCBS = 155, - ERROR_SIGNAL_REFUSED = 156, - ERROR_DISCARDED = 157, - ERROR_NOT_LOCKED = 158, - ERROR_BAD_THREADID_ADDR = 159, - ERROR_BAD_ARGUMENTS = 160, - ERROR_BAD_PATHNAME = 161, - ERROR_SIGNAL_PENDING = 162, - ERROR_MAX_THRDS_REACHED = 164, - ERROR_LOCK_FAILED = 167, - ERROR_BUSY = 170, - ERROR_CANCEL_VIOLATION = 173, - ERROR_ATOMIC_LOCKS_NOT_SUPPORTED = 174, - ERROR_INVALID_SEGMENT_NUMBER = 180, - ERROR_INVALID_ORDINAL = 182, - */ ERROR_ALREADY_EXISTS = 183, - /* ERROR_INVALID_FLAG_NUMBER = 186, - ERROR_SEM_NOT_FOUND = 187, - ERROR_INVALID_STARTING_CODESEG = 188, - ERROR_INVALID_STACKSEG = 189, - ERROR_INVALID_MODULETYPE = 190, - ERROR_INVALID_EXE_SIGNATURE = 191, - ERROR_EXE_MARKED_INVALID = 192, - ERROR_BAD_EXE_FORMAT = 193, - ERROR_ITERATED_DATA_EXCEEDS_64k = 194, - ERROR_INVALID_MINALLOCSIZE = 195, - ERROR_DYNLINK_FROM_INVALID_RING = 196, - ERROR_IOPL_NOT_ENABLED = 197, - ERROR_INVALID_SEGDPL = 198, - ERROR_AUTODATASEG_EXCEEDS_64k = 199, - ERROR_RING2SEG_MUST_BE_MOVABLE = 200, - ERROR_RELOC_CHAIN_XEEDS_SEGLIM = 201, - ERROR_INFLOOP_IN_RELOC_CHAIN = 202, - ERROR_ENVVAR_NOT_FOUND = 203, - ERROR_NO_SIGNAL_SENT = 205, - */ ERROR_FILENAME_EXCED_RANGE = 206, - /* ERROR_RING2_STACK_IN_USE = 207, - ERROR_META_EXPANSION_TOO_LONG = 208, - ERROR_INVALID_SIGNAL_NUMBER = 209, - ERROR_THREAD_1_INACTIVE = 210, - ERROR_LOCKED = 212, - ERROR_TOO_MANY_MODULES = 214, - ERROR_NESTING_NOT_ALLOWED = 215, - ERROR_EXE_MACHINE_TYPE_MISMATCH = 216, - ERROR_BAD_PIPE = 230, - ERROR_PIPE_BUSY = 231, - ERROR_NO_DATA = 232, - ERROR_PIPE_NOT_CONNECTED = 233, - ERROR_MORE_DATA = 234, - ERROR_VC_DISCONNECTED = 240, - ERROR_INVALID_EA_NAME = 254, - ERROR_EA_LIST_INCONSISTENT = 255, - WAIT_TIMEOUT = 258, - ERROR_NO_MORE_ITEMS = 259, - ERROR_CANNOT_COPY = 266, - */ ERROR_DIRECTORY = 267, - /* ERROR_EAS_DIDNT_FIT = 275, - ERROR_EA_FILE_CORRUPT = 276, - ERROR_EA_TABLE_FULL = 277, - ERROR_INVALID_EA_HANDLE = 278, - ERROR_EAS_NOT_SUPPORTED = 282, - ERROR_NOT_OWNER = 288, - ERROR_TOO_MANY_POSTS = 298, - ERROR_PARTIAL_COPY = 299, - ERROR_OPLOCK_NOT_GRANTED = 300, - ERROR_INVALID_OPLOCK_PROTOCOL = 301, - ERROR_DISK_TOO_FRAGMENTED = 302, - ERROR_DELETE_PENDING = 303, - ERROR_MR_MID_NOT_FOUND = 317, - ERROR_INVALID_ADDRESS = 487, - ERROR_ARITHMETIC_OVERFLOW = 534, - ERROR_PIPE_CONNECTED = 535, - ERROR_PIPE_LISTENING = 536, - ERROR_EA_ACCESS_DENIED = 994, - ERROR_OPERATION_ABORTED = 995, - ERROR_IO_INCOMPLETE = 996, - ERROR_IO_PENDING = 997, - ERROR_NOACCESS = 998, - ERROR_SWAPERROR = 999, - ERROR_STACK_OVERFLOW = 1001, - ERROR_INVALID_MESSAGE = 1002, - ERROR_CAN_NOT_COMPLETE = 1003, - ERROR_INVALID_FLAGS = 1004, - ERROR_UNRECOGNIZED_VOLUME = 1005, - ERROR_FILE_INVALID = 1006, - ERROR_FULLSCREEN_MODE = 1007, - ERROR_NO_TOKEN = 1008, - ERROR_BADDB = 1009, - ERROR_BADKEY = 1010, - ERROR_CANTOPEN = 1011, - ERROR_CANTREAD = 1012, - ERROR_CANTWRITE = 1013, - ERROR_REGISTRY_RECOVERED = 1014, - ERROR_REGISTRY_CORRUPT = 1015, - ERROR_REGISTRY_IO_FAILED = 1016, - ERROR_NOT_REGISTRY_FILE = 1017, - ERROR_KEY_DELETED = 1018, - ERROR_NO_LOG_SPACE = 1019, - ERROR_KEY_HAS_CHILDREN = 1020, - ERROR_CHILD_MUST_BE_VOLATILE = 1021, - ERROR_NOTIFY_ENUM_DIR = 1022, - ERROR_DEPENDENT_SERVICES_RUNNING = 1051, - ERROR_INVALID_SERVICE_CONTROL = 1052, - ERROR_SERVICE_REQUEST_TIMEOUT = 1053, - ERROR_SERVICE_NO_THREAD = 1054, - ERROR_SERVICE_DATABASE_LOCKED = 1055, - ERROR_SERVICE_ALREADY_RUNNING = 1056, - ERROR_INVALID_SERVICE_ACCOUNT = 1057, - ERROR_SERVICE_DISABLED = 1058, - ERROR_CIRCULAR_DEPENDENCY = 1059, - ERROR_SERVICE_DOES_NOT_EXIST = 1060, - ERROR_SERVICE_CANNOT_ACCEPT_CTRL = 1061, - ERROR_SERVICE_NOT_ACTIVE = 1062, - ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063, - ERROR_EXCEPTION_IN_SERVICE = 1064, - ERROR_DATABASE_DOES_NOT_EXIST = 1065, - ERROR_SERVICE_SPECIFIC_ERROR = 1066, - ERROR_PROCESS_ABORTED = 1067, - ERROR_SERVICE_DEPENDENCY_FAIL = 1068, - ERROR_SERVICE_LOGON_FAILED = 1069, - ERROR_SERVICE_START_HANG = 1070, - ERROR_INVALID_SERVICE_LOCK = 1071, - ERROR_SERVICE_MARKED_FOR_DELETE = 1072, - ERROR_SERVICE_EXISTS = 1073, - ERROR_ALREADY_RUNNING_LKG = 1074, - ERROR_SERVICE_DEPENDENCY_DELETED = 1075, - ERROR_BOOT_ALREADY_ACCEPTED = 1076, - ERROR_SERVICE_NEVER_STARTED = 1077, - ERROR_DUPLICATE_SERVICE_NAME = 1078, - ERROR_DIFFERENT_SERVICE_ACCOUNT = 1079, - ERROR_CANNOT_DETECT_DRIVER_FAILURE = 1080, - ERROR_CANNOT_DETECT_PROCESS_ABORT = 1081, - ERROR_NO_RECOVERY_PROGRAM = 1082, - ERROR_SERVICE_NOT_IN_EXE = 1083, - ERROR_NOT_SAFEBOOT_SERVICE = 1084, - ERROR_END_OF_MEDIA = 1100, - ERROR_FILEMARK_DETECTED = 1101, - ERROR_BEGINNING_OF_MEDIA = 1102, - ERROR_SETMARK_DETECTED = 1103, - ERROR_NO_DATA_DETECTED = 1104, - ERROR_PARTITION_FAILURE = 1105, - ERROR_INVALID_BLOCK_LENGTH = 1106, - ERROR_DEVICE_NOT_PARTITIONED = 1107, - ERROR_UNABLE_TO_LOCK_MEDIA = 1108, - ERROR_UNABLE_TO_UNLOAD_MEDIA = 1109, - ERROR_MEDIA_CHANGED = 1110, - ERROR_BUS_RESET = 1111, - ERROR_NO_MEDIA_IN_DRIVE = 1112, - ERROR_NO_UNICODE_TRANSLATION = 1113, - ERROR_DLL_INIT_FAILED = 1114, - ERROR_SHUTDOWN_IN_PROGRESS = 1115, - ERROR_NO_SHUTDOWN_IN_PROGRESS = 1116, - ERROR_IO_DEVICE = 1117, - ERROR_SERIAL_NO_DEVICE = 1118, - ERROR_IRQ_BUSY = 1119, - ERROR_MORE_WRITES = 1120, - ERROR_COUNTER_TIMEOUT = 1121, - ERROR_FLOPPY_ID_MARK_NOT_FOUND = 1122, - ERROR_FLOPPY_WRONG_CYLINDER = 1123, - ERROR_FLOPPY_UNKNOWN_ERROR = 1124, - ERROR_FLOPPY_BAD_REGISTERS = 1125, - ERROR_DISK_RECALIBRATE_FAILED = 1126, - ERROR_DISK_OPERATION_FAILED = 1127, - ERROR_DISK_RESET_FAILED = 1128, - ERROR_EOM_OVERFLOW = 1129, - ERROR_NOT_ENOUGH_SERVER_MEMORY = 1130, - ERROR_POSSIBLE_DEADLOCK = 1131, - ERROR_MAPPED_ALIGNMENT = 1132, - ERROR_SET_POWER_STATE_VETOED = 1140, - ERROR_SET_POWER_STATE_FAILED = 1141, - ERROR_TOO_MANY_LINKS = 1142, - ERROR_OLD_WIN_VERSION = 1150, - ERROR_APP_WRONG_OS = 1151, - ERROR_SINGLE_INSTANCE_APP = 1152, - ERROR_RMODE_APP = 1153, - ERROR_INVALID_DLL = 1154, - ERROR_NO_ASSOCIATION = 1155, - ERROR_DDE_FAIL = 1156, - ERROR_DLL_NOT_FOUND = 1157, - ERROR_NO_MORE_USER_HANDLES = 1158, - ERROR_MESSAGE_SYNC_ONLY = 1159, - ERROR_SOURCE_ELEMENT_EMPTY = 1160, - ERROR_DESTINATION_ELEMENT_FULL = 1161, - ERROR_ILLEGAL_ELEMENT_ADDRESS = 1162, - ERROR_MAGAZINE_NOT_PRESENT = 1163, - ERROR_DEVICE_REINITIALIZATION_NEEDED = 1164, - ERROR_DEVICE_REQUIRES_CLEANING = 1165, - ERROR_DEVICE_DOOR_OPEN = 1166, - ERROR_DEVICE_NOT_CONNECTED = 1167, - ERROR_NOT_FOUND = 1168, - ERROR_NO_MATCH = 1169, - ERROR_SET_NOT_FOUND = 1170, - ERROR_POINT_NOT_FOUND = 1171, - ERROR_NO_TRACKING_SERVICE = 1172, - ERROR_NO_VOLUME_ID = 1173, - ERROR_UNABLE_TO_REMOVE_REPLACED = 1175, - ERROR_UNABLE_TO_MOVE_REPLACEMENT = 1176, - ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 = 1177, - ERROR_JOURNAL_DELETE_IN_PROGRESS = 1178, - ERROR_JOURNAL_NOT_ACTIVE = 1179, - ERROR_POTENTIAL_FILE_FOUND = 1180, - ERROR_JOURNAL_ENTRY_DELETED = 1181, - ERROR_BAD_DEVICE = 1200, - ERROR_CONNECTION_UNAVAIL = 1201, - ERROR_DEVICE_ALREADY_REMEMBERED = 1202, - ERROR_NO_NET_OR_BAD_PATH = 1203, - ERROR_BAD_PROVIDER = 1204, - ERROR_CANNOT_OPEN_PROFILE = 1205, - ERROR_BAD_PROFILE = 1206, - ERROR_NOT_CONTAINER = 1207, - ERROR_EXTENDED_ERROR = 1208, - ERROR_INVALID_GROUPNAME = 1209, - ERROR_INVALID_COMPUTERNAME = 1210, - ERROR_INVALID_EVENTNAME = 1211, - ERROR_INVALID_DOMAINNAME = 1212, - ERROR_INVALID_SERVICENAME = 1213, - ERROR_INVALID_NETNAME = 1214, - ERROR_INVALID_SHARENAME = 1215, - ERROR_INVALID_PASSWORDNAME = 1216, - ERROR_INVALID_MESSAGENAME = 1217, - ERROR_INVALID_MESSAGEDEST = 1218, - ERROR_SESSION_CREDENTIAL_CONFLICT = 1219, - ERROR_REMOTE_SESSION_LIMIT_EXCEEDED = 1220, - ERROR_DUP_DOMAINNAME = 1221, - ERROR_NO_NETWORK = 1222, - ERROR_CANCELLED = 1223, - ERROR_USER_MAPPED_FILE = 1224, - ERROR_CONNECTION_REFUSED = 1225, - ERROR_GRACEFUL_DISCONNECT = 1226, - ERROR_ADDRESS_ALREADY_ASSOCIATED = 1227, - ERROR_ADDRESS_NOT_ASSOCIATED = 1228, - ERROR_CONNECTION_INVALID = 1229, - ERROR_CONNECTION_ACTIVE = 1230, - ERROR_NETWORK_UNREACHABLE = 1231, - ERROR_HOST_UNREACHABLE = 1232, - ERROR_PROTOCOL_UNREACHABLE = 1233, - ERROR_PORT_UNREACHABLE = 1234, - ERROR_REQUEST_ABORTED = 1235, - ERROR_CONNECTION_ABORTED = 1236, - ERROR_RETRY = 1237, - ERROR_CONNECTION_COUNT_LIMIT = 1238, - ERROR_LOGIN_TIME_RESTRICTION = 1239, - ERROR_LOGIN_WKSTA_RESTRICTION = 1240, - ERROR_INCORRECT_ADDRESS = 1241, - ERROR_ALREADY_REGISTERED = 1242, - ERROR_SERVICE_NOT_FOUND = 1243, - ERROR_NOT_AUTHENTICATED = 1244, - ERROR_NOT_LOGGED_ON = 1245, - ERROR_CONTINUE = 1246, - ERROR_ALREADY_INITIALIZED = 1247, - ERROR_NO_MORE_DEVICES = 1248, - ERROR_NO_SUCH_SITE = 1249, - ERROR_DOMAIN_CONTROLLER_EXISTS = 1250, - ERROR_ONLY_IF_CONNECTED = 1251, - ERROR_OVERRIDE_NOCHANGES = 1252, - ERROR_BAD_USER_PROFILE = 1253, - ERROR_NOT_SUPPORTED_ON_SBS = 1254, - ERROR_SERVER_SHUTDOWN_IN_PROGRESS = 1255, - ERROR_HOST_DOWN = 1256, - ERROR_NON_ACCOUNT_SID = 1257, - ERROR_NON_DOMAIN_SID = 1258, - ERROR_APPHELP_BLOCK = 1259, - ERROR_ACCESS_DISABLED_BY_POLICY = 1260, - ERROR_REG_NAT_CONSUMPTION = 1261, - ERROR_CSCSHARE_OFFLINE = 1262, - ERROR_PKINIT_FAILURE = 1263, - ERROR_SMARTCARD_SUBSYSTEM_FAILURE = 1264, - ERROR_DOWNGRADE_DETECTED = 1265, - SEC_E_SMARTCARD_CERT_REVOKED = 1266, - SEC_E_ISSUING_CA_UNTRUSTED = 1267, - SEC_E_REVOCATION_OFFLINE_C = 1268, - SEC_E_PKINIT_CLIENT_FAILUR = 1269, - SEC_E_SMARTCARD_CERT_EXPIRED = 1270, - ERROR_MACHINE_LOCKED = 1271, - ERROR_CALLBACK_SUPPLIED_INVALID_DATA = 1273, - ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED = 1274, - ERROR_DRIVER_BLOCKED = 1275, - ERROR_INVALID_IMPORT_OF_NON_DLL = 1276, - ERROR_NOT_ALL_ASSIGNED = 1300, - ERROR_SOME_NOT_MAPPED = 1301, - ERROR_NO_QUOTAS_FOR_ACCOUNT = 1302, - ERROR_LOCAL_USER_SESSION_KEY = 1303, - ERROR_NULL_LM_PASSWORD = 1304, - ERROR_UNKNOWN_REVISION = 1305, - ERROR_REVISION_MISMATCH = 1306, - ERROR_INVALID_OWNER = 1307, - ERROR_INVALID_PRIMARY_GROUP = 1308, - ERROR_NO_IMPERSONATION_TOKEN = 1309, - ERROR_CANT_DISABLE_MANDATORY = 1310, - ERROR_NO_LOGON_SERVERS = 1311, - ERROR_NO_SUCH_LOGON_SESSION = 1312, - ERROR_NO_SUCH_PRIVILEGE = 1313, - ERROR_PRIVILEGE_NOT_HELD = 1314, - ERROR_INVALID_ACCOUNT_NAME = 1315, - ERROR_USER_EXISTS = 1316, - ERROR_NO_SUCH_USER = 1317, - ERROR_GROUP_EXISTS = 1318, - ERROR_NO_SUCH_GROUP = 1319, - ERROR_MEMBER_IN_GROUP = 1320, - ERROR_MEMBER_NOT_IN_GROUP = 1321, - ERROR_LAST_ADMIN = 1322, - ERROR_WRONG_PASSWORD = 1323, - ERROR_ILL_FORMED_PASSWORD = 1324, - ERROR_PASSWORD_RESTRICTION = 1325, - ERROR_LOGON_FAILURE = 1326, - ERROR_ACCOUNT_RESTRICTION = 1327, - ERROR_INVALID_LOGON_HOURS = 1328, - ERROR_INVALID_WORKSTATION = 1329, - ERROR_PASSWORD_EXPIRED = 1330, - ERROR_ACCOUNT_DISABLED = 1331, - ERROR_NONE_MAPPED = 1332, - ERROR_TOO_MANY_LUIDS_REQUESTED = 1333, - ERROR_LUIDS_EXHAUSTED = 1334, - ERROR_INVALID_SUB_AUTHORITY = 1335, - ERROR_INVALID_ACL = 1336, - ERROR_INVALID_SID = 1337, - ERROR_INVALID_SECURITY_DESCR = 1338, - ERROR_BAD_INHERITANCE_ACL = 1340, - ERROR_SERVER_DISABLED = 1341, - ERROR_SERVER_NOT_DISABLED = 1342, - ERROR_INVALID_ID_AUTHORITY = 1343, - ERROR_ALLOTTED_SPACE_EXCEEDED = 1344, - ERROR_INVALID_GROUP_ATTRIBUTES = 1345, - ERROR_BAD_IMPERSONATION_LEVEL = 1346, - ERROR_CANT_OPEN_ANONYMOUS = 1347, - ERROR_BAD_VALIDATION_CLASS = 1348, - ERROR_BAD_TOKEN_TYPE = 1349, - ERROR_NO_SECURITY_ON_OBJECT = 1350, - ERROR_CANT_ACCESS_DOMAIN_INFO = 1351, - ERROR_INVALID_SERVER_STATE = 1352, - ERROR_INVALID_DOMAIN_STATE = 1353, - ERROR_INVALID_DOMAIN_ROLE = 1354, - ERROR_NO_SUCH_DOMAIN = 1355, - ERROR_DOMAIN_EXISTS = 1356, - ERROR_DOMAIN_LIMIT_EXCEEDED = 1357, - ERROR_INTERNAL_DB_CORRUPTION = 1358, - ERROR_INTERNAL_ERROR = 1359, - ERROR_GENERIC_NOT_MAPPED = 1360, - ERROR_BAD_DESCRIPTOR_FORMAT = 1361, - ERROR_NOT_LOGON_PROCESS = 1362, - ERROR_LOGON_SESSION_EXISTS = 1363, - ERROR_NO_SUCH_PACKAGE = 1364, - ERROR_BAD_LOGON_SESSION_STATE = 1365, - ERROR_LOGON_SESSION_COLLISION = 1366, - ERROR_INVALID_LOGON_TYPE = 1367, - ERROR_CANNOT_IMPERSONATE = 1368, - ERROR_RXACT_INVALID_STATE = 1369, - ERROR_RXACT_COMMIT_FAILURE = 1370, - ERROR_SPECIAL_ACCOUNT = 1371, - ERROR_SPECIAL_GROUP = 1372, - ERROR_SPECIAL_USER = 1373, - ERROR_MEMBERS_PRIMARY_GROUP = 1374, - ERROR_TOKEN_ALREADY_IN_USE = 1375, - ERROR_NO_SUCH_ALIAS = 1376, - ERROR_MEMBER_NOT_IN_ALIAS = 1377, - ERROR_MEMBER_IN_ALIAS = 1378, - ERROR_ALIAS_EXISTS = 1379, - ERROR_LOGON_NOT_GRANTED = 1380, - ERROR_TOO_MANY_SECRETS = 1381, - ERROR_SECRET_TOO_LONG = 1382, - ERROR_INTERNAL_DB_ERROR = 1383, - ERROR_TOO_MANY_CONTEXT_IDS = 1384, - ERROR_LOGON_TYPE_NOT_GRANTED = 1385, - ERROR_NT_CROSS_ENCRYPTION_REQUIRED = 1386, - ERROR_NO_SUCH_MEMBER = 1387, - ERROR_INVALID_MEMBER = 1388, - ERROR_TOO_MANY_SIDS = 1389, - ERROR_LM_CROSS_ENCRYPTION_REQUIRED = 1390, - ERROR_NO_INHERITANCE = 1391, - ERROR_FILE_CORRUPT = 1392, - ERROR_DISK_CORRUPT = 1393, - ERROR_NO_USER_SESSION_KEY = 1394, - ERROR_LICENSE_QUOTA_EXCEEDED = 1395, - ERROR_WRONG_TARGET_NAME = 1396, - ERROR_MUTUAL_AUTH_FAILED = 1397, - ERROR_TIME_SKEW = 1398, - ERROR_CURRENT_DOMAIN_NOT_ALLOWED = 1399, - ERROR_INVALID_WINDOW_HANDLE = 1400, - ERROR_INVALID_MENU_HANDLE = 1401, - ERROR_INVALID_CURSOR_HANDLE = 1402, - ERROR_INVALID_ACCEL_HANDLE = 1403, - ERROR_INVALID_HOOK_HANDLE = 1404, - ERROR_INVALID_DWP_HANDLE = 1405, - ERROR_TLW_WITH_WSCHILD = 1406, - ERROR_CANNOT_FIND_WND_CLASS = 1407, - ERROR_WINDOW_OF_OTHER_THREAD = 1408, - ERROR_HOTKEY_ALREADY_REGISTERED = 1409, - ERROR_CLASS_ALREADY_EXISTS = 1410, - ERROR_CLASS_DOES_NOT_EXIST = 1411, - ERROR_CLASS_HAS_WINDOWS = 1412, - ERROR_INVALID_INDEX = 1413, - ERROR_INVALID_ICON_HANDLE = 1414, - ERROR_PRIVATE_DIALOG_INDEX = 1415, - ERROR_LISTBOX_ID_NOT_FOUND = 1416, - ERROR_NO_WILDCARD_CHARACTERS = 1417, - ERROR_CLIPBOARD_NOT_OPEN = 1418, - ERROR_HOTKEY_NOT_REGISTERED = 1419, - ERROR_WINDOW_NOT_DIALOG = 1420, - ERROR_CONTROL_ID_NOT_FOUND = 1421, - ERROR_INVALID_COMBOBOX_MESSAGE = 1422, - ERROR_WINDOW_NOT_COMBOBOX = 1423, - ERROR_INVALID_EDIT_HEIGHT = 1424, - ERROR_DC_NOT_FOUND = 1425, - ERROR_INVALID_HOOK_FILTER = 1426, - ERROR_INVALID_FILTER_PROC = 1427, - ERROR_HOOK_NEEDS_HMOD = 1428, - ERROR_GLOBAL_ONLY_HOOK = 1429, - ERROR_JOURNAL_HOOK_SET = 1430, - ERROR_HOOK_NOT_INSTALLED = 1431, - ERROR_INVALID_LB_MESSAGE = 1432, - ERROR_SETCOUNT_ON_BAD_LB = 1433, - ERROR_LB_WITHOUT_TABSTOPS = 1434, - ERROR_DESTROY_OBJECT_OF_OTHER_THREAD = 1435, - ERROR_CHILD_WINDOW_MENU = 1436, - ERROR_NO_SYSTEM_MENU = 1437, - ERROR_INVALID_MSGBOX_STYLE = 1438, - ERROR_INVALID_SPI_VALUE = 1439, - ERROR_SCREEN_ALREADY_LOCKED = 1440, - ERROR_HWNDS_HAVE_DIFF_PARENT = 1441, - ERROR_NOT_CHILD_WINDOW = 1442, - ERROR_INVALID_GW_COMMAND = 1443, - ERROR_INVALID_THREAD_ID = 1444, - ERROR_NON_MDICHILD_WINDOW = 1445, - ERROR_POPUP_ALREADY_ACTIVE = 1446, - ERROR_NO_SCROLLBARS = 1447, - ERROR_INVALID_SCROLLBAR_RANGE = 1448, - ERROR_INVALID_SHOWWIN_COMMAND = 1449, - ERROR_NO_SYSTEM_RESOURCES = 1450, - ERROR_NONPAGED_SYSTEM_RESOURCES = 1451, - ERROR_PAGED_SYSTEM_RESOURCES = 1452, - ERROR_WORKING_SET_QUOTA = 1453, - ERROR_PAGEFILE_QUOTA = 1454, - ERROR_COMMITMENT_LIMIT = 1455, - ERROR_MENU_ITEM_NOT_FOUND = 1456, - ERROR_INVALID_KEYBOARD_HANDLE = 1457, - ERROR_HOOK_TYPE_NOT_ALLOWED = 1458, - ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION = 1459, - ERROR_TIMEOUT = 1460, - ERROR_INVALID_MONITOR_HANDLE = 1461, - ERROR_EVENTLOG_FILE_CORRUPT = 1500, - ERROR_EVENTLOG_CANT_START = 1501, - ERROR_LOG_FILE_FULL = 1502, - ERROR_EVENTLOG_FILE_CHANGED = 1503, - ERROR_INSTALL_SERVICE_FAILURE = 1601, - ERROR_INSTALL_USEREXIT = 1602, - ERROR_INSTALL_FAILURE = 1603, - ERROR_INSTALL_SUSPEND = 1604, - ERROR_UNKNOWN_PRODUCT = 1605, - ERROR_UNKNOWN_FEATURE = 1606, - ERROR_UNKNOWN_COMPONENT = 1607, - ERROR_UNKNOWN_PROPERTY = 1608, - ERROR_INVALID_HANDLE_STATE = 1609, - ERROR_BAD_CONFIGURATION = 1610, - ERROR_INDEX_ABSENT = 1611, - ERROR_INSTALL_SOURCE_ABSENT = 1612, - ERROR_INSTALL_PACKAGE_VERSION = 1613, - ERROR_PRODUCT_UNINSTALLED = 1614, - ERROR_BAD_QUERY_SYNTAX = 1615, - ERROR_INVALID_FIELD = 1616, - ERROR_DEVICE_REMOVED = 1617, - ERROR_INSTALL_ALREADY_RUNNING = 1618, - ERROR_INSTALL_PACKAGE_OPEN_FAILED = 1619, - ERROR_INSTALL_PACKAGE_INVALID = 1620, - ERROR_INSTALL_UI_FAILURE = 1621, - ERROR_INSTALL_LOG_FAILURE = 1622, - ERROR_INSTALL_LANGUAGE_UNSUPPORTED = 1623, - ERROR_INSTALL_TRANSFORM_FAILURE = 1624, - ERROR_INSTALL_PACKAGE_REJECTED = 1625, - ERROR_FUNCTION_NOT_CALLED = 1626, - ERROR_FUNCTION_FAILED = 1627, - ERROR_INVALID_TABLE = 1628, - ERROR_DATATYPE_MISMATCH = 1629, - ERROR_UNSUPPORTED_TYPE = 1630, - ERROR_CREATE_FAILED = 1631, - ERROR_INSTALL_TEMP_UNWRITABLE = 1632, - ERROR_INSTALL_PLATFORM_UNSUPPORTED = 1633, - ERROR_INSTALL_NOTUSED = 1634, - ERROR_PATCH_PACKAGE_OPEN_FAILED = 1635, - ERROR_PATCH_PACKAGE_INVALID = 1636, - ERROR_PATCH_PACKAGE_UNSUPPORTED = 1637, - ERROR_PRODUCT_VERSION = 1638, - ERROR_INVALID_COMMAND_LINE = 1639, - ERROR_INSTALL_REMOTE_DISALLOWED = 1640, - ERROR_SUCCESS_REBOOT_INITIATED = 1641, - ERROR_PATCH_TARGET_NOT_FOUND = 1642, - ERROR_PATCH_PACKAGE_REJECTED = 1643, - ERROR_INSTALL_TRANSFORM_REJECTED = 1644, - RPC_S_INVALID_STRING_BINDING = 1700, - RPC_S_WRONG_KIND_OF_BINDING = 1701, - RPC_S_INVALID_BINDING = 1702, - RPC_S_PROTSEQ_NOT_SUPPORTED = 1703, - RPC_S_INVALID_RPC_PROTSEQ = 1704, - RPC_S_INVALID_STRING_UUID = 1705, - RPC_S_INVALID_ENDPOINT_FORMAT = 1706, - RPC_S_INVALID_NET_ADDR = 1707, - RPC_S_NO_ENDPOINT_FOUND = 1708, - RPC_S_INVALID_TIMEOUT = 1709, - RPC_S_OBJECT_NOT_FOUND = 1710, - RPC_S_ALREADY_REGISTERED = 1711, - RPC_S_TYPE_ALREADY_REGISTERED = 1712, - RPC_S_ALREADY_LISTENING = 1713, - RPC_S_NO_PROTSEQS_REGISTERED = 1714, - RPC_S_NOT_LISTENING = 1715, - RPC_S_UNKNOWN_MGR_TYPE = 1716, - RPC_S_UNKNOWN_IF = 1717, - RPC_S_NO_BINDINGS = 1718, - RPC_S_NO_PROTSEQS = 1719, - RPC_S_CANT_CREATE_ENDPOINT = 1720, - RPC_S_OUT_OF_RESOURCES = 1721, - RPC_S_SERVER_UNAVAILABLE = 1722, - RPC_S_SERVER_TOO_BUSY = 1723, - RPC_S_INVALID_NETWORK_OPTIONS = 1724, - RPC_S_NO_CALL_ACTIVE = 1725, - RPC_S_CALL_FAILED = 1726, - RPC_S_CALL_FAILED_DNE = 1727, - RPC_S_PROTOCOL_ERROR = 1728, - RPC_S_UNSUPPORTED_TRANS_SYN = 1730, - RPC_S_UNSUPPORTED_TYPE = 1732, - RPC_S_INVALID_TAG = 1733, - RPC_S_INVALID_BOUND = 1734, - RPC_S_NO_ENTRY_NAME = 1735, - RPC_S_INVALID_NAME_SYNTAX = 1736, - RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737, - RPC_S_UUID_NO_ADDRESS = 1739, - RPC_S_DUPLICATE_ENDPOINT = 1740, - RPC_S_UNKNOWN_AUTHN_TYPE = 1741, - RPC_S_MAX_CALLS_TOO_SMALL = 1742, - RPC_S_STRING_TOO_LONG = 1743, - RPC_S_PROTSEQ_NOT_FOUND = 1744, - RPC_S_PROCNUM_OUT_OF_RANGE = 1745, - RPC_S_BINDING_HAS_NO_AUTH = 1746, - RPC_S_UNKNOWN_AUTHN_SERVICE = 1747, - RPC_S_UNKNOWN_AUTHN_LEVEL = 1748, - RPC_S_INVALID_AUTH_IDENTITY = 1749, - RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750, - EPT_S_INVALID_ENTRY = 1751, - EPT_S_CANT_PERFORM_OP = 1752, - EPT_S_NOT_REGISTERED = 1753, - RPC_S_NOTHING_TO_EXPORT = 1754, - RPC_S_INCOMPLETE_NAME = 1755, - RPC_S_INVALID_VERS_OPTION = 1756, - RPC_S_NO_MORE_MEMBERS = 1757, - RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758, - RPC_S_INTERFACE_NOT_FOUND = 1759, - RPC_S_ENTRY_ALREADY_EXISTS = 1760, - RPC_S_ENTRY_NOT_FOUND = 1761, - RPC_S_NAME_SERVICE_UNAVAILABLE = 1762, - RPC_S_INVALID_NAF_ID = 1763, - RPC_S_CANNOT_SUPPORT = 1764, - RPC_S_NO_CONTEXT_AVAILABLE = 1765, - RPC_S_INTERNAL_ERROR = 1766, - RPC_S_ZERO_DIVIDE = 1767, - RPC_S_ADDRESS_ERROR = 1768, - RPC_S_FP_DIV_ZERO = 1769, - RPC_S_FP_UNDERFLOW = 1770, - RPC_S_FP_OVERFLOW = 1771, - RPC_X_NO_MORE_ENTRIES = 1772, - RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773, - RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774, - RPC_X_SS_IN_NULL_CONTEXT = 1775, - RPC_X_SS_CONTEXT_DAMAGED = 1777, - RPC_X_SS_HANDLES_MISMATCH = 1778, - RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779, - RPC_X_NULL_REF_POINTER = 1780, - RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781, - RPC_X_BYTE_COUNT_TOO_SMALL = 1782, - RPC_X_BAD_STUB_DATA = 1783, - ERROR_INVALID_USER_BUFFER = 1784, - ERROR_UNRECOGNIZED_MEDIA = 1785, - ERROR_NO_TRUST_LSA_SECRET = 1786, - ERROR_NO_TRUST_SAM_ACCOUNT = 1787, - ERROR_TRUSTED_DOMAIN_FAILURE = 1788, - ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789, - ERROR_TRUST_FAILURE = 1790, - RPC_S_CALL_IN_PROGRESS = 1791, - ERROR_NETLOGON_NOT_STARTED = 1792, - ERROR_ACCOUNT_EXPIRED = 1793, - ERROR_REDIRECTOR_HAS_OPEN_HANDLES = 1794, - ERROR_PRINTER_DRIVER_ALREADY_INSTALLED = 1795, - ERROR_UNKNOWN_PORT = 1796, - ERROR_UNKNOWN_PRINTER_DRIVER = 1797, - ERROR_UNKNOWN_PRINTPROCESSOR = 1798, - ERROR_INVALID_SEPARATOR_FILE = 1799, - ERROR_INVALID_PRIORITY = 1800, - ERROR_INVALID_PRINTER_NAME = 1801, - ERROR_PRINTER_ALREADY_EXISTS = 1802, - ERROR_INVALID_PRINTER_COMMAND = 1803, - ERROR_INVALID_DATATYPE = 1804, - ERROR_INVALID_ENVIRONMENT = 1805, - RPC_S_NO_MORE_BINDINGS = 1806, - ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807, - ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808, - ERROR_NOLOGON_SERVER_TRUST_ACCOUNT = 1809, - ERROR_DOMAIN_TRUST_INCONSISTENT = 1810, - ERROR_SERVER_HAS_OPEN_HANDLES = 1811, - ERROR_RESOURCE_DATA_NOT_FOUND = 1812, - ERROR_RESOURCE_TYPE_NOT_FOUND = 1813, - ERROR_RESOURCE_NAME_NOT_FOUND = 1814, - ERROR_RESOURCE_LANG_NOT_FOUND = 1815, - ERROR_NOT_ENOUGH_QUOTA = 1816, - RPC_S_NO_INTERFACES = 1817, - RPC_S_CALL_CANCELLED = 1818, - RPC_S_BINDING_INCOMPLETE = 1819, - RPC_S_COMM_FAILURE = 1820, - RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821, - RPC_S_NO_PRINC_NAME = 1822, - RPC_S_NOT_RPC_ERROR = 1823, - RPC_S_UUID_LOCAL_ONLY = 1824, - RPC_S_SEC_PKG_ERROR = 1825, - RPC_S_NOT_CANCELLED = 1826, - RPC_X_INVALID_ES_ACTION = 1827, - RPC_X_WRONG_ES_VERSION = 1828, - RPC_X_WRONG_STUB_VERSION = 1829, - RPC_X_INVALID_PIPE_OBJECT = 1830, - RPC_X_WRONG_PIPE_ORDER = 1831, - RPC_X_WRONG_PIPE_VERSION = 1832, - RPC_S_GROUP_MEMBER_NOT_FOUND = 1898, - EPT_S_CANT_CREATE = 1899, - RPC_S_INVALID_OBJECT = 1900, - ERROR_INVALID_TIME = 1901, - ERROR_INVALID_FORM_NAME = 1902, - ERROR_INVALID_FORM_SIZE = 1903, - ERROR_ALREADY_WAITING = 1904, - ERROR_PRINTER_DELETED = 1905, - ERROR_INVALID_PRINTER_STATE = 1906, - ERROR_PASSWORD_MUST_CHANGE = 1907, - ERROR_DOMAIN_CONTROLLER_NOT_FOUND = 1908, - ERROR_ACCOUNT_LOCKED_OUT = 1909, - OR_INVALID_OXID = 1910, - OR_INVALID_OID = 1911, - OR_INVALID_SET = 1912, - RPC_S_SEND_INCOMPLETE = 1913, - RPC_S_INVALID_ASYNC_HANDLE = 1914, - RPC_S_INVALID_ASYNC_CALL = 1915, - RPC_X_PIPE_CLOSED = 1916, - RPC_X_PIPE_DISCIPLINE_ERROR = 1917, - RPC_X_PIPE_EMPTY = 1918, - ERROR_NO_SITENAME = 1919, - ERROR_CANT_ACCESS_FILE = 1920, - ERROR_CANT_RESOLVE_FILENAME = 1921, - RPC_S_ENTRY_TYPE_MISMATCH = 1922, - RPC_S_NOT_ALL_OBJS_EXPORTED = 1923, - RPC_S_INTERFACE_NOT_EXPORTED = 1924, - RPC_S_PROFILE_NOT_ADDED = 1925, - RPC_S_PRF_ELT_NOT_ADDED = 1926, - RPC_S_PRF_ELT_NOT_REMOVED = 1927, - RPC_S_GRP_ELT_NOT_ADDED = 1928, - RPC_S_GRP_ELT_NOT_REMOVED = 1929, - ERROR_KM_DRIVER_BLOCKED = 1930, - ERROR_CONTEXT_EXPIRED = 1931, - ERROR_INVALID_PIXEL_FORMAT = 2000, - ERROR_BAD_DRIVER = 2001, - ERROR_INVALID_WINDOW_STYLE = 2002, - ERROR_METAFILE_NOT_SUPPORTED = 2003, - ERROR_TRANSFORM_NOT_SUPPORTED = 2004, - ERROR_CLIPPING_NOT_SUPPORTED = 2005, - ERROR_INVALID_CMM = 2010, - ERROR_INVALID_PROFILE = 2011, - ERROR_TAG_NOT_FOUND = 2012, - ERROR_TAG_NOT_PRESENT = 2013, - ERROR_DUPLICATE_TAG = 2014, - ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015, - ERROR_PROFILE_NOT_FOUND = 2016, - ERROR_INVALID_COLORSPACE = 2017, - ERROR_ICM_NOT_ENABLED = 2018, - ERROR_DELETING_ICM_XFORM = 2019, - ERROR_INVALID_TRANSFORM = 2020, - ERROR_COLORSPACE_MISMATCH = 2021, - ERROR_INVALID_COLORINDEX = 2022, - ERROR_CONNECTED_OTHER_PASSWORD = 2108, - ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT = 2109, - ERROR_BAD_USERNAME = 2202, - ERROR_NOT_CONNECTED = 2250, - ERROR_OPEN_FILES = 2401, - ERROR_ACTIVE_CONNECTIONS = 2402, - ERROR_DEVICE_IN_USE = 2404, - ERROR_UNKNOWN_PRINT_MONITOR = 3000, - ERROR_PRINTER_DRIVER_IN_USE = 3001, - ERROR_SPOOL_FILE_NOT_FOUND = 3002, - ERROR_SPL_NO_STARTDOC = 3003, - ERROR_SPL_NO_ADDJOB = 3004, - ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED = 3005, - ERROR_PRINT_MONITOR_ALREADY_INSTALLED = 3006, - ERROR_INVALID_PRINT_MONITOR = 3007, - ERROR_PRINT_MONITOR_IN_USE = 3008, - ERROR_PRINTER_HAS_JOBS_QUEUED = 3009, - ERROR_SUCCESS_REBOOT_REQUIRED = 3010, - ERROR_SUCCESS_RESTART_REQUIRED = 3011, - ERROR_PRINTER_NOT_FOUND = 3012, - ERROR_PRINTER_DRIVER_WARNED = 3013, - ERROR_PRINTER_DRIVER_BLOCKED = 3014, - ERROR_WINS_INTERNAL = 4000, - ERROR_CAN_NOT_DEL_LOCAL_WINS = 4001, - ERROR_STATIC_INIT = 4002, - ERROR_INC_BACKUP = 4003, - ERROR_FULL_BACKUP = 4004, - ERROR_REC_NON_EXISTENT = 4005, - ERROR_RPL_NOT_ALLOWED = 4006, - ERROR_DHCP_ADDRESS_CONFLICT = 4100, - ERROR_WMI_GUID_NOT_FOUND = 4200, - ERROR_WMI_INSTANCE_NOT_FOUND = 4201, - ERROR_WMI_ITEMID_NOT_FOUND = 4202, - ERROR_WMI_TRY_AGAIN = 4203, - ERROR_WMI_DP_NOT_FOUND = 4204, - ERROR_WMI_UNRESOLVED_INSTANCE_REF = 4205, - ERROR_WMI_ALREADY_ENABLED = 4206, - ERROR_WMI_GUID_DISCONNECTED = 4207, - ERROR_WMI_SERVER_UNAVAILABLE = 4208, - ERROR_WMI_DP_FAILED = 4209, - ERROR_WMI_INVALID_MOF = 4210, - ERROR_WMI_INVALID_REGINFO = 4211, - ERROR_WMI_ALREADY_DISABLED = 4212, - ERROR_WMI_READ_ONLY = 4213, - ERROR_WMI_SET_FAILURE = 4214, - ERROR_INVALID_MEDIA = 4300, - ERROR_INVALID_LIBRARY = 4301, - ERROR_INVALID_MEDIA_POOL = 4302, - ERROR_DRIVE_MEDIA_MISMATCH = 4303, - ERROR_MEDIA_OFFLINE = 4304, - ERROR_LIBRARY_OFFLINE = 4305, - ERROR_EMPTY = 4306, - ERROR_NOT_EMPTY = 4307, - ERROR_MEDIA_UNAVAILABLE = 4308, - ERROR_RESOURCE_DISABLED = 4309, - ERROR_INVALID_CLEANER = 4310, - ERROR_UNABLE_TO_CLEAN = 4311, - ERROR_OBJECT_NOT_FOUND = 4312, - ERROR_DATABASE_FAILURE = 4313, - ERROR_DATABASE_FULL = 4314, - ERROR_MEDIA_INCOMPATIBLE = 4315, - ERROR_RESOURCE_NOT_PRESENT = 4316, - ERROR_INVALID_OPERATION = 4317, - ERROR_MEDIA_NOT_AVAILABLE = 4318, - ERROR_DEVICE_NOT_AVAILABLE = 4319, - ERROR_REQUEST_REFUSED = 4320, - ERROR_INVALID_DRIVE_OBJECT = 4321, - ERROR_LIBRARY_FULL = 4322, - ERROR_MEDIUM_NOT_ACCESSIBLE = 4323, - ERROR_UNABLE_TO_LOAD_MEDIUM = 4324, - ERROR_UNABLE_TO_INVENTORY_DRIVE = 4325, - ERROR_UNABLE_TO_INVENTORY_SLOT = 4326, - ERROR_UNABLE_TO_INVENTORY_TRANSPORT = 4327, - ERROR_TRANSPORT_FULL = 4328, - ERROR_CONTROLLING_IEPORT = 4329, - ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA = 4330, - ERROR_CLEANER_SLOT_SET = 4331, - ERROR_CLEANER_SLOT_NOT_SET = 4332, - ERROR_CLEANER_CARTRIDGE_SPENT = 4333, - ERROR_UNEXPECTED_OMID = 4334, - ERROR_CANT_DELETE_LAST_ITEM = 4335, - ERROR_MESSAGE_EXCEEDS_MAX_SIZE = 4336, - ERROR_VOLUME_CONTAINS_SYS_FILES = 4337, - ERROR_INDIGENOUS_TYPE = 4338, - ERROR_NO_SUPPORTING_DRIVES = 4339, - ERROR_CLEANER_CARTRIDGE_INSTALLED = 4340, - ERROR_FILE_OFFLINE = 4350, - ERROR_REMOTE_STORAGE_NOT_ACTIVE = 4351, - ERROR_REMOTE_STORAGE_MEDIA_ERROR = 4352, - ERROR_NOT_A_REPARSE_POINT = 4390, - ERROR_REPARSE_ATTRIBUTE_CONFLICT = 4391, - ERROR_INVALID_REPARSE_DATA = 4392, - ERROR_REPARSE_TAG_INVALID = 4393, - ERROR_REPARSE_TAG_MISMATCH = 4394, - ERROR_VOLUME_NOT_SIS_ENABLED = 4500, - ERROR_DEPENDENT_RESOURCE_EXISTS = 5001, - ERROR_DEPENDENCY_NOT_FOUND = 5002, - ERROR_DEPENDENCY_ALREADY_EXISTS = 5003, - ERROR_RESOURCE_NOT_ONLINE = 5004, - ERROR_HOST_NODE_NOT_AVAILABLE = 5005, - ERROR_RESOURCE_NOT_AVAILABLE = 5006, - ERROR_RESOURCE_NOT_FOUND = 5007, - ERROR_SHUTDOWN_CLUSTER = 5008, - ERROR_CANT_EVICT_ACTIVE_NODE = 5009, - ERROR_OBJECT_ALREADY_EXISTS = 5010, - ERROR_OBJECT_IN_LIST = 5011, - ERROR_GROUP_NOT_AVAILABLE = 5012, - ERROR_GROUP_NOT_FOUND = 5013, - ERROR_GROUP_NOT_ONLINE = 5014, - ERROR_HOST_NODE_NOT_RESOURCE_OWNER = 5015, - ERROR_HOST_NODE_NOT_GROUP_OWNER = 5016, - ERROR_RESMON_CREATE_FAILED = 5017, - ERROR_RESMON_ONLINE_FAILED = 5018, - ERROR_RESOURCE_ONLINE = 5019, - ERROR_QUORUM_RESOURCE = 5020, - ERROR_NOT_QUORUM_CAPABLE = 5021, - ERROR_CLUSTER_SHUTTING_DOWN = 5022, - ERROR_INVALID_STATE = 5023, - ERROR_RESOURCE_PROPERTIES_STORED = 5024, - ERROR_NOT_QUORUM_CLASS = 5025, - ERROR_CORE_RESOURCE = 5026, - ERROR_QUORUM_RESOURCE_ONLINE_FAILED = 5027, - ERROR_QUORUMLOG_OPEN_FAILED = 5028, - ERROR_CLUSTERLOG_CORRUPT = 5029, - ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE = 5030, - ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE = 5031, - ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND = 5032, - ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE = 5033, - ERROR_QUORUM_OWNER_ALIVE = 5034, - ERROR_NETWORK_NOT_AVAILABLE = 5035, - ERROR_NODE_NOT_AVAILABLE = 5036, - ERROR_ALL_NODES_NOT_AVAILABLE = 5037, - ERROR_RESOURCE_FAILED = 5038, - ERROR_CLUSTER_INVALID_NODE = 5039, - ERROR_CLUSTER_NODE_EXISTS = 5040, - ERROR_CLUSTER_JOIN_IN_PROGRESS = 5041, - ERROR_CLUSTER_NODE_NOT_FOUND = 5042, - ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND = 5043, - ERROR_CLUSTER_NETWORK_EXISTS = 5044, - ERROR_CLUSTER_NETWORK_NOT_FOUND = 5045, - ERROR_CLUSTER_NETINTERFACE_EXISTS = 5046, - ERROR_CLUSTER_NETINTERFACE_NOT_FOUND = 5047, - ERROR_CLUSTER_INVALID_REQUEST = 5048, - ERROR_CLUSTER_INVALID_NETWORK_PROVIDER = 5049, - ERROR_CLUSTER_NODE_DOWN = 5050, - ERROR_CLUSTER_NODE_UNREACHABLE = 5051, - ERROR_CLUSTER_NODE_NOT_MEMBER = 5052, - ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS = 5053, - ERROR_CLUSTER_INVALID_NETWORK = 5054, - ERROR_CLUSTER_NODE_UP = 5056, - ERROR_CLUSTER_IPADDR_IN_USE = 5057, - ERROR_CLUSTER_NODE_NOT_PAUSED = 5058, - ERROR_CLUSTER_NO_SECURITY_CONTEXT = 5059, - ERROR_CLUSTER_NETWORK_NOT_INTERNAL = 5060, - ERROR_CLUSTER_NODE_ALREADY_UP = 5061, - ERROR_CLUSTER_NODE_ALREADY_DOWN = 5062, - ERROR_CLUSTER_NETWORK_ALREADY_ONLINE = 5063, - ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE = 5064, - ERROR_CLUSTER_NODE_ALREADY_MEMBER = 5065, - ERROR_CLUSTER_LAST_INTERNAL_NETWORK = 5066, - ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS = 5067, - ERROR_INVALID_OPERATION_ON_QUORUM = 5068, - ERROR_DEPENDENCY_NOT_ALLOWED = 5069, - ERROR_CLUSTER_NODE_PAUSED = 5070, - ERROR_NODE_CANT_HOST_RESOURCE = 5071, - ERROR_CLUSTER_NODE_NOT_READY = 5072, - ERROR_CLUSTER_NODE_SHUTTING_DOWN = 5073, - ERROR_CLUSTER_JOIN_ABORTED = 5074, - ERROR_CLUSTER_INCOMPATIBLE_VERSIONS = 5075, - ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED = 5076, - ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED = 5077, - ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND = 5078, - ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED = 5079, - ERROR_CLUSTER_RESNAME_NOT_FOUND = 5080, - ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED = 5081, - ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST = 5082, - ERROR_CLUSTER_DATABASE_SEQMISMATCH = 5083, - ERROR_RESMON_INVALID_STATE = 5084, - ERROR_CLUSTER_GUM_NOT_LOCKER = 5085, - ERROR_QUORUM_DISK_NOT_FOUND = 5086, - ERROR_DATABASE_BACKUP_CORRUPT = 5087, - ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT = 5088, - ERROR_RESOURCE_PROPERTY_UNCHANGEABLE = 5089, - ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE = 5890, - ERROR_CLUSTER_QUORUMLOG_NOT_FOUND = 5891, - ERROR_CLUSTER_MEMBERSHIP_HALT = 5892, - ERROR_CLUSTER_INSTANCE_ID_MISMATCH = 5893, - ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP = 5894, - ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH = 5895, - ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP = 5896, - ERROR_CLUSTER_PARAMETER_MISMATCH = 5897, - ERROR_NODE_CANNOT_BE_CLUSTERED = 5898, - ERROR_CLUSTER_WRONG_OS_VERSION = 5899, - ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME = 5900, - */ - ERROR_ENCRYPTION_FAILED = 6000, - /* - ERROR_DECRYPTION_FAILED = 6001, - ERROR_FILE_ENCRYPTED = 6002, - ERROR_NO_RECOVERY_POLICY = 6003, - ERROR_NO_EFS = 6004, - ERROR_WRONG_EFS = 6005, - ERROR_NO_USER_KEYS = 6006, - ERROR_FILE_NOT_ENCRYPTED = 6007, - ERROR_NOT_EXPORT_FORMAT = 6008, - ERROR_FILE_READ_ONLY = 6009, - ERROR_DIR_EFS_DISALLOWED = 6010, - ERROR_EFS_SERVER_NOT_TRUSTED = 6011, - ERROR_BAD_RECOVERY_POLICY = 6012, - ERROR_EFS_ALG_BLOB_TOO_BIG = 6013, - ERROR_VOLUME_NOT_SUPPORT_EFS = 6014, - ERROR_EFS_DISABLED = 6015, - ERROR_EFS_VERSION_NOT_SUPPORT = 6016, - ERROR_NO_BROWSER_SERVERS_FOUND = 6118, - SCHED_E_SERVICE_NOT_LOCALSYSTEM = 6200, - ERROR_CTX_WINSTATION_NAME_INVALID = 7001, - ERROR_CTX_INVALID_PD = 7002, - ERROR_CTX_PD_NOT_FOUND = 7003, - ERROR_CTX_WD_NOT_FOUND = 7004, - ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY = 7005, - ERROR_CTX_SERVICE_NAME_COLLISION = 7006, - ERROR_CTX_CLOSE_PENDING = 7007, - ERROR_CTX_NO_OUTBUF = 7008, - ERROR_CTX_MODEM_INF_NOT_FOUND = 7009, - ERROR_CTX_INVALID_MODEMNAME = 7010, - ERROR_CTX_MODEM_RESPONSE_ERROR = 7011, - ERROR_CTX_MODEM_RESPONSE_TIMEOUT = 7012, - ERROR_CTX_MODEM_RESPONSE_NO_CARRIER = 7013, - ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE = 7014, - ERROR_CTX_MODEM_RESPONSE_BUSY = 7015, - ERROR_CTX_MODEM_RESPONSE_VOICE = 7016, - ERROR_CTX_TD_ERROR = 7017, - ERROR_CTX_WINSTATION_NOT_FOUND = 7022, - ERROR_CTX_WINSTATION_ALREADY_EXISTS = 7023, - ERROR_CTX_WINSTATION_BUSY = 7024, - ERROR_CTX_BAD_VIDEO_MODE = 7025, - ERROR_CTX_GRAPHICS_INVALID = 7035, - ERROR_CTX_LOGON_DISABLED = 7037, - ERROR_CTX_NOT_CONSOLE = 7038, - ERROR_CTX_CLIENT_QUERY_TIMEOUT = 7040, - ERROR_CTX_CONSOLE_DISCONNECT = 7041, - ERROR_CTX_CONSOLE_CONNECT = 7042, - ERROR_CTX_SHADOW_DENIED = 7044, - ERROR_CTX_WINSTATION_ACCESS_DENIED = 7045, - ERROR_CTX_INVALID_WD = 7049, - ERROR_CTX_SHADOW_INVALID = 7050, - ERROR_CTX_SHADOW_DISABLED = 7051, - ERROR_CTX_CLIENT_LICENSE_IN_USE = 7052, - ERROR_CTX_CLIENT_LICENSE_NOT_SET = 7053, - ERROR_CTX_LICENSE_NOT_AVAILABLE = 7054, - ERROR_CTX_LICENSE_CLIENT_INVALID = 7055, - ERROR_CTX_LICENSE_EXPIRED = 7056, - ERROR_CTX_SHADOW_NOT_RUNNING = 7057, - ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE = 7058, - FRS_ERR_INVALID_API_SEQUENCE = 8001, - FRS_ERR_STARTING_SERVICE = 8002, - FRS_ERR_STOPPING_SERVICE = 8003, - FRS_ERR_INTERNAL_API = 8004, - FRS_ERR_INTERNAL = 8005, - FRS_ERR_SERVICE_COMM = 8006, - FRS_ERR_INSUFFICIENT_PRIV = 8007, - FRS_ERR_AUTHENTICATION = 8008, - FRS_ERR_PARENT_INSUFFICIENT_PRIV = 8009, - FRS_ERR_PARENT_AUTHENTICATION = 8010, - FRS_ERR_CHILD_TO_PARENT_COMM = 8011, - FRS_ERR_PARENT_TO_CHILD_COMM = 8012, - FRS_ERR_SYSVOL_POPULATE = 8013, - FRS_ERR_SYSVOL_POPULATE_TIMEOUT = 8014, - FRS_ERR_SYSVOL_IS_BUSY = 8015, - FRS_ERR_SYSVOL_DEMOTE = 8016, - FRS_ERR_INVALID_SERVICE_PARAMETER = 8017, - ERROR_DS_NOT_INSTALLED = 8200, - ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY = 8201, - ERROR_DS_NO_ATTRIBUTE_OR_VALUE = 8202, - ERROR_DS_INVALID_ATTRIBUTE_SYNTAX = 8203, - ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED = 8204, - ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS = 8205, - ERROR_DS_BUSY = 8206, - ERROR_DS_UNAVAILABLE = 8207, - ERROR_DS_NO_RIDS_ALLOCATED = 8208, - ERROR_DS_NO_MORE_RIDS = 8209, - ERROR_DS_INCORRECT_ROLE_OWNER = 8210, - ERROR_DS_RIDMGR_INIT_ERROR = 8211, - ERROR_DS_OBJ_CLASS_VIOLATION = 8212, - ERROR_DS_CANT_ON_NON_LEAF = 8213, - ERROR_DS_CANT_ON_RDN = 8214, - ERROR_DS_CANT_MOD_OBJ_CLASS = 8215, - ERROR_DS_CROSS_DOM_MOVE_ERROR = 8216, - ERROR_DS_GC_NOT_AVAILABLE = 8217, - ERROR_SHARED_POLICY = 8218, - ERROR_POLICY_OBJECT_NOT_FOUND = 8219, - ERROR_POLICY_ONLY_IN_DS = 8220, - ERROR_PROMOTION_ACTIVE = 8221, - ERROR_NO_PROMOTION_ACTIVE = 8222, - ERROR_DS_OPERATIONS_ERROR = 8224, - ERROR_DS_PROTOCOL_ERROR = 8225, - ERROR_DS_TIMELIMIT_EXCEEDED = 8226, - ERROR_DS_SIZELIMIT_EXCEEDED = 8227, - ERROR_DS_ADMIN_LIMIT_EXCEEDED = 8228, - ERROR_DS_COMPARE_FALSE = 8229, - ERROR_DS_COMPARE_TRUE = 8230, - ERROR_DS_AUTH_METHOD_NOT_SUPPORTED = 8231, - ERROR_DS_STRONG_AUTH_REQUIRED = 8232, - ERROR_DS_INAPPROPRIATE_AUTH = 8233, - ERROR_DS_AUTH_UNKNOWN = 8234, - ERROR_DS_REFERRAL = 8235, - ERROR_DS_UNAVAILABLE_CRIT_EXTENSION = 8236, - ERROR_DS_CONFIDENTIALITY_REQUIRED = 8237, - ERROR_DS_INAPPROPRIATE_MATCHING = 8238, - ERROR_DS_CONSTRAINT_VIOLATION = 8239, - ERROR_DS_NO_SUCH_OBJECT = 8240, - ERROR_DS_ALIAS_PROBLEM = 8241, - ERROR_DS_INVALID_DN_SYNTAX = 8242, - ERROR_DS_IS_LEAF = 8243, - ERROR_DS_ALIAS_DEREF_PROBLEM = 8244, - ERROR_DS_UNWILLING_TO_PERFORM = 8245, - ERROR_DS_LOOP_DETECT = 8246, - ERROR_DS_NAMING_VIOLATION = 8247, - ERROR_DS_OBJECT_RESULTS_TOO_LARGE = 8248, - ERROR_DS_AFFECTS_MULTIPLE_DSAS = 8249, - ERROR_DS_SERVER_DOWN = 8250, - ERROR_DS_LOCAL_ERROR = 8251, - ERROR_DS_ENCODING_ERROR = 8252, - ERROR_DS_DECODING_ERROR = 8253, - ERROR_DS_FILTER_UNKNOWN = 8254, - ERROR_DS_PARAM_ERROR = 8255, - ERROR_DS_NOT_SUPPORTED = 8256, - ERROR_DS_NO_RESULTS_RETURNED = 8257, - ERROR_DS_CONTROL_NOT_FOUND = 8258, - ERROR_DS_CLIENT_LOOP = 8259, - ERROR_DS_REFERRAL_LIMIT_EXCEEDED = 8260, - ERROR_DS_SORT_CONTROL_MISSING = 8261, - ERROR_DS_OFFSET_RANGE_ERROR = 8262, - ERROR_DS_ROOT_MUST_BE_NC = 8301, - ERROR_DS_ADD_REPLICA_INHIBITED = 8302, - ERROR_DS_ATT_NOT_DEF_IN_SCHEMA = 8303, - ERROR_DS_MAX_OBJ_SIZE_EXCEEDED = 8304, - ERROR_DS_OBJ_STRING_NAME_EXISTS = 8305, - ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA = 8306, - ERROR_DS_RDN_DOESNT_MATCH_SCHEMA = 8307, - ERROR_DS_NO_REQUESTED_ATTS_FOUND = 8308, - ERROR_DS_USER_BUFFER_TO_SMALL = 8309, - ERROR_DS_ATT_IS_NOT_ON_OBJ = 8310, - ERROR_DS_ILLEGAL_MOD_OPERATION = 8311, - ERROR_DS_OBJ_TOO_LARGE = 8312, - ERROR_DS_BAD_INSTANCE_TYPE = 8313, - ERROR_DS_MASTERDSA_REQUIRED = 8314, - ERROR_DS_OBJECT_CLASS_REQUIRED = 8315, - ERROR_DS_MISSING_REQUIRED_ATT = 8316, - ERROR_DS_ATT_NOT_DEF_FOR_CLASS = 8317, - ERROR_DS_ATT_ALREADY_EXISTS = 8318, - ERROR_DS_CANT_ADD_ATT_VALUES = 8320, - ERROR_DS_SINGLE_VALUE_CONSTRAINT = 8321, - ERROR_DS_RANGE_CONSTRAINT = 8322, - ERROR_DS_ATT_VAL_ALREADY_EXISTS = 8323, - ERROR_DS_CANT_REM_MISSING_ATT = 8324, - ERROR_DS_CANT_REM_MISSING_ATT_VAL = 8325, - ERROR_DS_ROOT_CANT_BE_SUBREF = 8326, - ERROR_DS_NO_CHAINING = 8327, - ERROR_DS_NO_CHAINED_EVAL = 8328, - ERROR_DS_NO_PARENT_OBJECT = 8329, - ERROR_DS_PARENT_IS_AN_ALIAS = 8330, - ERROR_DS_CANT_MIX_MASTER_AND_REPS = 8331, - ERROR_DS_CHILDREN_EXIST = 8332, - ERROR_DS_OBJ_NOT_FOUND = 8333, - ERROR_DS_ALIASED_OBJ_MISSING = 8334, - ERROR_DS_BAD_NAME_SYNTAX = 8335, - ERROR_DS_ALIAS_POINTS_TO_ALIAS = 8336, - ERROR_DS_CANT_DEREF_ALIAS = 8337, - ERROR_DS_OUT_OF_SCOPE = 8338, - ERROR_DS_OBJECT_BEING_REMOVED = 8339, - ERROR_DS_CANT_DELETE_DSA_OBJ = 8340, - ERROR_DS_GENERIC_ERROR = 8341, - ERROR_DS_DSA_MUST_BE_INT_MASTER = 8342, - ERROR_DS_CLASS_NOT_DSA = 8343, - ERROR_DS_INSUFF_ACCESS_RIGHTS = 8344, - ERROR_DS_ILLEGAL_SUPERIOR = 8345, - ERROR_DS_ATTRIBUTE_OWNED_BY_SAM = 8346, - ERROR_DS_NAME_TOO_MANY_PARTS = 8347, - ERROR_DS_NAME_TOO_LONG = 8348, - ERROR_DS_NAME_VALUE_TOO_LONG = 8349, - ERROR_DS_NAME_UNPARSEABLE = 8350, - ERROR_DS_NAME_TYPE_UNKNOWN = 8351, - ERROR_DS_NOT_AN_OBJECT = 8352, - ERROR_DS_SEC_DESC_TOO_SHORT = 8353, - ERROR_DS_SEC_DESC_INVALID = 8354, - ERROR_DS_NO_DELETED_NAME = 8355, - ERROR_DS_SUBREF_MUST_HAVE_PARENT = 8356, - ERROR_DS_NCNAME_MUST_BE_NC = 8357, - ERROR_DS_CANT_ADD_SYSTEM_ONLY = 8358, - ERROR_DS_CLASS_MUST_BE_CONCRETE = 8359, - ERROR_DS_INVALID_DMD = 8360, - ERROR_DS_OBJ_GUID_EXISTS = 8361, - ERROR_DS_NOT_ON_BACKLINK = 8362, - ERROR_DS_NO_CROSSREF_FOR_NC = 8363, - ERROR_DS_SHUTTING_DOWN = 8364, - ERROR_DS_UNKNOWN_OPERATION = 8365, - ERROR_DS_INVALID_ROLE_OWNER = 8366, - ERROR_DS_COULDNT_CONTACT_FSMO = 8367, - ERROR_DS_CROSS_NC_DN_RENAME = 8368, - ERROR_DS_CANT_MOD_SYSTEM_ONLY = 8369, - ERROR_DS_REPLICATOR_ONLY = 8370, - ERROR_DS_OBJ_CLASS_NOT_DEFINED = 8371, - ERROR_DS_OBJ_CLASS_NOT_SUBCLASS = 8372, - ERROR_DS_NAME_REFERENCE_INVALID = 8373, - ERROR_DS_CROSS_REF_EXISTS = 8374, - ERROR_DS_CANT_DEL_MASTER_CROSSREF = 8375, - ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD = 8376, - ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX = 8377, - ERROR_DS_DUP_RDN = 8378, - ERROR_DS_DUP_OID = 8379, - ERROR_DS_DUP_MAPI_ID = 8380, - ERROR_DS_DUP_SCHEMA_ID_GUID = 8381, - ERROR_DS_DUP_LDAP_DISPLAY_NAME = 8382, - ERROR_DS_SEMANTIC_ATT_TEST = 8383, - ERROR_DS_SYNTAX_MISMATCH = 8384, - ERROR_DS_EXISTS_IN_MUST_HAVE = 8385, - ERROR_DS_EXISTS_IN_MAY_HAVE = 8386, - ERROR_DS_NONEXISTENT_MAY_HAVE = 8387, - ERROR_DS_NONEXISTENT_MUST_HAVE = 8388, - ERROR_DS_AUX_CLS_TEST_FAIL = 8389, - ERROR_DS_NONEXISTENT_POSS_SUP = 8390, - ERROR_DS_SUB_CLS_TEST_FAIL = 8391, - ERROR_DS_BAD_RDN_ATT_ID_SYNTAX = 8392, - ERROR_DS_EXISTS_IN_AUX_CLS = 8393, - ERROR_DS_EXISTS_IN_SUB_CLS = 8394, - ERROR_DS_EXISTS_IN_POSS_SUP = 8395, - ERROR_DS_RECALCSCHEMA_FAILED = 8396, - ERROR_DS_TREE_DELETE_NOT_FINISHED = 8397, - ERROR_DS_CANT_DELETE = 8398, - ERROR_DS_ATT_SCHEMA_REQ_ID = 8399, - ERROR_DS_BAD_ATT_SCHEMA_SYNTAX = 8400, - ERROR_DS_CANT_CACHE_ATT = 8401, - ERROR_DS_CANT_CACHE_CLASS = 8402, - ERROR_DS_CANT_REMOVE_ATT_CACHE = 8403, - ERROR_DS_CANT_REMOVE_CLASS_CACHE = 8404, - ERROR_DS_CANT_RETRIEVE_DN = 8405, - ERROR_DS_MISSING_SUPREF = 8406, - ERROR_DS_CANT_RETRIEVE_INSTANCE = 8407, - ERROR_DS_CODE_INCONSISTENCY = 8408, - ERROR_DS_DATABASE_ERROR = 8409, - ERROR_DS_GOVERNSID_MISSING = 8410, - ERROR_DS_MISSING_EXPECTED_ATT = 8411, - ERROR_DS_NCNAME_MISSING_CR_REF = 8412, - ERROR_DS_SECURITY_CHECKING_ERROR = 8413, - ERROR_DS_SCHEMA_NOT_LOADED = 8414, - ERROR_DS_SCHEMA_ALLOC_FAILED = 8415, - ERROR_DS_ATT_SCHEMA_REQ_SYNTAX = 8416, - ERROR_DS_GCVERIFY_ERROR = 8417, - ERROR_DS_DRA_SCHEMA_MISMATCH = 8418, - ERROR_DS_CANT_FIND_DSA_OBJ = 8419, - ERROR_DS_CANT_FIND_EXPECTED_NC = 8420, - ERROR_DS_CANT_FIND_NC_IN_CACHE = 8421, - ERROR_DS_CANT_RETRIEVE_CHILD = 8422, - ERROR_DS_SECURITY_ILLEGAL_MODIFY = 8423, - ERROR_DS_CANT_REPLACE_HIDDEN_REC = 8424, - ERROR_DS_BAD_HIERARCHY_FILE = 8425, - ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED = 8426, - ERROR_DS_CONFIG_PARAM_MISSING = 8427, - ERROR_DS_COUNTING_AB_INDICES_FAILED = 8428, - ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED = 8429, - ERROR_DS_INTERNAL_FAILURE = 8430, - ERROR_DS_UNKNOWN_ERROR = 8431, - ERROR_DS_ROOT_REQUIRES_CLASS_TOP = 8432, - ERROR_DS_REFUSING_FSMO_ROLES = 8433, - ERROR_DS_MISSING_FSMO_SETTINGS = 8434, - ERROR_DS_UNABLE_TO_SURRENDER_ROLES = 8435, - ERROR_DS_DRA_GENERIC = 8436, - ERROR_DS_DRA_INVALID_PARAMETER = 8437, - ERROR_DS_DRA_BUSY = 8438, - ERROR_DS_DRA_BAD_DN = 8439, - ERROR_DS_DRA_BAD_NC = 8440, - ERROR_DS_DRA_DN_EXISTS = 8441, - ERROR_DS_DRA_INTERNAL_ERROR = 8442, - ERROR_DS_DRA_INCONSISTENT_DIT = 8443, - ERROR_DS_DRA_CONNECTION_FAILED = 8444, - ERROR_DS_DRA_BAD_INSTANCE_TYPE = 8445, - ERROR_DS_DRA_OUT_OF_MEM = 8446, - ERROR_DS_DRA_MAIL_PROBLEM = 8447, - ERROR_DS_DRA_REF_ALREADY_EXISTS = 8448, - ERROR_DS_DRA_REF_NOT_FOUND = 8449, - ERROR_DS_DRA_OBJ_IS_REP_SOURCE = 8450, - ERROR_DS_DRA_DB_ERROR = 8451, - ERROR_DS_DRA_NO_REPLICA = 8452, - ERROR_DS_DRA_ACCESS_DENIED = 8453, - ERROR_DS_DRA_NOT_SUPPORTED = 8454, - ERROR_DS_DRA_RPC_CANCELLED = 8455, - ERROR_DS_DRA_SOURCE_DISABLED = 8456, - ERROR_DS_DRA_SINK_DISABLED = 8457, - ERROR_DS_DRA_NAME_COLLISION = 8458, - ERROR_DS_DRA_SOURCE_REINSTALLED = 8459, - ERROR_DS_DRA_MISSING_PARENT = 8460, - ERROR_DS_DRA_PREEMPTED = 8461, - ERROR_DS_DRA_ABANDON_SYNC = 8462, - ERROR_DS_DRA_SHUTDOWN = 8463, - ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET = 8464, - ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA = 8465, - ERROR_DS_DRA_EXTN_CONNECTION_FAILED = 8466, - ERROR_DS_INSTALL_SCHEMA_MISMATCH = 8467, - ERROR_DS_DUP_LINK_ID = 8468, - ERROR_DS_NAME_ERROR_RESOLVING = 8469, - ERROR_DS_NAME_ERROR_NOT_FOUND = 8470, - ERROR_DS_NAME_ERROR_NOT_UNIQUE = 8471, - ERROR_DS_NAME_ERROR_NO_MAPPING = 8472, - ERROR_DS_NAME_ERROR_DOMAIN_ONLY = 8473, - ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 8474, - ERROR_DS_CONSTRUCTED_ATT_MOD = 8475, - ERROR_DS_WRONG_OM_OBJ_CLASS = 8476, - ERROR_DS_DRA_REPL_PENDING = 8477, - ERROR_DS_DS_REQUIRED = 8478, - ERROR_DS_INVALID_LDAP_DISPLAY_NAME = 8479, - ERROR_DS_NON_BASE_SEARCH = 8480, - ERROR_DS_CANT_RETRIEVE_ATTS = 8481, - ERROR_DS_BACKLINK_WITHOUT_LINK = 8482, - ERROR_DS_EPOCH_MISMATCH = 8483, - ERROR_DS_SRC_NAME_MISMATCH = 8484, - ERROR_DS_SRC_AND_DST_NC_IDENTICAL = 8485, - ERROR_DS_DST_NC_MISMATCH = 8486, - ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC = 8487, - ERROR_DS_SRC_GUID_MISMATCH = 8488, - ERROR_DS_CANT_MOVE_DELETED_OBJECT = 8489, - ERROR_DS_PDC_OPERATION_IN_PROGRESS = 8490, - ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD = 8491, - ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION = 8492, - ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS = 8493, - ERROR_DS_NC_MUST_HAVE_NC_PARENT = 8494, - ERROR_DS_DST_DOMAIN_NOT_NATIVE = 8496, - ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER = 8497, - ERROR_DS_CANT_MOVE_ACCOUNT_GROUP = 8498, - ERROR_DS_CANT_MOVE_RESOURCE_GROUP = 8499, - ERROR_DS_INVALID_SEARCH_FLAG = 8500, - ERROR_DS_NO_TREE_DELETE_ABOVE_NC = 8501, - ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE = 8502, - ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE = 8503, - ERROR_DS_SAM_INIT_FAILURE = 8504, - ERROR_DS_SENSITIVE_GROUP_VIOLATION = 8505, - ERROR_DS_CANT_MOD_PRIMARYGROUPID = 8506, - ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD = 8507, - ERROR_DS_NONSAFE_SCHEMA_CHANGE = 8508, - ERROR_DS_SCHEMA_UPDATE_DISALLOWED = 8509, - ERROR_DS_CANT_CREATE_UNDER_SCHEMA = 8510, - ERROR_DS_INSTALL_NO_SRC_SCH_VERSION = 8511, - ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE = 8512, - ERROR_DS_INVALID_GROUP_TYPE = 8513, - ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN = 8514, - ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN = 8515, - ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER = 8516, - ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER = 8517, - ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER = 8518, - ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER = 8519, - ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER = 8520, - ERROR_DS_HAVE_PRIMARY_MEMBERS = 8521, - ERROR_DS_STRING_SD_CONVERSION_FAILED = 8522, - ERROR_DS_NAMING_MASTER_GC = 8523, - ERROR_DS_LOOKUP_FAILURE = 8524, - ERROR_DS_COULDNT_UPDATE_SPNS = 8525, - ERROR_DS_CANT_RETRIEVE_SD = 8526, - ERROR_DS_KEY_NOT_UNIQUE = 8527, - ERROR_DS_WRONG_LINKED_ATT_SYNTAX = 8528, - ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD = 8529, - ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY = 8530, - ERROR_DS_CANT_START = 8531, - ERROR_DS_INIT_FAILURE = 8532, - ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION = 8533, - ERROR_DS_SOURCE_DOMAIN_IN_FOREST = 8534, - ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST = 8535, - ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED = 8536, - ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN = 8537, - ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER = 8538, - ERROR_DS_SRC_SID_EXISTS_IN_FOREST = 8539, - ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH = 8540, - ERROR_SAM_INIT_FAILURE = 8541, - ERROR_DS_DRA_SCHEMA_INFO_SHIP = 8542, - ERROR_DS_DRA_SCHEMA_CONFLICT = 8543, - ERROR_DS_DRA_EARLIER_SCHEMA_CONLICT = 8544, - ERROR_DS_DRA_OBJ_NC_MISMATCH = 8545, - ERROR_DS_NC_STILL_HAS_DSAS = 8546, - ERROR_DS_GC_REQUIRED = 8547, - ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY = 8548, - ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS = 8549, - ERROR_DS_CANT_ADD_TO_GC = 8550, - ERROR_DS_NO_CHECKPOINT_WITH_PDC = 8551, - ERROR_DS_SOURCE_AUDITING_NOT_ENABLED = 8552, - ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC = 8553, - ERROR_DS_INVALID_NAME_FOR_SPN = 8554, - ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS = 8555, - ERROR_DS_UNICODEPWD_NOT_IN_QUOTES = 8556, - ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED = 8557, - ERROR_DS_MUST_BE_RUN_ON_DST_DC = 8558, - ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER = 8559, - ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ = 8560, - ERROR_DS_INIT_FAILURE_CONSOLE = 8561, - ERROR_DS_SAM_INIT_FAILURE_CONSOLE = 8562, - ERROR_DS_FOREST_VERSION_TOO_HIGH = 8563, - ERROR_DS_DOMAIN_VERSION_TOO_HIGH = 8564, - ERROR_DS_FOREST_VERSION_TOO_LOW = 8565, - ERROR_DS_DOMAIN_VERSION_TOO_LOW = 8566, - ERROR_DS_INCOMPATIBLE_VERSION = 8567, - ERROR_DS_LOW_DSA_VERSION = 8568, - ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN = 8569, - ERROR_DS_NOT_SUPPORTED_SORT_ORDER = 8570, - ERROR_DS_NAME_NOT_UNIQUE = 8571, - ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4 = 8572, - ERROR_DS_OUT_OF_VERSION_STORE = 8573, - ERROR_DS_INCOMPATIBLE_CONTROLS_USED = 8574, - ERROR_DS_NO_REF_DOMAIN = 8575, - ERROR_DS_RESERVED_LINK_ID = 8576, - ERROR_DS_LINK_ID_NOT_AVAILABLE = 8577, - ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER = 8578, - ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE = 8579, - ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC = 8580, - ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG = 8581, - ERROR_DS_MODIFYDN_WRONG_GRANDPARENT = 8582, - ERROR_DS_NAME_ERROR_TRUST_REFERRAL = 8583, - ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER = 8584, - ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD = 8585, - ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE = 8586, - ERROR_DS_THREAD_LIMIT_EXCEEDED = 8587, - ERROR_DS_NOT_CLOSEST = 8588, - ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF = 8589, - ERROR_DS_SINGLE_USER_MODE_FAILED = 8590, - ERROR_DS_NTDSCRIPT_SYNTAX_ERROR = 8591, - ERROR_DS_NTDSCRIPT_PROCESS_ERROR = 8592, - ERROR_DS_DIFFERENT_REPL_EPOCHS = 8593, - ERROR_DS_DRS_EXTENSIONS_CHANGED = 8594, - ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR = 8595, - ERROR_DS_NO_MSDS_INTID = 8596, - ERROR_DS_DUP_MSDS_INTID = 8597, - ERROR_DS_EXISTS_IN_RDNATTID = 8598, - ERROR_DS_AUTHORIZATION_FAILED = 8599, - ERROR_DS_INVALID_SCRIPT = 8600, - ERROR_DS_REMOTE_CROSSREF_OP_FAILED = 8601, - DNS_ERROR_RCODE_FORMAT_ERROR = 9001, - DNS_ERROR_RCODE_SERVER_FAILURE = 9002, - DNS_ERROR_RCODE_NAME_ERROR = 9003, - DNS_ERROR_RCODE_NOT_IMPLEMENTED = 9004, - DNS_ERROR_RCODE_REFUSED = 9005, - DNS_ERROR_RCODE_YXDOMAIN = 9006, - DNS_ERROR_RCODE_YXRRSET = 9007, - DNS_ERROR_RCODE_NXRRSET = 9008, - DNS_ERROR_RCODE_NOTAUTH = 9009, - DNS_ERROR_RCODE_NOTZONE = 9010, - DNS_ERROR_RCODE_BADSIG = 9016, - DNS_ERROR_RCODE_BADKEY = 9017, - DNS_ERROR_RCODE_BADTIME = 9018, - DNS_INFO_NO_RECORDS = 9501, - DNS_ERROR_BAD_PACKET = 9502, - DNS_ERROR_NO_PACKET = 9503, - DNS_ERROR_RCODE = 9504, - DNS_ERROR_UNSECURE_PACKET = 9505, - DNS_ERROR_INVALID_TYPE = 9551, - DNS_ERROR_INVALID_IP_ADDRESS = 9552, - DNS_ERROR_INVALID_PROPERTY = 9553, - DNS_ERROR_TRY_AGAIN_LATER = 9554, - DNS_ERROR_NOT_UNIQUE = 9555, - DNS_ERROR_NON_RFC_NAME = 9556, - DNS_STATUS_FQDN = 9557, - DNS_STATUS_DOTTED_NAME = 9558, - DNS_STATUS_SINGLE_PART_NAME = 9559, - DNS_ERROR_INVALID_NAME_CHAR = 9560, - DNS_ERROR_NUMERIC_NAME = 9561, - DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER = 9562, - DNS_ERROR_ZONE_DOES_NOT_EXIST = 9601, - DNS_ERROR_NO_ZONE_INFO = 9602, - DNS_ERROR_INVALID_ZONE_OPERATION = 9603, - DNS_ERROR_ZONE_CONFIGURATION_ERROR = 9604, - DNS_ERROR_ZONE_HAS_NO_SOA_RECORD = 9605, - DNS_ERROR_ZONE_HAS_NO_NS_RECORDS = 9606, - DNS_ERROR_ZONE_LOCKED = 9607, - DNS_ERROR_ZONE_CREATION_FAILED = 9608, - DNS_ERROR_ZONE_ALREADY_EXISTS = 9609, - DNS_ERROR_AUTOZONE_ALREADY_EXISTS = 9610, - DNS_ERROR_INVALID_ZONE_TYPE = 9611, - DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP = 9612, - DNS_ERROR_ZONE_NOT_SECONDARY = 9613, - DNS_ERROR_NEED_SECONDARY_ADDRESSES = 9614, - DNS_ERROR_WINS_INIT_FAILED = 9615, - DNS_ERROR_NEED_WINS_SERVERS = 9616, - DNS_ERROR_NBSTAT_INIT_FAILED = 9617, - DNS_ERROR_SOA_DELETE_INVALID = 9618, - DNS_ERROR_FORWARDER_ALREADY_EXISTS = 9619, - DNS_ERROR_ZONE_REQUIRES_MASTER_IP = 9620, - DNS_ERROR_ZONE_IS_SHUTDOWN = 9621, - DNS_ERROR_PRIMARY_REQUIRES_DATAFILE = 9651, - DNS_ERROR_INVALID_DATAFILE_NAME = 9652, - DNS_ERROR_DATAFILE_OPEN_FAILURE = 9653, - DNS_ERROR_FILE_WRITEBACK_FAILED = 9654, - DNS_ERROR_DATAFILE_PARSING = 9655, - DNS_ERROR_RECORD_DOES_NOT_EXIST = 9701, - DNS_ERROR_RECORD_FORMAT = 9702, - DNS_ERROR_NODE_CREATION_FAILED = 9703, - DNS_ERROR_UNKNOWN_RECORD_TYPE = 9704, - DNS_ERROR_RECORD_TIMED_OUT = 9705, - DNS_ERROR_NAME_NOT_IN_ZONE = 9706, - DNS_ERROR_CNAME_LOOP = 9707, - DNS_ERROR_NODE_IS_CNAME = 9708, - DNS_ERROR_CNAME_COLLISION = 9709, - DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT = 9710, - DNS_ERROR_RECORD_ALREADY_EXISTS = 9711, - DNS_ERROR_SECONDARY_DATA = 9712, - DNS_ERROR_NO_CREATE_CACHE_DATA = 9713, - DNS_ERROR_NAME_DOES_NOT_EXIST = 9714, - DNS_WARNING_PTR_CREATE_FAILED = 9715, - DNS_WARNING_DOMAIN_UNDELETED = 9716, - DNS_ERROR_DS_UNAVAILABLE = 9717, - DNS_ERROR_DS_ZONE_ALREADY_EXISTS = 9718, - DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE = 9719, - DNS_INFO_AXFR_COMPLETE = 9751, - DNS_ERROR_AXFR = 9752, - DNS_INFO_ADDED_LOCAL_WINS = 9753, - DNS_STATUS_CONTINUE_NEEDED = 9801, - DNS_ERROR_NO_TCPIP = 9851, - DNS_ERROR_NO_DNS_SERVERS = 9852, - DNS_ERROR_DP_DOES_NOT_EXIST = 9901, - DNS_ERROR_DP_ALREADY_EXISTS = 9902, - DNS_ERROR_DP_NOT_ENLISTED = 9903, - DNS_ERROR_DP_ALREADY_ENLISTED = 9904, - WSAEINTR = 10004, - WSAEBADF = 10009, - WSAEACCES = 10013, - WSAEFAULT = 10014, - WSAEINVAL = 10022, - WSAEMFILE = 10024, - WSAEWOULDBLOCK = 10035, - WSAEINPROGRESS = 10036, - WSAEALREADY = 10037, - WSAENOTSOCK = 10038, - WSAEDESTADDRREQ = 10039, - WSAEMSGSIZE = 10040, - WSAEPROTOTYPE = 10041, - WSAENOPROTOOPT = 10042, - WSAEPROTONOSUPPORT = 10043, - WSAESOCKTNOSUPPORT = 10044, - WSAEOPNOTSUPP = 10045, - WSAEPFNOSUPPORT = 10046, - WSAEAFNOSUPPORT = 10047, - WSAEADDRINUSE = 10048, - WSAEADDRNOTAVAIL = 10049, - WSAENETDOWN = 10050, - WSAENETUNREACH = 10051, - WSAENETRESET = 10052, - WSAECONNABORTED = 10053, - WSAECONNRESET = 10054, - WSAENOBUFS = 10055, - WSAEISCONN = 10056, - WSAENOTCONN = 10057, - WSAESHUTDOWN = 10058, - WSAETOOMANYREFS = 10059, - WSAETIMEDOUT = 10060, - WSAECONNREFUSED = 10061, - WSAELOOP = 10062, - WSAENAMETOOLONG = 10063, - WSAEHOSTDOWN = 10064, - WSAEHOSTUNREACH = 10065, - WSAENOTEMPTY = 10066, - WSAEPROCLIM = 10067, - WSAEUSERS = 10068, - WSAEDQUOT = 10069, - WSAESTALE = 10070, - WSAEREMOTE = 10071, - WSASYSNOTREADY = 10091, - WSAVERNOTSUPPORTED = 10092, - WSANOTINITIALISED = 10093, - WSAEDISCON = 10101, - WSAENOMORE = 10102, - WSAECANCELLED = 10103, - WSAEINVALIDPROCTABLE = 10104, - WSAEINVALIDPROVIDER = 10105, - WSAEPROVIDERFAILEDINIT = 10106, - WSASYSCALLFAILURE = 10107, - WSASERVICE_NOT_FOUND = 10108, - WSATYPE_NOT_FOUND = 10109, - WSA_E_NO_MORE = 10110, - WSA_E_CANCELLED = 10111, - WSAEREFUSED = 10112, - WSAHOST_NOT_FOUND = 11001, - WSATRY_AGAIN = 11002, - WSANO_RECOVERY = 11003, - WSANO_DATA = 11004, - WSA_QOS_RECEIVERS = 11005, - WSA_QOS_SENDERS = 11006, - WSA_QOS_NO_SENDERS = 11007, - WSA_QOS_NO_RECEIVERS = 11008, - WSA_QOS_REQUEST_CONFIRMED = 11009, - WSA_QOS_ADMISSION_FAILURE = 11010, - WSA_QOS_POLICY_FAILURE = 11011, - WSA_QOS_BAD_STYLE = 11012, - WSA_QOS_BAD_OBJECT = 11013, - WSA_QOS_TRAFFIC_CTRL_ERROR = 11014, - WSA_QOS_GENERIC_ERROR = 11015, - WSA_QOS_ESERVICETYPE = 11016, - WSA_QOS_EFLOWSPEC = 11017, - WSA_QOS_EPROVSPECBUF = 11018, - WSA_QOS_EFILTERSTYLE = 11019, - WSA_QOS_EFILTERTYPE = 11020, - WSA_QOS_EFILTERCOUNT = 11021, - WSA_QOS_EOBJLENGTH = 11022, - WSA_QOS_EFLOWCOUNT = 11023, - WSA_QOS_EUNKNOWNPSOBJ = 11024, - WSA_QOS_EPOLICYOBJ = 11025, - WSA_QOS_EFLOWDESC = 11026, - WSA_QOS_EPSFLOWSPEC = 11027, - WSA_QOS_EPSFILTERSPEC = 11028, - WSA_QOS_ESDMODEOBJ = 11029, - WSA_QOS_ESHAPERATEOBJ = 11030, - WSA_QOS_RESERVED_PETYPE = 11031, - ERROR_IPSEC_QM_POLICY_EXISTS = 13000, - ERROR_IPSEC_QM_POLICY_NOT_FOUND = 13001, - ERROR_IPSEC_QM_POLICY_IN_USE = 13002, - ERROR_IPSEC_MM_POLICY_EXISTS = 13003, - ERROR_IPSEC_MM_POLICY_NOT_FOUND = 13004, - ERROR_IPSEC_MM_POLICY_IN_USE = 13005, - ERROR_IPSEC_MM_FILTER_EXISTS = 13006, - ERROR_IPSEC_MM_FILTER_NOT_FOUND = 13007, - ERROR_IPSEC_TRANSPORT_FILTER_EXISTS = 13008, - ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND = 13009, - ERROR_IPSEC_MM_AUTH_EXISTS = 13010, - ERROR_IPSEC_MM_AUTH_NOT_FOUND = 13011, - ERROR_IPSEC_MM_AUTH_IN_USE = 13012, - ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND = 13013, - ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND = 13014, - ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND = 13015, - ERROR_IPSEC_TUNNEL_FILTER_EXISTS = 13016, - ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND = 13017, - ERROR_IPSEC_MM_FILTER_PENDING_DELETION = 13018, - ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION = 13019, - ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION = 13020, - ERROR_IPSEC_MM_POLICY_PENDING_DELETION = 13021, - ERROR_IPSEC_MM_AUTH_PENDING_DELETION = 13022, - ERROR_IPSEC_QM_POLICY_PENDING_DELETION = 13023, - ERROR_IPSEC_IKE_AUTH_FAIL = 13801, - ERROR_IPSEC_IKE_ATTRIB_FAIL = 13802, - ERROR_IPSEC_IKE_NEGOTIATION_PENDING = 13803, - ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR = 13804, - ERROR_IPSEC_IKE_TIMED_OUT = 13805, - ERROR_IPSEC_IKE_NO_CERT = 13806, - ERROR_IPSEC_IKE_SA_DELETED = 13807, - ERROR_IPSEC_IKE_SA_REAPED = 13808, - ERROR_IPSEC_IKE_MM_ACQUIRE_DROP = 13809, - ERROR_IPSEC_IKE_QM_ACQUIRE_DROP = 13810, - ERROR_IPSEC_IKE_QUEUE_DROP_MM = 13811, - ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM = 13812, - ERROR_IPSEC_IKE_DROP_NO_RESPONSE = 13813, - ERROR_IPSEC_IKE_MM_DELAY_DROP = 13814, - ERROR_IPSEC_IKE_QM_DELAY_DROP = 13815, - ERROR_IPSEC_IKE_ERROR = 13816, - ERROR_IPSEC_IKE_CRL_FAILED = 13817, - ERROR_IPSEC_IKE_INVALID_KEY_USAGE = 13818, - ERROR_IPSEC_IKE_INVALID_CERT_TYPE = 13819, - ERROR_IPSEC_IKE_NO_PRIVATE_KEY = 13820, - ERROR_IPSEC_IKE_DH_FAIL = 13822, - ERROR_IPSEC_IKE_INVALID_HEADER = 13824, - ERROR_IPSEC_IKE_NO_POLICY = 13825, - ERROR_IPSEC_IKE_INVALID_SIGNATURE = 13826, - ERROR_IPSEC_IKE_KERBEROS_ERROR = 13827, - ERROR_IPSEC_IKE_NO_PUBLIC_KEY = 13828, - ERROR_IPSEC_IKE_PROCESS_ERR = 13829, - ERROR_IPSEC_IKE_PROCESS_ERR_SA = 13830, - ERROR_IPSEC_IKE_PROCESS_ERR_PROP = 13831, - ERROR_IPSEC_IKE_PROCESS_ERR_TRANS = 13832, - ERROR_IPSEC_IKE_PROCESS_ERR_KE = 13833, - ERROR_IPSEC_IKE_PROCESS_ERR_ID = 13834, - ERROR_IPSEC_IKE_PROCESS_ERR_CERT = 13835, - ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ = 13836, - ERROR_IPSEC_IKE_PROCESS_ERR_HASH = 13837, - ERROR_IPSEC_IKE_PROCESS_ERR_SIG = 13838, - ERROR_IPSEC_IKE_PROCESS_ERR_NONCE = 13839, - ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY = 13840, - ERROR_IPSEC_IKE_PROCESS_ERR_DELETE = 13841, - ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR = 13842, - ERROR_IPSEC_IKE_INVALID_PAYLOAD = 13843, - ERROR_IPSEC_IKE_LOAD_SOFT_SA = 13844, - ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN = 13845, - ERROR_IPSEC_IKE_INVALID_COOKIE = 13846, - ERROR_IPSEC_IKE_NO_PEER_CERT = 13847, - ERROR_IPSEC_IKE_PEER_CRL_FAILED = 13848, - ERROR_IPSEC_IKE_POLICY_CHANGE = 13849, - ERROR_IPSEC_IKE_NO_MM_POLICY = 13850, - ERROR_IPSEC_IKE_NOTCBPRIV = 13851, - ERROR_IPSEC_IKE_SECLOADFAIL = 13852, - ERROR_IPSEC_IKE_FAILSSPINIT = 13853, - ERROR_IPSEC_IKE_FAILQUERYSSP = 13854, - ERROR_IPSEC_IKE_SRVACQFAIL = 13855, - ERROR_IPSEC_IKE_SRVQUERYCRED = 13856, - ERROR_IPSEC_IKE_GETSPIFAIL = 13857, - ERROR_IPSEC_IKE_INVALID_FILTER = 13858, - ERROR_IPSEC_IKE_OUT_OF_MEMORY = 13859, - ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED = 13860, - ERROR_IPSEC_IKE_INVALID_POLICY = 13861, - ERROR_IPSEC_IKE_UNKNOWN_DOI = 13862, - ERROR_IPSEC_IKE_INVALID_SITUATION = 13863, - ERROR_IPSEC_IKE_DH_FAILURE = 13864, - ERROR_IPSEC_IKE_INVALID_GROUP = 13865, - ERROR_IPSEC_IKE_ENCRYPT = 13866, - ERROR_IPSEC_IKE_DECRYPT = 13867, - ERROR_IPSEC_IKE_POLICY_MATCH = 13868, - ERROR_IPSEC_IKE_UNSUPPORTED_ID = 13869, - ERROR_IPSEC_IKE_INVALID_HASH = 13870, - ERROR_IPSEC_IKE_INVALID_HASH_ALG = 13871, - ERROR_IPSEC_IKE_INVALID_HASH_SIZE = 13872, - ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG = 13873, - ERROR_IPSEC_IKE_INVALID_AUTH_ALG = 13874, - ERROR_IPSEC_IKE_INVALID_SIG = 13875, - ERROR_IPSEC_IKE_LOAD_FAILED = 13876, - ERROR_IPSEC_IKE_RPC_DELETE = 13877, - ERROR_IPSEC_IKE_BENIGN_REINIT = 13878, - ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY = 13879, - ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN = 13881, - ERROR_IPSEC_IKE_MM_LIMIT = 13882, - ERROR_IPSEC_IKE_NEGOTIATION_DISABLED = 13883, - ERROR_IPSEC_IKE_NEG_STATUS_END = 13884, - ERROR_SXS_SECTION_NOT_FOUND = 14000, - ERROR_SXS_CANT_GEN_ACTCTX = 14001, - ERROR_SXS_INVALID_ACTCTXDATA_FORMAT = 14002, - ERROR_SXS_ASSEMBLY_NOT_FOUND = 14003, - ERROR_SXS_MANIFEST_FORMAT_ERROR = 14004, - ERROR_SXS_MANIFEST_PARSE_ERROR = 14005, - ERROR_SXS_ACTIVATION_CONTEXT_DISABLED = 14006, - ERROR_SXS_KEY_NOT_FOUND = 14007, - ERROR_SXS_VERSION_CONFLICT = 14008, - ERROR_SXS_WRONG_SECTION_TYPE = 14009, - ERROR_SXS_THREAD_QUERIES_DISABLED = 14010, - ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET = 14011, - ERROR_SXS_UNKNOWN_ENCODING_GROUP = 14012, - ERROR_SXS_UNKNOWN_ENCODING = 14013, - ERROR_SXS_INVALID_XML_NAMESPACE_URI = 14014, - ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED = 14015, - ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED = 14016, - ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE = 14017, - ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE = 14018, - ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE = 14019, - ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT = 14020, - ERROR_SXS_DUPLICATE_DLL_NAME = 14021, - ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME = 14022, - ERROR_SXS_DUPLICATE_CLSID = 14023, - ERROR_SXS_DUPLICATE_IID = 14024, - ERROR_SXS_DUPLICATE_TLBID = 14025, - ERROR_SXS_DUPLICATE_PROGID = 14026, - ERROR_SXS_DUPLICATE_ASSEMBLY_NAME = 14027, - ERROR_SXS_FILE_HASH_MISMATCH = 14028, - ERROR_SXS_POLICY_PARSE_ERROR = 14029, - ERROR_SXS_XML_E_MISSINGQUOTE = 14030, - ERROR_SXS_XML_E_COMMENTSYNTAX = 14031, - ERROR_SXS_XML_E_BADSTARTNAMECHAR = 14032, - ERROR_SXS_XML_E_BADNAMECHAR = 14033, - ERROR_SXS_XML_E_BADCHARINSTRING = 14034, - ERROR_SXS_XML_E_XMLDECLSYNTAX = 14035, - ERROR_SXS_XML_E_BADCHARDATA = 14036, - ERROR_SXS_XML_E_MISSINGWHITESPACE = 14037, - ERROR_SXS_XML_E_EXPECTINGTAGEND = 14038, - ERROR_SXS_XML_E_MISSINGSEMICOLON = 14039, - ERROR_SXS_XML_E_UNBALANCEDPAREN = 14040, - ERROR_SXS_XML_E_INTERNALERROR = 14041, - ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE = 14042, - ERROR_SXS_XML_E_INCOMPLETE_ENCODING = 14043, - ERROR_SXS_XML_E_MISSING_PAREN = 14044, - ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE = 14045, - ERROR_SXS_XML_E_MULTIPLE_COLONS = 14046, - ERROR_SXS_XML_E_INVALID_DECIMAL = 14047, - ERROR_SXS_XML_E_INVALID_HEXIDECIMAL = 14048, - ERROR_SXS_XML_E_INVALID_UNICODE = 14049, - ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK = 14050, - ERROR_SXS_XML_E_UNEXPECTEDENDTAG = 14051, - ERROR_SXS_XML_E_UNCLOSEDTAG = 14052, - ERROR_SXS_XML_E_DUPLICATEATTRIBUTE = 14053, - ERROR_SXS_XML_E_MULTIPLEROOTS = 14054, - ERROR_SXS_XML_E_INVALIDATROOTLEVEL = 14055, - ERROR_SXS_XML_E_BADXMLDECL = 14056, - ERROR_SXS_XML_E_MISSINGROOT = 14057, - ERROR_SXS_XML_E_UNEXPECTEDEOF = 14058, - ERROR_SXS_XML_E_BADPEREFINSUBSET = 14059, - ERROR_SXS_XML_E_UNCLOSEDSTARTTAG = 14060, - ERROR_SXS_XML_E_UNCLOSEDENDTAG = 14061, - ERROR_SXS_XML_E_UNCLOSEDSTRING = 14062, - ERROR_SXS_XML_E_UNCLOSEDCOMMENT = 14063, - ERROR_SXS_XML_E_UNCLOSEDDECL = 14064, - ERROR_SXS_XML_E_UNCLOSEDCDATA = 14065, - ERROR_SXS_XML_E_RESERVEDNAMESPACE = 14066, - ERROR_SXS_XML_E_INVALIDENCODING = 14067, - ERROR_SXS_XML_E_INVALIDSWITCH = 14068, - ERROR_SXS_XML_E_BADXMLCASE = 14069, - ERROR_SXS_XML_E_INVALID_STANDALONE = 14070, - ERROR_SXS_XML_E_UNEXPECTED_STANDALONE = 14071, - ERROR_SXS_XML_E_INVALID_VERSION = 14072, - ERROR_SXS_XML_E_MISSINGEQUALS = 14073, - ERROR_SXS_PROTECTION_RECOVERY_FAILED = 14074, - ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT = 14075, - ERROR_SXS_PROTECTION_CATALOG_NOT_VALID = 14076, - ERROR_SXS_UNTRANSLATABLE_HRESULT = 14077, - ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING = 14078, - ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE = 14079, - ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME = 14080 */ - } -} diff --git a/netcore/System.Private.CoreLib/src/System/IO/Stream.Mono.cs b/netcore/System.Private.CoreLib/src/System/IO/Stream.Mono.cs deleted file mode 100644 index 3e0c4e47a02..00000000000 --- a/netcore/System.Private.CoreLib/src/System/IO/Stream.Mono.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System.IO -{ - partial class Stream - { - [MethodImpl (MethodImplOptions.InternalCall)] - extern bool HasOverriddenBeginEndRead (); - - [MethodImpl (MethodImplOptions.InternalCall)] - extern bool HasOverriddenBeginEndWrite (); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Math.Mono.cs b/netcore/System.Private.CoreLib/src/System/Math.Mono.cs deleted file mode 100644 index 6f6fe9eb724..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Math.Mono.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System -{ - partial class Math - { - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Abs (double value); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Abs (float value); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Acos (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Acosh (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Asin (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Asinh (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Atan (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Atan2 (double y, double x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Atanh (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Cbrt (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Ceiling (double a); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Cos (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Cosh (double value); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Exp (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Floor (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Log (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Log10 (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Pow (double x, double y); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Sin (double a); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Sinh (double value); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Sqrt (double d); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Tan (double a); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Tanh (double value); - - [Intrinsic] - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double FusedMultiplyAdd (double x, double y, double z); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern int ILogB (double x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double Log2 (double x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern double ScaleB (double x, int n); - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern double FMod(double x, double y); - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern unsafe double ModF(double x, double* intptr); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/MathF.Mono.cs b/netcore/System.Private.CoreLib/src/System/MathF.Mono.cs deleted file mode 100644 index 16d04343814..00000000000 --- a/netcore/System.Private.CoreLib/src/System/MathF.Mono.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System -{ - partial class MathF - { - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Acos (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Acosh (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Asin (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Asinh (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Atan (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Atan2 (float y, float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Atanh (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Cbrt (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Ceiling (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Cos (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Cosh (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Exp (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Floor (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Log (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Log10 (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Pow (float x, float y); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Sin (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Sinh (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Sqrt (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Tan (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Tanh (float x); - - [Intrinsic] - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float FusedMultiplyAdd (float x, float y, float z); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern int ILogB (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float Log2 (float x); - - [MethodImpl (MethodImplOptions.InternalCall)] - public static extern float ScaleB (float x, int n); - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern float FMod (float x, float y); - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern unsafe float ModF (float x, float* intptr); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/MissingMemberException.Mono.cs b/netcore/System.Private.CoreLib/src/System/MissingMemberException.Mono.cs deleted file mode 100644 index a346eea450b..00000000000 --- a/netcore/System.Private.CoreLib/src/System/MissingMemberException.Mono.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System -{ - partial class MissingMemberException - { - internal static string FormatSignature (byte[] signature) - { - return ""; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/ModuleHandle.cs b/netcore/System.Private.CoreLib/src/System/ModuleHandle.cs deleted file mode 100644 index ce0e6a1e4dd..00000000000 --- a/netcore/System.Private.CoreLib/src/System/ModuleHandle.cs +++ /dev/null @@ -1,142 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace System -{ - public struct ModuleHandle - { - readonly IntPtr value; - - public static readonly ModuleHandle EmptyHandle = new ModuleHandle (IntPtr.Zero); - - internal ModuleHandle (IntPtr v) - { - value = v; - } - - internal IntPtr Value { - get { - return value; - } - } - - public int MDStreamVersion { - get { - if (value == IntPtr.Zero) - throw new ArgumentNullException (String.Empty, "Invalid handle"); - return RuntimeModule.GetMDStreamVersion (value); - } - } - - public RuntimeFieldHandle ResolveFieldHandle (int fieldToken) - { - return ResolveFieldHandle (fieldToken, null, null); - } - - public RuntimeMethodHandle ResolveMethodHandle (int methodToken) - { - return ResolveMethodHandle (methodToken, null, null); - } - - public RuntimeTypeHandle ResolveTypeHandle (int typeToken) - { - return ResolveTypeHandle (typeToken, null, null); - } - - static IntPtr[]? ptrs_from_handles (RuntimeTypeHandle[]? handles) - { - if (handles == null) - return null; - - var res = new IntPtr [handles.Length]; - for (int i = 0; i < handles.Length; ++i) - res [i] = handles [i].Value; - return res; - } - - public RuntimeTypeHandle ResolveTypeHandle (int typeToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) - { - ResolveTokenError error; - if (value == IntPtr.Zero) - throw new ArgumentNullException (String.Empty, "Invalid handle"); - IntPtr res = RuntimeModule.ResolveTypeToken (value, typeToken, ptrs_from_handles (typeInstantiationContext), ptrs_from_handles (methodInstantiationContext), out error); - if (res == IntPtr.Zero) - throw new TypeLoadException (String.Format ("Could not load type '0x{0:x}' from assembly '0x{1:x}'", typeToken, value.ToInt64 ())); - else - return new RuntimeTypeHandle (res); - } - - public RuntimeMethodHandle ResolveMethodHandle (int methodToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) - { - ResolveTokenError error; - if (value == IntPtr.Zero) - throw new ArgumentNullException (String.Empty, "Invalid handle"); - IntPtr res = RuntimeModule.ResolveMethodToken (value, methodToken, ptrs_from_handles (typeInstantiationContext), ptrs_from_handles (methodInstantiationContext), out error); - if (res == IntPtr.Zero) - throw new Exception (String.Format ("Could not load method '0x{0:x}' from assembly '0x{1:x}'", methodToken, value.ToInt64 ())); - else - return new RuntimeMethodHandle (res); - } - - public RuntimeFieldHandle ResolveFieldHandle (int fieldToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) - { - ResolveTokenError error; - if (value == IntPtr.Zero) - throw new ArgumentNullException (String.Empty, "Invalid handle"); - - IntPtr res = RuntimeModule.ResolveFieldToken (value, fieldToken, ptrs_from_handles (typeInstantiationContext), ptrs_from_handles (methodInstantiationContext), out error); - if (res == IntPtr.Zero) - throw new Exception (String.Format ("Could not load field '0x{0:x}' from assembly '0x{1:x}'", fieldToken, value.ToInt64 ())); - else - return new RuntimeFieldHandle (res); - } - - public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken (int fieldToken) - { - return ResolveFieldHandle (fieldToken); - } - - public RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken (int methodToken) - { - return ResolveMethodHandle (methodToken); - } - - public RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken (int typeToken) - { - return ResolveTypeHandle (typeToken); - } - - public override bool Equals (object? obj) - { - if (obj == null || GetType () != obj.GetType ()) - return false; - - return value == ((ModuleHandle)obj).Value; - } - - public bool Equals (ModuleHandle handle) - { - return value == handle.Value; - } - - public override int GetHashCode () - { - return value.GetHashCode (); - } - - public static bool operator == (ModuleHandle left, ModuleHandle right) - { - return Equals (left, right); - } - - public static bool operator != (ModuleHandle left, ModuleHandle right) - { - return !Equals (left, right); - } - } -} - diff --git a/netcore/System.Private.CoreLib/src/System/MulticastDelegate.cs b/netcore/System.Private.CoreLib/src/System/MulticastDelegate.cs deleted file mode 100644 index 5205ef060e2..00000000000 --- a/netcore/System.Private.CoreLib/src/System/MulticastDelegate.cs +++ /dev/null @@ -1,262 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.Serialization; -using System.Runtime.InteropServices; - -namespace System -{ - [StructLayout (LayoutKind.Sequential)] - public abstract class MulticastDelegate : Delegate - { - Delegate[]? delegates; - - protected MulticastDelegate (object target, string method) - : base (target, method) - { - } - - protected MulticastDelegate (Type target, string method) - : base (target, method) - { - } - - public override void GetObjectData (SerializationInfo info, StreamingContext context) - { - throw new SerializationException (SR.Serialization_DelegatesNotSupported); - } - - protected sealed override object? DynamicInvokeImpl (object?[]? args) - { - if (delegates == null) { - return base.DynamicInvokeImpl (args); - } else { - object r; - int i = 0, len = delegates.Length; - do { - r = delegates [i].DynamicInvoke (args); - } while (++i < len); - return r; - } - } - - // Some high-performance applications use this internal property - // to avoid using a slow path to determine if there is more than one handler - // This brings an API that we removed in f410e545e2db0e0dc338673a6b10a5cfd2d3340f - // which some users depeneded on - // - // This is an example of code that used this: - // https://gist.github.com/migueldeicaza/cd99938c2a4372e7e5d5 - // - // Do not remove this API - internal bool HasSingleTarget { - get { return delegates == null; } - } - - // <remarks> - // Equals: two multicast delegates are equal if their base is equal - // and their invocations list is equal. - // </remarks> - public sealed override bool Equals (object? obj) - { - if (!base.Equals (obj)) - return false; - - if (!(obj is MulticastDelegate d)) - return false; - - if (delegates == null && d.delegates == null) { - return true; - } else if (delegates == null ^ d.delegates == null) { - return false; - } else { - if (delegates.Length != d.delegates.Length) - return false; - - for (int i = 0; i < delegates.Length; ++i) { - if (!delegates [i].Equals (d.delegates [i])) - return false; - } - - return true; - } - } - - // - // FIXME: This could use some improvements. - // - public sealed override int GetHashCode () - { - return base.GetHashCode (); - } - - protected override MethodInfo GetMethodImpl () - { - if (delegates != null) - return delegates [delegates.Length - 1].Method; - - return base.GetMethodImpl (); - } - - // <summary> - // Return, in order of invocation, the invocation list - // of a MulticastDelegate - // </summary> - public sealed override Delegate[] GetInvocationList () - { - if (delegates != null) - return (Delegate[]) delegates.Clone (); - else - return new Delegate[1] { this }; - } - - // <summary> - // Combines this MulticastDelegate with the (Multicast)Delegate `follow'. - // This does _not_ combine with Delegates. ECMA states the whole delegate - // thing should have better been a simple System.Delegate class. - // Compiler generated delegates are always MulticastDelegates. - // </summary> - protected sealed override Delegate CombineImpl (Delegate? follow) - { - if (follow == null) - return this; - - MulticastDelegate other = (MulticastDelegate) follow; - - MulticastDelegate ret = AllocDelegateLike_internal (this); - - if (delegates == null && other.delegates == null) { - ret.delegates = new Delegate [2] { this, other }; - } else if (delegates == null) { - ret.delegates = new Delegate [1 + other.delegates.Length]; - - ret.delegates [0] = this; - Array.Copy (other.delegates, 0, ret.delegates, 1, other.delegates.Length); - } else if (other.delegates == null) { - ret.delegates = new Delegate [delegates.Length + 1]; - - Array.Copy (delegates, 0, ret.delegates, 0, delegates.Length); - ret.delegates [ret.delegates.Length - 1] = other; - } else { - ret.delegates = new Delegate [delegates.Length + other.delegates.Length]; - - Array.Copy (delegates, 0, ret.delegates, 0, delegates.Length); - Array.Copy (other.delegates, 0, ret.delegates, delegates.Length, other.delegates.Length); - } - - return ret; - } - - /* Based on the Boyer–Moore string search algorithm */ - int LastIndexOf (Delegate[] haystack, Delegate[] needle) - { - if (haystack.Length < needle.Length) - return -1; - - if (haystack.Length == needle.Length) { - for (int i = 0; i < haystack.Length; ++i) - if (!haystack [i].Equals (needle [i])) - return -1; - - return 0; - } - - for (int i = haystack.Length - needle.Length, j; i >= 0;) { - for (j = 0; needle [j].Equals (haystack [i]); ++i, ++j) { - if (j == needle.Length - 1) - return i - j; - } - - i -= j + 1; - } - - return -1; - } - - protected sealed override Delegate RemoveImpl (Delegate value) - { - if (value == null) - return this; - - MulticastDelegate other = (MulticastDelegate) value; - - if (delegates == null && other.delegates == null) { - /* if they are not equal and the current one is not - * a multicastdelegate then we cannot delete it */ - return this.Equals (other) ? null : this; - } else if (delegates == null) { - foreach (var d in other.delegates) { - if (this.Equals (d)) - return null; - } - return this; - } else if (other.delegates == null) { - int idx = Array.LastIndexOf (delegates, other); - if (idx == -1) - return this; - - if (delegates.Length <= 1) { - /* delegates.Length should never be equal or - * lower than 1, it should be 2 or greater */ - throw new InvalidOperationException (); - } - - if (delegates.Length == 2) - return delegates [idx == 0 ? 1 : 0]; - - MulticastDelegate ret = AllocDelegateLike_internal (this); - ret.delegates = new Delegate [delegates.Length - 1]; - - Array.Copy (delegates, ret.delegates, idx); - Array.Copy (delegates, idx + 1, ret.delegates, idx, delegates.Length - idx - 1); - - return ret; - } else { - /* wild case : remove MulticastDelegate from MulticastDelegate - * complexity is O(m + n), with n the number of elements in - * this.delegates and m the number of elements in other.delegates */ - - if (delegates.Equals (other.delegates)) - return null; - - /* we need to remove elements from the end to the beginning, as - * the addition and removal of delegates behaves like a stack */ - int idx = LastIndexOf (delegates, other.delegates); - if (idx == -1) - return this; - - MulticastDelegate ret = AllocDelegateLike_internal (this); - ret.delegates = new Delegate [delegates.Length - other.delegates.Length]; - - Array.Copy (delegates, ret.delegates, idx); - Array.Copy (delegates, idx + other.delegates.Length, ret.delegates, idx, delegates.Length - idx - other.delegates.Length); - - return ret; - } - } - - public static bool operator == (MulticastDelegate d1, MulticastDelegate d2) - { - if (d1 == null) - return d2 == null; - - return d1.Equals (d2); - } - - public static bool operator != (MulticastDelegate d1, MulticastDelegate d2) - { - if (d1 == null) - return d2 != null; - - return !d1.Equals (d2); - } - - internal override object GetTarget() - { - return delegates?.Length > 0 ? delegates [delegates.Length - 1].GetTarget () : base.GetTarget (); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/NotImplemented.cs b/netcore/System.Private.CoreLib/src/System/NotImplemented.cs deleted file mode 100644 index 5a2690e97f6..00000000000 --- a/netcore/System.Private.CoreLib/src/System/NotImplemented.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System -{ - // - // This simple class enables one to throw a NotImplementedException using the following - // idiom: - // - // throw NotImplemented.ByDesign; - // - // Used by methods whose intended implementation is to throw a NotImplementedException (typically - // virtual methods in public abstract classes that intended to be subclassed by third parties.) - // - // This makes it distinguishable both from human eyes and CCI from NYI's that truly represent undone work. - // - internal static class NotImplemented - { - internal static Exception ByDesign - { - get - { - return new NotImplementedException(); - } - } - } -} - diff --git a/netcore/System.Private.CoreLib/src/System/Nullable.Mono.cs b/netcore/System.Private.CoreLib/src/System/Nullable.Mono.cs deleted file mode 100644 index 8958c0fab8b..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Nullable.Mono.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System -{ - partial struct Nullable<T> - { - // - // These are called by the JIT - // - - // - // JIT implementation of box valuetype System.Nullable`1<T> - // - static object? Box (T? o) - { - if (!o.hasValue) - return null; - - return o.value; - } - - static T? Unbox (object o) - { - if (o == null) - return null; - return (T) o; - } - - static T? UnboxExact (object o) - { - if (o == null) - return null; - if (o.GetType() != typeof (T)) - throw new InvalidCastException(); - - return (T) o; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Object.Mono.cs b/netcore/System.Private.CoreLib/src/System/Object.Mono.cs deleted file mode 100644 index a34de194d20..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Object.Mono.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System -{ - partial class Object - { - [Intrinsic] - public Type GetType () => GetType (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - protected extern object MemberwiseClone (); - - [Intrinsic] - internal ref byte GetRawData () => ref GetRawData (); - - internal object CloneInternal () => MemberwiseClone (); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs deleted file mode 100644 index a8ac7339b9c..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Loader; -using System.Threading; - -namespace System.Reflection -{ - [StructLayout (LayoutKind.Sequential)] - partial class Assembly - { - internal bool IsRuntimeImplemented () => this is RuntimeAssembly; - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Assembly? LoadWithPartialName (string partialName) - { - if (partialName == null) - throw new ArgumentNullException (nameof (partialName)); - - if (partialName.Length == 0 || partialName [0] == '\0') - throw new ArgumentException (SR.Format_StringZeroLength, nameof (partialName)); - - try { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeAssembly.InternalLoad (partialName, ref stackMark, IntPtr.Zero); - } catch (FileNotFoundException) { - return null; - } - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Assembly GetExecutingAssembly() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return GetExecutingAssembly(ref stackMark); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern RuntimeAssembly GetExecutingAssembly (ref StackCrawlMark stackMark); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public static extern Assembly GetCallingAssembly (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern Assembly GetEntryAssemblyNative (); - - private static Assembly? GetEntryAssemblyInternal () - { - return GetEntryAssemblyNative (); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Assembly Load (string assemblyString) - { - if (assemblyString == null) - throw new ArgumentNullException (nameof (assemblyString)); - - var name = new AssemblyName (assemblyString); - // TODO: trigger assemblyFromResolveEvent - - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return Load (name, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Assembly Load (AssemblyName assemblyRef) - { - if (assemblyRef == null) - throw new ArgumentNullException (nameof (assemblyRef)); - - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return Load (assemblyRef, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); - } - - internal static Assembly Load (AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext) - { - // TODO: pass AssemblyName - var assembly = InternalLoad (assemblyRef.FullName, ref stackMark, assemblyLoadContext != null ? assemblyLoadContext.NativeALC : IntPtr.Zero); - if (assembly == null) - throw new FileNotFoundException (null, assemblyRef.Name); - return assembly; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern Assembly InternalLoad (string assemblyName, ref StackCrawlMark stackMark, IntPtr ptrLoadContextBinder); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern Type InternalGetType (Module module, string name, bool throwOnError, bool ignoreCase); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static void InternalGetAssemblyName (string assemblyFile, out Mono.MonoAssemblyName aname, out string codebase); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/AssemblyName.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/AssemblyName.Mono.cs deleted file mode 100644 index 5d93f5c7262..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/AssemblyName.Mono.cs +++ /dev/null @@ -1,135 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Mono; -using System.Configuration.Assemblies; -using System.Globalization; -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection -{ - [StructLayout (LayoutKind.Sequential)] - partial class AssemblyName - { - public AssemblyName (string assemblyName) - { - if (assemblyName == null) - throw new ArgumentNullException (nameof (assemblyName)); - if (assemblyName.Length == 0 || assemblyName [0] == '\0') - throw new ArgumentException (SR.Format_StringZeroLength); - - using (var name = RuntimeMarshal.MarshalString (assemblyName)) { - // TODO: Should use CoreRT AssemblyNameParser - if (!ParseAssemblyName (name.Value, out var nativeName, out var isVersionDefined, out var isTokenDefined)) - throw new FileLoadException ("The assembly name is invalid."); - - try { - unsafe { - FillName (&nativeName, null, isVersionDefined, false, isTokenDefined); - } - } finally { - RuntimeMarshal.FreeAssemblyName (ref nativeName, false); - } - } - } - - unsafe byte [] ComputePublicKeyToken () - { - if (_publicKey == null) - return null; - if (_publicKey.Length == 0) - return Array.Empty<byte>(); - - var token = new byte [8]; - fixed (byte* pkt = token) - fixed (byte *pk = _publicKey) - get_public_token (pkt, pk, _publicKey.Length); - return token; - } - - internal static AssemblyName Create (IntPtr monoAssembly, string codeBase) - { - AssemblyName aname = new AssemblyName (); - unsafe { - MonoAssemblyName *native = GetNativeName (monoAssembly); - aname.FillName (native, codeBase, true, true, true); - } - return aname; - } - - internal unsafe void FillName (MonoAssemblyName *native, string codeBase, bool addVersion, bool addPublickey, bool defaultToken) - { - _name = RuntimeMarshal.PtrToUtf8String (native->name); - - _flags = (AssemblyNameFlags) native->flags; - - _hashAlgorithm = (AssemblyHashAlgorithm) native->hash_alg; - - _versionCompatibility = AssemblyVersionCompatibility.SameMachine; - - if (addVersion) { - var build = native->build == 65535 ? -1 : native->build; - var revision = native->revision == 65535 ? -1 : native->revision; - - if (build == -1) - _version = new Version (native->major, native->minor); - else if (revision == -1) - _version = new Version (native->major, native->minor, build); - else - _version = new Version (native->major, native->minor, build, revision); - } - - _codeBase = codeBase; - - if (native->culture != IntPtr.Zero) - _cultureInfo = CultureInfo.GetCultureInfo (RuntimeMarshal.PtrToUtf8String (native->culture)); - - if (native->public_key != IntPtr.Zero) { - _publicKey = RuntimeMarshal.DecodeBlobArray (native->public_key); - _flags |= AssemblyNameFlags.PublicKey; - } else if (addPublickey) { - _publicKey = Array.Empty<byte> (); - _flags |= AssemblyNameFlags.PublicKey; - } - - // MonoAssemblyName keeps the public key token as an hexadecimal string - if (native->public_key_token [0] != 0) { - var keyToken = new byte [8]; - for (int i = 0, j = 0; i < 8; ++i) { - keyToken [i] = (byte) (RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]) << 4); - keyToken [i] |= (byte) RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]); - } - _publicKeyToken = keyToken; - } else if (defaultToken) { - _publicKeyToken = Array.Empty<byte> (); - } - } - - static AssemblyName GetFileInformationCore (string assemblyFile) - { - unsafe { - Assembly.InternalGetAssemblyName (Path.GetFullPath (assemblyFile), out var nativeName, out var codebase); - - var aname = new AssemblyName (); - try { - aname.FillName (&nativeName, codebase, true, false, true); - return aname; - } finally { - RuntimeMarshal.FreeAssemblyName (ref nativeName, false); - } - } - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern unsafe void get_public_token (byte* token, byte* pubkey, int len); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern unsafe MonoAssemblyName* GetNativeName (IntPtr assemblyPtr); - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern bool ParseAssemblyName (IntPtr name, out MonoAssemblyName aname, out bool is_version_definited, out bool is_token_defined); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs b/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs deleted file mode 100644 index 03880d38c87..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs +++ /dev/null @@ -1,720 +0,0 @@ -// -// (c) 2002,2003 Ximian, Inc. (http://www.ximian.com) -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// Copyright (C) 2013 Xamarin, Inc (http://www.xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using System.Reflection; -using System.Collections; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -using System.Collections.Generic; - -namespace System.Reflection -{ - static class CustomAttribute - { - static Assembly corlib; - [ThreadStatic] - static Dictionary<Type, AttributeUsageAttribute> usage_cache; - - /* Treat as user types all corlib types extending System.Type that are not RuntimeType and TypeBuilder */ - static bool IsUserCattrProvider (object obj) - { - Type type = obj as Type; - if ((type is RuntimeType) || (RuntimeFeature.IsDynamicCodeSupported && type?.IsTypeBuilder () == true)) - return false; - if ((obj is Type)) - return true; - if (corlib == null) - corlib = typeof (int).Assembly; - return obj.GetType ().Assembly != corlib; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern Attribute[] GetCustomAttributesInternal (ICustomAttributeProvider obj, Type attributeType, bool pseudoAttrs); - - internal static object[] GetPseudoCustomAttributes (ICustomAttributeProvider obj, Type attributeType) { - object[] pseudoAttrs = null; - /* FIXME: Add other types */ - if (obj is RuntimeMethodInfo monoMethod) - pseudoAttrs = monoMethod.GetPseudoCustomAttributes (); - else if (obj is RuntimeFieldInfo fieldInfo) - pseudoAttrs = fieldInfo.GetPseudoCustomAttributes (); - else if (obj is RuntimeParameterInfo monoParamInfo) - pseudoAttrs = monoParamInfo.GetPseudoCustomAttributes (); - else if (obj is Type t) - pseudoAttrs = GetPseudoCustomAttributes (t); - - if ((attributeType != null) && (pseudoAttrs != null)) { - for (int i = 0; i < pseudoAttrs.Length; ++i) - if (attributeType.IsAssignableFrom (pseudoAttrs [i].GetType ())) - if (pseudoAttrs.Length == 1) - return pseudoAttrs; - else - return new object [] { pseudoAttrs [i] }; - return Array.Empty<object> (); - } - - return pseudoAttrs; - } - - static object[] GetPseudoCustomAttributes (Type type) - { - int count = 0; - var Attributes = type.Attributes; - - /* IsSerializable returns true for delegates/enums as well */ - if ((Attributes & TypeAttributes.Serializable) != 0) - count ++; - if ((Attributes & TypeAttributes.Import) != 0) - count ++; - - if (count == 0) - return null; - object[] attrs = new object [count]; - count = 0; - - if ((Attributes & TypeAttributes.Serializable) != 0) - attrs [count ++] = new SerializableAttribute (); - if ((Attributes & TypeAttributes.Import) != 0) - attrs [count ++] = new ComImportAttribute (); - - return attrs; - } - - internal static object[] GetCustomAttributesBase (ICustomAttributeProvider obj, Type attributeType, bool inheritedOnly) - { - object[] attrs; - - if (IsUserCattrProvider (obj)) - attrs = obj.GetCustomAttributes (attributeType, true); - else - attrs = GetCustomAttributesInternal (obj, attributeType, false); - - // - // All pseudo custom attributes are Inherited = false hence we can avoid - // building attributes array which would be discarded by inherited checks - // - if (!inheritedOnly) { - object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType); - if (pseudoAttrs != null) { - object[] res = new Attribute [attrs.Length + pseudoAttrs.Length]; - System.Array.Copy (attrs, res, attrs.Length); - System.Array.Copy (pseudoAttrs, 0, res, attrs.Length, pseudoAttrs.Length); - return res; - } - } - - return attrs; - } - - internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, Type attributeType, bool inherit) - { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - if (attributeType == null) - throw new ArgumentNullException (nameof (attributeType)); - if (!attributeType.IsSubclassOf (typeof (Attribute)) && attributeType != typeof (Attribute)&& attributeType != typeof (CustomAttribute) && attributeType != typeof (System.Object)) - throw new ArgumentException (SR.Argument_MustHaveAttributeBaseClass + " " + attributeType.FullName); - - if (attributeType == typeof (CustomAttribute)) - attributeType = null; - if (attributeType == typeof (Attribute)) - attributeType = null; - if (attributeType == typeof (System.Object)) - attributeType = null; - - object[] r; - object[] res = GetCustomAttributesBase (obj, attributeType, false); - // shortcut - if (!inherit && res.Length == 1) { - if (res [0] == null) - throw new CustomAttributeFormatException ("Invalid custom attribute format"); - - if (attributeType != null) { - if (attributeType.IsAssignableFrom (res[0].GetType ())) { - r = (object[]) Array.CreateInstance (attributeType, 1); - r[0] = res[0]; - } else { - r = (object[]) Array.CreateInstance (attributeType, 0); - } - } else { - r = (object[]) Array.CreateInstance (res[0].GetType (), 1); - r[0] = res[0]; - } - return r; - } - - if (inherit && GetBase (obj) == null) - inherit = false; - - // if AttributeType is sealed, and Inherited is set to false, then - // there's no use in scanning base types - if ((attributeType != null && attributeType.IsSealed) && inherit) { - AttributeUsageAttribute usageAttribute = RetrieveAttributeUsage ( - attributeType); - if (!usageAttribute.Inherited) - inherit = false; - } - - var initialSize = Math.Max (res.Length, 16); - List<Object> a = null; - ICustomAttributeProvider btype = obj; - object[] array; - - /* Non-inherit case */ - if (!inherit) { - if (attributeType == null) { - foreach (object attr in res) { - if (attr == null) - throw new CustomAttributeFormatException ("Invalid custom attribute format"); - } - var result = new Attribute [res.Length]; - res.CopyTo (result, 0); - return result; - } - - a = new List<object> (initialSize); - foreach (object attr in res) { - if (attr == null) - throw new CustomAttributeFormatException ("Invalid custom attribute format"); - - Type attrType = attr.GetType (); - if (attributeType != null && !attributeType.IsAssignableFrom (attrType)) - continue; - a.Add (attr); - } - - if (attributeType == null || attributeType.IsValueType) - array = new Attribute [a.Count]; - else - array = Array.CreateInstance (attributeType, a.Count) as object[]; - a.CopyTo (array, 0); - return array; - } - - /* Inherit case */ - var attributeInfos = new Dictionary<Type, AttributeInfo> (initialSize); - int inheritanceLevel = 0; - a = new List<object> (initialSize); - - do { - foreach (object attr in res) { - AttributeUsageAttribute usage; - if (attr == null) - throw new CustomAttributeFormatException ("Invalid custom attribute format"); - - Type attrType = attr.GetType (); - if (attributeType != null) { - if (!attributeType.IsAssignableFrom (attrType)) - continue; - } - - AttributeInfo firstAttribute; - if (attributeInfos.TryGetValue (attrType, out firstAttribute)) - usage = firstAttribute.Usage; - else - usage = RetrieveAttributeUsage (attrType); - - // only add attribute to the list of attributes if - // - we are on the first inheritance level, or the attribute can be inherited anyway - // and ( - // - multiple attributes of the type are allowed - // or ( - // - this is the first attribute we've discovered - // or - // - the attribute is on same inheritance level than the first - // attribute that was discovered for this attribute type )) - if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple || - (firstAttribute == null || (firstAttribute != null - && firstAttribute.InheritanceLevel == inheritanceLevel)))) - a.Add (attr); - - if (firstAttribute == null) - attributeInfos.Add (attrType, new AttributeInfo (usage, inheritanceLevel)); - } - - if ((btype = GetBase (btype)) != null) { - inheritanceLevel++; - res = GetCustomAttributesBase (btype, attributeType, true); - } - } while (inherit && btype != null); - - if (attributeType == null || attributeType.IsValueType) - array = new Attribute [a.Count]; - else - array = Array.CreateInstance (attributeType, a.Count) as object[]; - - // copy attributes to array - a.CopyTo (array, 0); - - return array; - } - - internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, bool inherit) - { - if (obj == null) - throw new ArgumentNullException ("obj"); - - if (!inherit) - return (object[]) GetCustomAttributesBase (obj, null, false).Clone (); - - return GetCustomAttributes (obj, typeof (CustomAttribute), inherit); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - [PreserveDependency(".ctor(System.Reflection.ConstructorInfo,System.Reflection.Assembly,System.IntPtr,System.UInt32)", "System.Reflection.CustomAttributeData")] - [PreserveDependency(".ctor(System.Reflection.MemberInfo,System.Object)", "System.Reflection.CustomAttributeNamedArgument")] - [PreserveDependency(".ctor(System.Type,System.Object)", "System.Reflection.CustomAttributeTypedArgument")] - static extern CustomAttributeData [] GetCustomAttributesDataInternal (ICustomAttributeProvider obj); - - internal static IList<CustomAttributeData> GetCustomAttributesData (ICustomAttributeProvider obj, bool inherit = false) - { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - - if (!inherit) - return GetCustomAttributesDataBase (obj, null, false); - - return GetCustomAttributesData (obj, typeof (CustomAttribute), inherit); - } - - internal static IList<CustomAttributeData> GetCustomAttributesData (ICustomAttributeProvider obj, Type attributeType, bool inherit) - { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - if (attributeType == null) - throw new ArgumentNullException (nameof (attributeType)); - - if (attributeType == typeof (CustomAttribute)) - attributeType = null; - - const string Message = "Invalid custom attribute data format"; - IList<CustomAttributeData> r; - IList<CustomAttributeData> res = GetCustomAttributesDataBase (obj, attributeType, false); - // shortcut - if (!inherit && res.Count == 1) { - if (res [0] == null) - throw new CustomAttributeFormatException (Message); - if (attributeType != null) { - if (attributeType.IsAssignableFrom (res [0].AttributeType)) - r = new CustomAttributeData[] { res [0] }; - else - r = Array.Empty<CustomAttributeData> (); - } else { - r = new CustomAttributeData[] { res [0] }; - } - - return r; - } - - if (inherit && GetBase (obj) == null) - inherit = false; - - // if AttributeType is sealed, and Inherited is set to false, then - // there's no use in scanning base types - if ((attributeType != null && attributeType.IsSealed) && inherit) { - var usageAttribute = RetrieveAttributeUsage (attributeType); - if (!usageAttribute.Inherited) - inherit = false; - } - - var initialSize = Math.Max (res.Count, 16); - List<CustomAttributeData> a = null; - ICustomAttributeProvider btype = obj; - - /* Non-inherit case */ - if (!inherit) { - if (attributeType == null) { - foreach (CustomAttributeData attrData in res) { - if (attrData == null) - throw new CustomAttributeFormatException (Message); - } - - var result = new CustomAttributeData [res.Count]; - res.CopyTo (result, 0); - return result; - } else { - a = new List<CustomAttributeData> (initialSize); - foreach (CustomAttributeData attrData in res) { - if (attrData == null) - throw new CustomAttributeFormatException (Message); - if (!attributeType.IsAssignableFrom (attrData.AttributeType)) - continue; - a.Add (attrData); - } - - return a.ToArray (); - } - } - - /* Inherit case */ - var attributeInfos = new Dictionary<Type, AttributeInfo> (initialSize); - int inheritanceLevel = 0; - a = new List<CustomAttributeData> (initialSize); - - do { - foreach (CustomAttributeData attrData in res) { - AttributeUsageAttribute usage; - if (attrData == null) - throw new CustomAttributeFormatException (Message); - - Type attrType = attrData.AttributeType; - if (attributeType != null) { - if (!attributeType.IsAssignableFrom (attrType)) - continue; - } - - AttributeInfo firstAttribute; - if (attributeInfos.TryGetValue (attrType, out firstAttribute)) - usage = firstAttribute.Usage; - else - usage = RetrieveAttributeUsage (attrType); - - // The same as for CustomAttributes. - // - // Only add attribute to the list of attributes if - // - we are on the first inheritance level, or the attribute can be inherited anyway - // and ( - // - multiple attributes of the type are allowed - // or ( - // - this is the first attribute we've discovered - // or - // - the attribute is on same inheritance level than the first - // attribute that was discovered for this attribute type )) - if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple || - (firstAttribute == null || (firstAttribute != null - && firstAttribute.InheritanceLevel == inheritanceLevel)))) - a.Add(attrData); - - if (firstAttribute == null) - attributeInfos.Add (attrType, new AttributeInfo (usage, inheritanceLevel)); - } - - if ((btype = GetBase (btype)) != null) { - inheritanceLevel++; - res = GetCustomAttributesDataBase (btype, attributeType, true); - } - } while (inherit && btype != null); - - return a.ToArray (); - } - - internal static IList<CustomAttributeData> GetCustomAttributesDataBase (ICustomAttributeProvider obj, Type attributeType, bool inheritedOnly) - { - CustomAttributeData[] attrsData; - if (IsUserCattrProvider (obj)) { - //FIXME resolve this case if it makes sense. Assign empty array for now. - //attrsData = obj.GetCustomAttributesData(attributeType, true); - attrsData = Array.Empty<CustomAttributeData> (); - } else - attrsData = GetCustomAttributesDataInternal (obj); - - // - // All pseudo custom attributes are Inherited = false hence we can avoid - // building attributes data array which would be discarded by inherited checks - // - if (!inheritedOnly) { - CustomAttributeData[] pseudoAttrsData = GetPseudoCustomAttributesData (obj, attributeType); - if (pseudoAttrsData != null) { - if (attrsData.Length == 0) - return Array.AsReadOnly (pseudoAttrsData); - CustomAttributeData[] res = new CustomAttributeData [attrsData.Length + pseudoAttrsData.Length]; - Array.Copy (attrsData, res, attrsData.Length); - Array.Copy (pseudoAttrsData, 0, res, attrsData.Length, pseudoAttrsData.Length); - return Array.AsReadOnly (res); - } - } - - return Array.AsReadOnly (attrsData); - } - - internal static CustomAttributeData[] GetPseudoCustomAttributesData (ICustomAttributeProvider obj, Type attributeType) - { - CustomAttributeData[] pseudoAttrsData = null; - - /* FIXME: Add other types */ - if (obj is RuntimeMethodInfo monoMethod) - pseudoAttrsData = monoMethod.GetPseudoCustomAttributesData (); - else if (obj is RuntimeFieldInfo fieldInfo) - pseudoAttrsData = fieldInfo.GetPseudoCustomAttributesData (); - else if (obj is RuntimeParameterInfo monoParamInfo) - pseudoAttrsData = monoParamInfo.GetPseudoCustomAttributesData (); - else if (obj is Type t) - pseudoAttrsData = GetPseudoCustomAttributesData (t); - - if ((attributeType != null) && (pseudoAttrsData != null)) { - for (int i = 0; i < pseudoAttrsData.Length; ++i) { - if (attributeType.IsAssignableFrom (pseudoAttrsData [i].AttributeType)) { - if (pseudoAttrsData.Length == 1) - return pseudoAttrsData; - else - return new CustomAttributeData[] { pseudoAttrsData[i] }; - } - } - - return Array.Empty<CustomAttributeData> (); - } - - return pseudoAttrsData; - } - - static CustomAttributeData[] GetPseudoCustomAttributesData (Type type) - { - int count = 0; - var Attributes = type.Attributes; - - /* IsSerializable returns true for delegates/enums as well */ - if ((Attributes & TypeAttributes.Serializable) != 0) - count++; - if ((Attributes & TypeAttributes.Import) != 0) - count++; - - if (count == 0) - return null; - CustomAttributeData[] attrsData = new CustomAttributeData [count]; - count = 0; - - if ((Attributes & TypeAttributes.Serializable) != 0) - attrsData [count++] = new CustomAttributeData ((typeof (SerializableAttribute)).GetConstructor (Type.EmptyTypes)); - if ((Attributes & TypeAttributes.Import) != 0) - attrsData [count++] = new CustomAttributeData ((typeof (ComImportAttribute)).GetConstructor (Type.EmptyTypes)); - - return attrsData; - } - - internal static bool IsDefined (ICustomAttributeProvider obj, Type attributeType, bool inherit) - { - if (attributeType == null) - throw new ArgumentNullException (nameof (attributeType)); - if (!attributeType.IsSubclassOf (typeof (Attribute)) && attributeType != typeof (Attribute)) - throw new ArgumentException (SR.Argument_MustHaveAttributeBaseClass + " " + attributeType.FullName); - - AttributeUsageAttribute usage = null; - do { - if (IsUserCattrProvider (obj)) - return obj.IsDefined (attributeType, inherit); - - if (IsDefinedInternal (obj, attributeType)) - return true; - - object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType); - if (pseudoAttrs != null) { - for (int i = 0; i < pseudoAttrs.Length; ++i) - if (attributeType.IsAssignableFrom (pseudoAttrs[i].GetType ())) - return true; - } - - if (usage == null) { - if (!inherit) - return false; - - usage = RetrieveAttributeUsage (attributeType); - if (!usage.Inherited) - return false; - } - - obj = GetBase (obj); - } while (obj != null); - - return false; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern bool IsDefinedInternal (ICustomAttributeProvider obj, Type AttributeType); - - static PropertyInfo GetBasePropertyDefinition (RuntimePropertyInfo property) - { - MethodInfo method = property.GetGetMethod (true); - if (method == null || !method.IsVirtual) - method = property.GetSetMethod (true); - if (method == null || !method.IsVirtual) - return null; - - MethodInfo baseMethod = ((RuntimeMethodInfo)method).GetBaseMethod (); - if (baseMethod != null && baseMethod != method) { - ParameterInfo[] parameters = property.GetIndexParameters (); - if (parameters != null && parameters.Length > 0) { - Type[] paramTypes = new Type[parameters.Length]; - for (int i=0; i < paramTypes.Length; i++) - paramTypes[i] = parameters[i].ParameterType; - return baseMethod.DeclaringType.GetProperty (property.Name, property.PropertyType, - paramTypes); - } else { - return baseMethod.DeclaringType.GetProperty (property.Name, property.PropertyType); - } - } - return null; - - } - - static EventInfo GetBaseEventDefinition (RuntimeEventInfo evt) - { - MethodInfo method = evt.GetAddMethod (true); - if (method == null || !method.IsVirtual) - method = evt.GetRaiseMethod (true); - if (method == null || !method.IsVirtual) - method = evt.GetRemoveMethod (true); - if (method == null || !method.IsVirtual) - return null; - - MethodInfo baseMethod = ((RuntimeMethodInfo)method).GetBaseMethod (); - if (baseMethod != null && baseMethod != method) { - BindingFlags flags = method.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic; - flags |= method.IsStatic ? BindingFlags.Static : BindingFlags.Instance; - - return baseMethod.DeclaringType.GetEvent (evt.Name, flags); - } - return null; - } - - // Handles Type, RuntimePropertyInfo and RuntimeMethodInfo. - // The runtime has also cases for RuntimeEventInfo, RuntimeFieldInfo, Assembly and ParameterInfo, - // but for those we return null here. - static ICustomAttributeProvider GetBase (ICustomAttributeProvider obj) - { - if (obj == null) - return null; - - if (obj is Type) - return ((Type) obj).BaseType; - - MethodInfo method = null; - if (obj is RuntimePropertyInfo) - return GetBasePropertyDefinition ((RuntimePropertyInfo) obj); - else if (obj is RuntimeEventInfo) - return GetBaseEventDefinition ((RuntimeEventInfo)obj); - else if (obj is RuntimeMethodInfo) - method = (MethodInfo) obj; - if (obj is RuntimeParameterInfo parinfo) { - var member = parinfo.Member; - if (member is MethodInfo) { - method = (MethodInfo)member; - MethodInfo bmethod = ((RuntimeMethodInfo)method).GetBaseMethod (); - if (bmethod == method) - return null; - return bmethod.GetParameters ()[parinfo.Position]; - } - } - /* - * ParameterInfo -> null - * Assembly -> null - * RuntimeEventInfo -> null - * RuntimeFieldInfo -> null - */ - if (method == null || !method.IsVirtual) - return null; - - MethodInfo baseMethod = ((RuntimeMethodInfo)method).GetBaseMethod (); - if (baseMethod == method) - return null; - - return baseMethod; - } - - private static AttributeUsageAttribute RetrieveAttributeUsageNoCache (Type attributeType) - { - if (attributeType == typeof (AttributeUsageAttribute)) - /* Avoid endless recursion */ - return new AttributeUsageAttribute (AttributeTargets.Class); - - AttributeUsageAttribute usageAttribute = null; - object[] attribs = GetCustomAttributes (attributeType, typeof(AttributeUsageAttribute), false); - if (attribs.Length == 0) - { - // if no AttributeUsage was defined on the attribute level, then - // try to retrieve if from its base type - if (attributeType.BaseType != null) - { - usageAttribute = RetrieveAttributeUsage (attributeType.BaseType); - - } - if (usageAttribute != null) - { - // return AttributeUsage of base class - return usageAttribute; - - } - // return default AttributeUsageAttribute if no AttributeUsage - // was defined on attribute, or its base class - return DefaultAttributeUsage; - } - // check if more than one AttributeUsageAttribute has been specified - // on the type - // NOTE: compilers should prevent this, but that doesn't prevent - // anyone from using IL ofcourse - if (attribs.Length > 1) - { - throw new FormatException ("Duplicate AttributeUsageAttribute cannot be specified on an attribute type."); - } - - return ((AttributeUsageAttribute) attribs[0]); - } - - static AttributeUsageAttribute RetrieveAttributeUsage (Type attributeType) - { - AttributeUsageAttribute usageAttribute = null; - /* Usage a thread-local cache to speed this up, since it is called a lot from GetCustomAttributes () */ - if (usage_cache == null) - usage_cache = new Dictionary<Type, AttributeUsageAttribute> (); - if (usage_cache.TryGetValue (attributeType, out usageAttribute)) - return usageAttribute; - usageAttribute = RetrieveAttributeUsageNoCache (attributeType); - usage_cache [attributeType] = usageAttribute; - return usageAttribute; - } - - private static readonly AttributeUsageAttribute DefaultAttributeUsage = - new AttributeUsageAttribute (AttributeTargets.All); - - private class AttributeInfo - { - private AttributeUsageAttribute _usage; - private int _inheritanceLevel; - - public AttributeInfo (AttributeUsageAttribute usage, int inheritanceLevel) - { - _usage = usage; - _inheritanceLevel = inheritanceLevel; - } - - public AttributeUsageAttribute Usage - { - get - { - return _usage; - } - } - - public int InheritanceLevel - { - get - { - return _inheritanceLevel; - } - } - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs b/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs deleted file mode 100644 index 979a5215091..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs +++ /dev/null @@ -1,187 +0,0 @@ -// -// Author: -// Zoltan Varga (vargaz@gmail.com) -// Carlos Alberto Cortez (calberto.cortez@gmail.com) -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; - -namespace System.Reflection -{ - public class CustomAttributeData - { - class LazyCAttrData { - internal Assembly assembly; - internal IntPtr data; - internal uint data_length; - } - - ConstructorInfo ctorInfo; - IList<CustomAttributeTypedArgument> ctorArgs; - IList<CustomAttributeNamedArgument> namedArgs; - LazyCAttrData lazyData; - - protected CustomAttributeData () - { - } - - // custom-attrs.c:create_custom_attr_data () - internal CustomAttributeData (ConstructorInfo ctorInfo, Assembly assembly, IntPtr data, uint data_length) - { - this.ctorInfo = ctorInfo; - this.lazyData = new LazyCAttrData (); - this.lazyData.assembly = assembly; - this.lazyData.data = data; - this.lazyData.data_length = data_length; - } - - internal CustomAttributeData (ConstructorInfo ctorInfo) - : this (ctorInfo, Array.Empty<CustomAttributeTypedArgument> (), Array.Empty<CustomAttributeNamedArgument> ()) - { - } - - internal CustomAttributeData (ConstructorInfo ctorInfo, IList<CustomAttributeTypedArgument> ctorArgs, IList<CustomAttributeNamedArgument> namedArgs) - { - this.ctorInfo = ctorInfo; - this.ctorArgs = ctorArgs; - this.namedArgs = namedArgs; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern void ResolveArgumentsInternal (ConstructorInfo ctor, Assembly assembly, IntPtr data, uint data_length, out object[] ctorArgs, out object[] namedArgs); - - void ResolveArguments () - { - object[] ctor_args, named_args; - if (lazyData == null) - return; - - ResolveArgumentsInternal (ctorInfo, lazyData.assembly, lazyData.data, lazyData.data_length, out ctor_args, out named_args); - - this.ctorArgs = Array.AsReadOnly<CustomAttributeTypedArgument> - (ctor_args != null ? UnboxValues<CustomAttributeTypedArgument> (ctor_args) : Array.Empty<CustomAttributeTypedArgument>()); - this.namedArgs = Array.AsReadOnly<CustomAttributeNamedArgument> - (named_args != null ? UnboxValues<CustomAttributeNamedArgument> (named_args) : Array.Empty<CustomAttributeNamedArgument>()); - - lazyData = null; - } - - public - virtual - ConstructorInfo Constructor { - get { - return ctorInfo; - } - } - - public - virtual - IList<CustomAttributeTypedArgument> ConstructorArguments { - get { - ResolveArguments (); - return ctorArgs; - } - } - - public - virtual - IList<CustomAttributeNamedArgument> NamedArguments { - get { - ResolveArguments (); - return namedArgs; - } - } - - public static IList<CustomAttributeData> GetCustomAttributes (Assembly target) { - return CustomAttribute.GetCustomAttributesData (target); - } - - public static IList<CustomAttributeData> GetCustomAttributes (MemberInfo target) { - return CustomAttribute.GetCustomAttributesData (target); - } - - internal static IList<CustomAttributeData> GetCustomAttributesInternal (RuntimeType target) { - return CustomAttribute.GetCustomAttributesData (target); - } - - public static IList<CustomAttributeData> GetCustomAttributes (Module target) { - return CustomAttribute.GetCustomAttributesData (target); - } - - public static IList<CustomAttributeData> GetCustomAttributes (ParameterInfo target) { - return CustomAttribute.GetCustomAttributesData (target); - } - - virtual public Type AttributeType { - get { return ctorInfo.DeclaringType; } - } - - public override string ToString () - { - ResolveArguments (); - - StringBuilder sb = new StringBuilder (); - - sb.Append ("[" + ctorInfo.DeclaringType.FullName + "("); - for (int i = 0; i < ctorArgs.Count; i++) { - sb.Append (ctorArgs [i].ToString ()); - if (i + 1 < ctorArgs.Count) - sb.Append (", "); - } - - if (namedArgs.Count > 0) - sb.Append (", "); - - for (int j = 0; j < namedArgs.Count; j++) { - sb.Append (namedArgs [j].ToString ()); - if (j + 1 < namedArgs.Count) - sb.Append (", "); - } - sb.AppendFormat (")]"); - - return sb.ToString (); - } - - static T [] UnboxValues<T> (object [] values) - { - T [] retval = new T [values.Length]; - for (int i = 0; i < values.Length; i++) - retval [i] = (T) values [i]; - - return retval; - } - - public override int GetHashCode () => base.GetHashCode (); - - public override bool Equals (object? obj) - { - return obj == (object)this; - } - } - -} - diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.Mono.cs deleted file mode 100644 index 27b08f8372a..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.Mono.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Reflection -{ - partial struct CustomAttributeTypedArgument - { - static object CanonicalizeValue (object value) - { - if (value.GetType ().IsEnum) - return ((Enum) value).GetValue (); - - return value; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs deleted file mode 100644 index f15997d5823..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs +++ /dev/null @@ -1,591 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit/AssemblyBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.IO; -using System.Runtime.Serialization; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Collections; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Security; -using System.Security.Cryptography; -using System.Threading; - -namespace System.Reflection.Emit -{ - internal class GenericInstanceKey { - Type gtd; - internal Type[] args; - int hash_code; - - internal GenericInstanceKey (Type gtd, Type[] args) - { - this.gtd = gtd; - this.args = args; - - hash_code = gtd.GetHashCode (); - for (int i = 0; i < args.Length; ++i) - hash_code ^= args [i].GetHashCode (); - } - - static bool IsBoundedVector (Type type) { - ArrayType at = type as ArrayType; - if (at != null) - return at.GetEffectiveRank () == 1; - return type.ToString ().EndsWith ("[*]", StringComparison.Ordinal); /*Super uggly hack, SR doesn't allow one to query for it */ - } - - static bool TypeEquals (Type a, Type b) { - if (a == b) - return true; - - if (a.HasElementType) { - if (!b.HasElementType) - return false; - if (!TypeEquals (a.GetElementType (), b.GetElementType ())) - return false; - if (a.IsArray) { - if (!b.IsArray) - return false; - int rank = a.GetArrayRank (); - if (rank != b.GetArrayRank ()) - return false; - if (rank == 1 && IsBoundedVector (a) != IsBoundedVector (b)) - return false; - } else if (a.IsByRef) { - if (!b.IsByRef) - return false; - } else if (a.IsPointer) { - if (!b.IsPointer) - return false; - } - return true; - } - - if (a.IsGenericType) { - if (!b.IsGenericType) - return false; - if (a.IsGenericParameter) - return a == b; - if (a.IsGenericParameter) //previous test should have caught it - return false; - - if (a.IsGenericTypeDefinition) { - if (!b.IsGenericTypeDefinition) - return false; - } else { - if (b.IsGenericTypeDefinition) - return false; - if (!TypeEquals (a.GetGenericTypeDefinition (), b.GetGenericTypeDefinition ())) - return false; - - Type[] argsA = a.GetGenericArguments (); - Type[] argsB = b.GetGenericArguments (); - for (int i = 0; i < argsA.Length; ++i) { - if (!TypeEquals (argsA [i], argsB [i])) - return false; - } - } - } - - /* - Now only non-generic, non compound types are left. To properly deal with user - types we would have to call UnderlyingSystemType, but we let them have their - own instantiation as this is MS behavior and mcs (pre C# 4.0, at least) doesn't - depend on proper UT canonicalization. - */ - return a == b; - } - - public override bool Equals (object obj) - { - GenericInstanceKey other = obj as GenericInstanceKey; - if (other == null) - return false; - if (gtd != other.gtd) - return false; - for (int i = 0; i < args.Length; ++i) { - Type a = args [i]; - Type b = other.args [i]; - /* - We must cannonicalize as much as we can. Using equals means that some resulting types - won't have the exact same types as the argument ones. - For example, flyweight types used array, pointer and byref will should this behavior. - MCS seens to be resilient to this problem so hopefully this won't show up. - */ - if (a != b && !a.Equals (b)) - return false; - } - return true; - } - - public override int GetHashCode () - { - return hash_code; - } - } - - [StructLayout (LayoutKind.Sequential)] - public sealed partial class AssemblyBuilder : Assembly - { - // - // AssemblyBuilder inherits from Assembly, but the runtime thinks its layout inherits from RuntimeAssembly - // - #region Sync with RuntimeAssembly.cs and ReflectionAssembly in object-internals.h -#pragma warning disable 649 - internal IntPtr _mono_assembly; -#pragma warning restore 649 - object _evidence; - #endregion - -#pragma warning disable 169, 414, 649 - #region Sync with object-internals.h - private UIntPtr dynamic_assembly; /* GC-tracked */ - private MethodInfo entry_point; - private ModuleBuilder[] modules; - private string name; - private string dir; - private CustomAttributeBuilder[] cattrs; - private object resources; - byte[] public_key; - string version; - string culture; - uint algid; - uint flags; - PEFileKinds pekind = PEFileKinds.Dll; - bool delay_sign; - uint access; - Module[] loaded_modules; - object win32_resources; - private object permissions_minimum; - private object permissions_optional; - private object permissions_refused; - PortableExecutableKinds peKind; - ImageFileMachine machine; - bool corlib_internal; - Type[] type_forwarders; - byte[] pktoken; - #endregion -#pragma warning restore 169, 414, 649 - - AssemblyName aname; - string assemblyName; - bool created; - string versioninfo_culture; - ModuleBuilder manifest_module; - bool manifest_module_used; - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void basic_init (AssemblyBuilder ab); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern void UpdateNativeCustomAttributes (AssemblyBuilder ab); - - [PreserveDependency ("RuntimeResolve", "System.Reflection.Emit.ModuleBuilder")] - internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal) - { - aname = (AssemblyName)n.Clone (); - - if (!Enum.IsDefined (typeof (AssemblyBuilderAccess), access)) - throw new ArgumentException (string.Format (CultureInfo.InvariantCulture, - "Argument value {0} is not valid.", (int) access), - "access"); - - name = n.Name; - this.access = (uint)access; - flags = (uint) n.Flags; - - dir = directory; - - /* Set defaults from n */ - if (n.CultureInfo != null) { - culture = n.CultureInfo.Name; - versioninfo_culture = n.CultureInfo.Name; - } - Version v = n.Version; - if (v != null) { - version = v.ToString (); - } - - basic_init (this); - - // Netcore only allows one module per assembly - manifest_module = new ModuleBuilder (this, "RefEmit_InMemoryManifestModule", false); - modules = new ModuleBuilder [] { manifest_module }; - } - - public override string CodeBase { - get { throw not_supported (); } - } - - public override MethodInfo EntryPoint { - get { - return entry_point; - } - } - - public override string Location { - get { - throw not_supported (); - } - } - - public override bool ReflectionOnly { - get { return base.ReflectionOnly; } - } - - public static AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access) - { - if (name == null) - throw new ArgumentNullException ("name"); - - return new AssemblyBuilder (name, null, access, false); - } - - public static AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) - { - var ab = DefineDynamicAssembly (name, access); - if (assemblyAttributes != null) { - foreach (var attr in assemblyAttributes) - ab.SetCustomAttribute (attr); - } - - return ab; - } - - public ModuleBuilder DefineDynamicModule (string name) - { - return DefineDynamicModule (name, false); - } - - public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo) - { - if (name == null) - throw new ArgumentNullException ("name"); - if (name.Length == 0) - throw new ArgumentException ("Empty name is not legal.", "name"); - if (name[0] == '\0') - throw new ArgumentException (SR.Argument_InvalidName, nameof (name)); - - if (manifest_module_used) - throw new InvalidOperationException (SR.InvalidOperation_NoMultiModuleAssembly); - manifest_module_used = true; - return manifest_module; - } - - public ModuleBuilder GetDynamicModule (string name) - { - if (name == null) - throw new ArgumentNullException ("name"); - if (name.Length == 0) - throw new ArgumentException ("Empty name is not legal.", "name"); - - if (modules != null) - for (int i = 0; i < modules.Length; ++i) - if (modules [i].name == name) - return modules [i]; - return null; - } - - public override Type[] GetExportedTypes () - { - throw not_supported (); - } - - public override FileStream GetFile (string name) - { - throw not_supported (); - } - - public override FileStream[] GetFiles(bool getResourceModules) { - throw not_supported (); - } - - public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) { - throw not_supported (); - } - - public override string[] GetManifestResourceNames() { - throw not_supported (); - } - - public override Stream GetManifestResourceStream(string name) { - throw not_supported (); - } - public override Stream GetManifestResourceStream(Type type, string name) { - throw not_supported (); - } - - public override bool IsCollectible { - get { - return access == (uint)AssemblyBuilderAccess.RunAndCollect; - } - } - - internal string AssemblyDir { - get { - return dir; - } - } - - public void SetCustomAttribute( CustomAttributeBuilder customBuilder) - { - if (customBuilder == null) - throw new ArgumentNullException ("customBuilder"); - - if (cattrs != null) { - CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; - cattrs.CopyTo (new_array, 0); - new_array [cattrs.Length] = customBuilder; - cattrs = new_array; - } else { - cattrs = new CustomAttributeBuilder [1]; - cattrs [0] = customBuilder; - } - - /* - Only update the native list of custom attributes if we're adding one that is known to change dynamic execution behavior. - */ - if (customBuilder.Ctor != null && customBuilder.Ctor.DeclaringType == typeof (System.Runtime.CompilerServices.RuntimeCompatibilityAttribute)) - UpdateNativeCustomAttributes (this); - } - - [ComVisible (true)] - public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) - throw new ArgumentNullException ("con"); - if (binaryAttribute == null) - throw new ArgumentNullException ("binaryAttribute"); - - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } - - private Exception not_supported () { - // Strange message but this is what MS.NET prints... - return new NotSupportedException ("The invoked member is not supported in a dynamic module."); - } - - private String create_assembly_version (String version) { - String[] parts = version.Split ('.'); - int[] ver = new int [4] { 0, 0, 0, 0 }; - - if ((parts.Length < 0) || (parts.Length > 4)) - throw new ArgumentException ("The version specified '" + version + "' is invalid"); - - for (int i = 0; i < parts.Length; ++i) { - if (parts [i] == "*") { - DateTime now = DateTime.Now; - - if (i == 2) { - ver [2] = (now - new DateTime (2000, 1, 1)).Days; - if (parts.Length == 3) - ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2; - } - else - if (i == 3) - ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2; - else - throw new ArgumentException ("The version specified '" + version + "' is invalid"); - } - else { - try { - ver [i] = Int32.Parse (parts [i]); - } - catch (FormatException) { - throw new ArgumentException ("The version specified '" + version + "' is invalid"); - } - } - } - - return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3]; - } - - private string GetCultureString (string str) - { - return (str == "neutral" ? String.Empty : str); - } - - /*Warning, @typeArguments must be a mscorlib internal array. So make a copy before passing it in*/ - internal Type MakeGenericType (Type gtd, Type[] typeArguments) - { - return new TypeBuilderInstantiation (gtd, typeArguments); - } - - public override Type GetType (string name, bool throwOnError, bool ignoreCase) - { - if (name == null) - throw new ArgumentNullException (name); - if (name.Length == 0) - throw new ArgumentException ("Name cannot be empty", nameof (name)); - - var res = InternalGetType (null, name, throwOnError, ignoreCase); - if (res is TypeBuilder) { - if (throwOnError) - throw new TypeLoadException (string.Format ("Could not load type '{0}' from assembly '{1}'", name, this.name)); - return null; - } - return res; - } - - public override Module GetModule (String name) - { - if (name == null) - throw new ArgumentNullException ("name"); - if (name.Length == 0) - throw new ArgumentException ("Name can't be empty"); - - if (modules == null) - return null; - - foreach (Module module in modules) { - if (module.ScopeName == name) - return module; - } - - return null; - } - - public override Module[] GetModules (bool getResourceModules) - { - return (Module[])modules.Clone (); - } - - public override AssemblyName GetName (bool copiedName) - { - return AssemblyName.Create (_mono_assembly, null); - } - - // FIXME: "This always returns an empty array" - public override AssemblyName[] GetReferencedAssemblies () - { - throw new NotImplementedException (); -#if FALSE - return GetReferencedAssemblies (this); -#endif - } - - public override Module[] GetLoadedModules (bool getResourceModules) - { - return GetModules (getResourceModules); - } - - //FIXME MS has issues loading satelite assemblies from SRE - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public override Assembly GetSatelliteAssembly (CultureInfo culture) - { - throw new NotImplementedException (); -#if FALSE - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return GetSatelliteAssembly (culture, null, true, ref stackMark); -#endif - } - - //FIXME MS has issues loading satelite assemblies from SRE - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public override Assembly GetSatelliteAssembly (CultureInfo culture, Version version) - { - throw new NotImplementedException (); -#if FALSE - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return GetSatelliteAssembly (culture, version, true, ref stackMark); -#endif - } - - public override Module ManifestModule { - get { - return manifest_module; - } - } - - public override bool GlobalAssemblyCache { - get { - return false; - } - } - - public override bool IsDynamic { - get { return true; } - } - - public override bool Equals (object obj) - { - return base.Equals (obj); - } - - public override int GetHashCode () - { - return base.GetHashCode (); - } - - public override string ToString () - { - if (assemblyName != null) - return assemblyName; - - assemblyName = FullName; - return assemblyName; - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - return CustomAttribute.IsDefined (this, attributeType, inherit); - } - - public override object[] GetCustomAttributes (bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, inherit); - } - - public override object[] GetCustomAttributes (Type attributeType, bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - } - - public override IList<CustomAttributeData> GetCustomAttributesData () - { - return CustomAttributeData.GetCustomAttributes (this); - } - - public override string FullName { - get { - return aname.ToString (); - } - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs deleted file mode 100644 index 7874748a0a2..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs +++ /dev/null @@ -1,373 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit.ConstructorBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Reflection.Emit; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Diagnostics.SymbolStore; - -namespace System.Reflection.Emit { - [StructLayout (LayoutKind.Sequential)] - public sealed partial class ConstructorBuilder : ConstructorInfo { - -#pragma warning disable 169, 414 - private RuntimeMethodHandle mhandle; - private ILGenerator ilgen; - internal Type[] parameters; - private MethodAttributes attrs; - private MethodImplAttributes iattrs; - private int table_idx; - private CallingConventions call_conv; - private TypeBuilder type; - internal ParameterBuilder[] pinfo; - private CustomAttributeBuilder[] cattrs; - private bool init_locals = true; - private Type[][] paramModReq; - private Type[][] paramModOpt; - private object permissions; -#pragma warning restore 169, 414 - internal bool finished; - - internal ConstructorBuilder (TypeBuilder tb, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt) - { - attrs = attributes | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; - call_conv = callingConvention; - if (parameterTypes != null) { - for (int i = 0; i < parameterTypes.Length; ++i) - if (parameterTypes [i] == null) - throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes"); - - this.parameters = new Type [parameterTypes.Length]; - System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length); - } - type = tb; - this.paramModReq = paramModReq; - this.paramModOpt = paramModOpt; - table_idx = get_next_table_index (this, 0x06, 1); - - ((ModuleBuilder) tb.Module).RegisterToken (this, GetToken ().Token); - } - - // FIXME: - public override CallingConventions CallingConvention { - get { - return call_conv; - } - } - - public bool InitLocals { - get { - return init_locals; - } - set { - init_locals = value; - } - } - - internal TypeBuilder TypeBuilder { - get { - return type; - } - } - - public override MethodImplAttributes GetMethodImplementationFlags () - { - return iattrs; - } - - public override ParameterInfo[] GetParameters () - { - if (!type.is_created) - throw not_created (); - - return GetParametersInternal (); - } - - internal override ParameterInfo [] GetParametersInternal () - { - if (parameters == null) - return Array.Empty<ParameterInfo> (); - - ParameterInfo [] retval = new ParameterInfo [parameters.Length]; - for (int i = 0; i < parameters.Length; i++) - retval [i] = RuntimeParameterInfo.New (pinfo?[i + 1], parameters [i], this, i + 1); - - return retval; - } - - internal override int GetParametersCount () - { - if (parameters == null) - return 0; - - return parameters.Length; - } - - internal override Type GetParameterType (int pos) { - return parameters [pos]; - } - - internal MethodBase RuntimeResolve () { - return type.RuntimeResolve ().GetConstructor (this); - } - - public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - throw not_supported (); - } - - public override object Invoke (BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) - { - throw not_supported (); - } - - public override RuntimeMethodHandle MethodHandle { - get { - throw not_supported (); - } - } - - public override MethodAttributes Attributes { - get { - return attrs; - } - } - - public override Type ReflectedType { - get { - return type; - } - } - - public override Type DeclaringType { - get { - return type; - } - } - - public override string Name { - get { - return (attrs & MethodAttributes.Static) != 0 ? ConstructorInfo.TypeConstructorName : ConstructorInfo.ConstructorName; - } - } - - public string Signature { - get { - return "constructor signature"; - } - } - - public ParameterBuilder DefineParameter (int iSequence, ParameterAttributes attributes, string strParamName) - { - // The 0th ParameterBuilder does not correspond to an - // actual parameter, but .NETFramework lets you define - // it anyway. It is not useful. - if (iSequence < 0 || iSequence > GetParametersCount ()) - throw new ArgumentOutOfRangeException ("iSequence"); - if (type.is_created) - throw not_after_created (); - - ParameterBuilder pb = new ParameterBuilder (this, iSequence, attributes, strParamName); - if (pinfo == null) - pinfo = new ParameterBuilder [parameters.Length + 1]; - pinfo [iSequence] = pb; - return pb; - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - throw not_supported (); - } - - public override object [] GetCustomAttributes (bool inherit) - { - throw not_supported (); - } - - public override object [] GetCustomAttributes (Type attributeType, bool inherit) - { - throw not_supported (); - } - - public ILGenerator GetILGenerator () - { - return GetILGenerator (64); - } - - public ILGenerator GetILGenerator (int streamSize) - { - if (finished) - throw new InvalidOperationException (); - if (ilgen != null) - return ilgen; - if (!(((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0))) - throw new InvalidOperationException (); - ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), streamSize); - return ilgen; - } - - public void SetCustomAttribute (CustomAttributeBuilder customBuilder) - { - if (customBuilder == null) - throw new ArgumentNullException ("customBuilder"); - - string attrname = customBuilder.Ctor.ReflectedType.FullName; - if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") { - byte[] data = customBuilder.Data; - int impla; // the (stupid) ctor takes a short or an int ... - impla = (int)data [2]; - impla |= ((int)data [3]) << 8; - SetImplementationFlags ((MethodImplAttributes)impla); - return; - } - if (cattrs != null) { - CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; - cattrs.CopyTo (new_array, 0); - new_array [cattrs.Length] = customBuilder; - cattrs = new_array; - } else { - cattrs = new CustomAttributeBuilder [1]; - cattrs [0] = customBuilder; - } - } - - [ComVisible (true)] - public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute) - { - if (con == null) - throw new ArgumentNullException ("con"); - if (binaryAttribute == null) - throw new ArgumentNullException ("binaryAttribute"); - - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } - - public void SetImplementationFlags (MethodImplAttributes attributes) - { - if (type.is_created) - throw not_after_created (); - - iattrs = attributes; - } - - public Module GetModule () - { - return type.Module; - } - - public MethodToken GetToken () - { - return new MethodToken (0x06000000 | table_idx); - } - - public override Module Module { - get { - return GetModule (); - } - } - - public override string ToString () - { - return "ConstructorBuilder ['" + type.Name + "']"; - } - - internal void fixup () - { - if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) { - if ((ilgen == null) || (ilgen.ILOffset == 0)) - throw new InvalidOperationException ("Method '" + Name + "' does not have a method body."); - } - if (IsStatic && - ((call_conv & CallingConventions.VarArgs) != 0 || - (call_conv & CallingConventions.HasThis) != 0)) - throw new TypeLoadException (); - if (ilgen != null) - ilgen.label_fixup (this); - } - - internal void ResolveUserTypes () { - TypeBuilder.ResolveUserTypes (parameters); - if (paramModReq != null) { - foreach (var types in paramModReq) - TypeBuilder.ResolveUserTypes (types); - } - if (paramModOpt != null) { - foreach (var types in paramModOpt) - TypeBuilder.ResolveUserTypes (types); - } - } -/* - internal void GenerateDebugInfo (ISymbolWriter symbolWriter) - { - if (ilgen != null && ilgen.HasDebugInfo) { - SymbolToken token = new SymbolToken (GetToken().Token); - symbolWriter.OpenMethod (token); - symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name)); - ilgen.GenerateDebugInfo (symbolWriter); - symbolWriter.CloseMethod (); - } - } -*/ - internal override int get_next_table_index (object obj, int table, int count) - { - return type.get_next_table_index (obj, table, count); - } - - private void RejectIfCreated () - { - if (type.is_created) - throw new InvalidOperationException ("Type definition of the method is complete."); - } - - private Exception not_supported () - { - return new NotSupportedException ("The invoked member is not supported in a dynamic module."); - } - - private Exception not_after_created () - { - return new InvalidOperationException ("Unable to change after type has been created."); - } - - private Exception not_created () - { - return new NotSupportedException ("The type is not yet created."); - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorOnTypeBuilderInst.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorOnTypeBuilderInst.cs deleted file mode 100644 index 835f161f25b..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorOnTypeBuilderInst.cs +++ /dev/null @@ -1,227 +0,0 @@ -#nullable disable -// -// System.Reflection.Emit/ConstructorOnTypeBuilderInst.cs -// -// Author: -// Zoltan Varga (vargaz@gmail.com) -// -// -// Copyright (C) 2008 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Globalization; -using System.Reflection; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit -{ - /* - * This class represents a ctor of an instantiation of a generic type builder. - */ - [StructLayout (LayoutKind.Sequential)] - internal class ConstructorOnTypeBuilderInst : ConstructorInfo - { - #region Keep in sync with object-internals.h - internal TypeBuilderInstantiation instantiation; - internal ConstructorInfo cb; - #endregion - - public ConstructorOnTypeBuilderInst (TypeBuilderInstantiation instantiation, ConstructorInfo cb) - { - this.instantiation = instantiation; - this.cb = cb; - } - - // - // MemberInfo members - // - - public override Type DeclaringType { - get { - return instantiation; - } - } - - public override string Name { - get { - return cb.Name; - } - } - - public override Type ReflectedType { - get { - return instantiation; - } - } - - public override Module Module { - get { - return cb.Module; - } - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - return cb.IsDefined (attributeType, inherit); - } - - public override object [] GetCustomAttributes (bool inherit) - { - return cb.GetCustomAttributes (inherit); - } - - public override object [] GetCustomAttributes (Type attributeType, bool inherit) - { - return cb.GetCustomAttributes (attributeType, inherit); - } - - // - // MethodBase members - // - - public override MethodImplAttributes GetMethodImplementationFlags () - { - return cb.GetMethodImplementationFlags (); - } - - public override ParameterInfo[] GetParameters () - { - /*FIXME, maybe the right thing to do when the type is creates is to retrieve from the inflated type*/ - if (!instantiation.IsCreated) - throw new NotSupportedException (); - - return GetParametersInternal (); - } - - internal override ParameterInfo[] GetParametersInternal () - { - ParameterInfo [] res; - if (cb is ConstructorBuilder) { - ConstructorBuilder cbuilder = (ConstructorBuilder)cb; - res = new ParameterInfo [cbuilder.parameters.Length]; - for (int i = 0; i < cbuilder.parameters.Length; i++) { - Type type = instantiation.InflateType (cbuilder.parameters [i]); - res [i] = RuntimeParameterInfo.New (cbuilder.pinfo?[i], type, this, i + 1); - } - } else { - ParameterInfo[] parms = cb.GetParameters (); - res = new ParameterInfo [parms.Length]; - for (int i = 0; i < parms.Length; i++) { - Type type = instantiation.InflateType (parms [i].ParameterType); - res [i] = RuntimeParameterInfo.New (parms [i], type, this, i + 1); - } - } - return res; - } - - internal override Type[] GetParameterTypes () { - if (cb is ConstructorBuilder) { - return (cb as ConstructorBuilder).parameters; - } else { - ParameterInfo[] parms = cb.GetParameters (); - var res = new Type [parms.Length]; - for (int i = 0; i < parms.Length; i++) { - res [i] = parms [i].ParameterType; - } - return res; - } - } - - // Called from the runtime to return the corresponding finished ConstructorInfo object - internal ConstructorInfo RuntimeResolve () { - var type = instantiation.InternalResolve (); - return type.GetConstructor (cb); - } - - public override int MetadataToken { - get { - return base.MetadataToken; - } - } - - internal override int GetParametersCount () - { - return cb.GetParametersCount (); - } - - public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - return cb.Invoke (obj, invokeAttr, binder, parameters, - culture); - } - - public override RuntimeMethodHandle MethodHandle { - get { - return cb.MethodHandle; - } - } - - public override MethodAttributes Attributes { - get { - return cb.Attributes; - } - } - - public override CallingConventions CallingConvention { - get { - return cb.CallingConvention; - } - } - - public override Type [] GetGenericArguments () - { - return cb.GetGenericArguments (); - } - - public override bool ContainsGenericParameters { - get { - return false; - } - } - - public override bool IsGenericMethodDefinition { - get { - return false; - } - } - - public override bool IsGenericMethod { - get { - return false; - } - } - - // - // MethodBase members - // - - public override object Invoke (BindingFlags invokeAttr, Binder binder, object[] parameters, - CultureInfo culture) - { - throw new InvalidOperationException (); - } - } -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs deleted file mode 100644 index 8c75be019e8..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs +++ /dev/null @@ -1,552 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// System.Reflection.Emit/CustomAttributeBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - [StructLayout (LayoutKind.Sequential)] - public partial class CustomAttributeBuilder { - ConstructorInfo ctor; - byte[] data; - object [] args; - PropertyInfo [] namedProperties; - object [] propertyValues; - FieldInfo [] namedFields; - object [] fieldValues; - - internal ConstructorInfo Ctor { - get {return ctor;} - } - - internal byte[] Data { - get {return data;} - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern byte[] GetBlob(Assembly asmb, ConstructorInfo con, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues); - - internal object Invoke () - { - object result = ctor.Invoke (args); - - for (int i=0; i < namedFields.Length; i++) - namedFields [i].SetValue (result, fieldValues [i]); - - for (int i=0; i < namedProperties.Length; i++) - namedProperties [i].SetValue (result, propertyValues [i]); - - return result; - } - - internal CustomAttributeBuilder( ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) - throw new ArgumentNullException ("con"); - if (binaryAttribute == null) - throw new ArgumentNullException ("binaryAttribute"); - ctor = con; - data = (byte[])binaryAttribute.Clone (); - /* should we check that the user supplied data is correct? */ - } - - public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs) - { - Initialize (con, constructorArgs, new PropertyInfo [0], new object [0], - new FieldInfo [0], new object [0]); - } - public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs, - FieldInfo[] namedFields, object[] fieldValues) - { - Initialize (con, constructorArgs, new PropertyInfo [0], new object [0], - namedFields, fieldValues); - } - public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs, - PropertyInfo[] namedProperties, object[] propertyValues) - { - Initialize (con, constructorArgs, namedProperties, propertyValues, new FieldInfo [0], - new object [0]); - } - public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs, - PropertyInfo[] namedProperties, object[] propertyValues, - FieldInfo[] namedFields, object[] fieldValues) - { - Initialize (con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues); - } - - private bool IsValidType (Type t) - { - /* FIXME: Add more checks */ - if (t.IsArray && t.GetArrayRank () > 1) - return false; - if (t is TypeBuilder && t.IsEnum) { - // Check that the enum is properly constructed, the unmanaged code - // depends on this - Enum.GetUnderlyingType (t); - } - if (t.IsClass && !(t.IsArray || t == typeof (object) || t == typeof (Type) || t == typeof (string) || t.Assembly.GetName ().Name == "mscorlib")) - return false; - if (t.IsValueType && !(t.IsPrimitive || t.IsEnum || ((t.Assembly is AssemblyBuilder) && t.Assembly.GetName ().Name == "mscorlib"))) - return false; - return true; - } - - private bool IsValidParam (object o, Type paramType) - { - Type t = o.GetType (); - if (!IsValidType (t)) - return false; - if (paramType == typeof (object)) { - if (t.IsArray && t.GetArrayRank () == 1) - return IsValidType (t.GetElementType ()); - if (!t.IsPrimitive && !typeof (Type).IsAssignableFrom (t) && t != typeof (string) && !t.IsEnum) - return false; - } - return true; - } - - static bool IsValidValue (Type type, object value) { - if (type.IsValueType && value == null) - return false; - if (type.IsArray && type.GetElementType ().IsValueType) { - foreach (var v in (Array)value) { - if (v == null) - return false; - } - } - return true; - } - - private void Initialize (ConstructorInfo con, object [] constructorArgs, - PropertyInfo [] namedProperties, object [] propertyValues, - FieldInfo [] namedFields, object [] fieldValues) - { - ctor = con; - args = constructorArgs; - this.namedProperties = namedProperties; - this.propertyValues = propertyValues; - this.namedFields = namedFields; - this.fieldValues = fieldValues; - - if (con == null) - throw new ArgumentNullException ("con"); - if (constructorArgs == null) - throw new ArgumentNullException ("constructorArgs"); - if (namedProperties == null) - throw new ArgumentNullException ("namedProperties"); - if (propertyValues == null) - throw new ArgumentNullException ("propertyValues"); - if (namedFields == null) - throw new ArgumentNullException ("namedFields"); - if (fieldValues == null) - throw new ArgumentNullException ("fieldValues"); - if (con.GetParametersCount () != constructorArgs.Length) - throw new ArgumentException ("Parameter count does not match " + - "passed in argument value count."); - if (namedProperties.Length != propertyValues.Length) - throw new ArgumentException ("Array lengths must be the same.", - "namedProperties, propertyValues"); - if (namedFields.Length != fieldValues.Length) - throw new ArgumentException ("Array lengths must be the same.", - "namedFields, fieldValues"); - if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static || - (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) - throw new ArgumentException ("Cannot have private or static constructor."); - - Type atype = ctor.DeclaringType; - int i; - i = 0; - foreach (FieldInfo fi in namedFields) { - Type t = fi.DeclaringType; - if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t))) - throw new ArgumentException ("Field '" + fi.Name + "' does not belong to the same class as the constructor"); - if (!IsValidType (fi.FieldType)) - throw new ArgumentException ("Field '" + fi.Name + "' does not have a valid type."); - if (!IsValidValue (fi.FieldType, fieldValues [i])) - throw new ArgumentException ("Field " + fi.Name + " is not a valid value."); - // FIXME: Check enums and TypeBuilders as well - if (fieldValues [i] != null) - // IsEnum does not seem to work on TypeBuilders - if (!(fi.FieldType is TypeBuilder) && !fi.FieldType.IsEnum && !fi.FieldType.IsInstanceOfType (fieldValues [i])) { - // - // mcs allways uses object[] for array types and - // MS.NET allows this - // - if (!fi.FieldType.IsArray) - throw new ArgumentException ("Value of field '" + fi.Name + "' does not match field type: " + fi.FieldType); - } - i ++; - } - - i = 0; - foreach (PropertyInfo pi in namedProperties) { - if (!pi.CanWrite) - throw new ArgumentException ("Property '" + pi.Name + "' does not have a setter."); - Type t = pi.DeclaringType; - if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t))) - throw new ArgumentException ("Property '" + pi.Name + "' does not belong to the same class as the constructor"); - if (!IsValidType (pi.PropertyType)) - throw new ArgumentException ("Property '" + pi.Name + "' does not have a valid type."); - if (!IsValidValue (pi.PropertyType, propertyValues [i])) - throw new ArgumentException ("Property " + pi.Name + " is not a valid value."); - if (propertyValues [i] != null) { - if (!(pi.PropertyType is TypeBuilder) && !pi.PropertyType.IsEnum && !pi.PropertyType.IsInstanceOfType (propertyValues [i])) - if (!pi.PropertyType.IsArray) - throw new ArgumentException ("Value of property '" + pi.Name + "' does not match property type: " + pi.PropertyType + " -> " + propertyValues [i]); - } - i ++; - } - - i = 0; - foreach (ParameterInfo pi in GetParameters (con)) { - if (pi != null) { - Type paramType = pi.ParameterType; - if (!IsValidType (paramType)) - throw new ArgumentException ("Parameter " + i + " does not have a valid type."); - if (!IsValidValue (paramType, constructorArgs [i])) - throw new ArgumentException ("Parameter " + i + " is not a valid value."); - - if (constructorArgs [i] != null) { - if (!(paramType is TypeBuilder) && !paramType.IsEnum && !paramType.IsInstanceOfType (constructorArgs [i])) - if (!paramType.IsArray) - throw new ArgumentException ("Value of argument " + i + " does not match parameter type: " + paramType + " -> " + constructorArgs [i]); - if (!IsValidParam (constructorArgs [i], paramType)) - throw new ArgumentException ("Cannot emit a CustomAttribute with argument of type " + constructorArgs [i].GetType () + "."); - } - } - i ++; - } - - data = GetBlob (atype.Assembly, con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues); - } - - /* helper methods */ - internal static int decode_len (byte[] data, int pos, out int rpos) { - int len = 0; - if ((data [pos] & 0x80) == 0) { - len = (int)(data [pos++] & 0x7f); - } else if ((data [pos] & 0x40) == 0) { - len = ((data [pos] & 0x3f) << 8) + data [pos + 1]; - pos += 2; - } else { - len = ((data [pos] & 0x1f) << 24) + (data [pos + 1] << 16) + (data [pos + 2] << 8) + data [pos + 3]; - pos += 4; - } - rpos = pos; - return len; - } - - internal static string string_from_bytes (byte[] data, int pos, int len) - { - return System.Text.Encoding.UTF8.GetString(data, pos, len); - } - - internal static string decode_string (byte [] data, int pos, out int rpos) - { - if (data [pos] == 0xff) { - rpos = pos + 1; - return null; - } else { - int len = decode_len (data, pos, out pos); - string s = string_from_bytes (data, pos, len); - pos += len; - rpos = pos; - return s; - } - } - - internal string string_arg () - { - int pos = 2; - return decode_string (data, pos, out pos); - } - - internal static UnmanagedMarshal get_umarshal (CustomAttributeBuilder customBuilder, bool is_field) { - byte[] data = customBuilder.Data; - UnmanagedType subtype = (UnmanagedType)0x50; /* NATIVE_MAX */ - int sizeConst = -1; - int sizeParamIndex = -1; - bool hasSize = false; - int value; - int utype; /* the (stupid) ctor takes a short or an enum ... */ - string marshalTypeName = null; - Type marshalTypeRef = null; - string marshalCookie = String.Empty; - utype = (int)data [2]; - utype |= ((int)data [3]) << 8; - - string first_type_name = GetParameters (customBuilder.Ctor) [0].ParameterType.FullName; - int pos = 6; - if (first_type_name == "System.Int16") - pos = 4; - int nnamed = (int)data [pos++]; - nnamed |= ((int)data [pos++]) << 8; - - for (int i = 0; i < nnamed; ++i) { - int paramType; // What is this ? - - /* Skip field/property signature */ - int fieldPropSig = (int)data [pos ++]; - /* Read type */ - paramType = ((int)data [pos++]); - if (paramType == 0x55) { - /* enums, the value is preceeded by the type */ - decode_string (data, pos, out pos); - } - string named_name = decode_string (data, pos, out pos); - - switch (named_name) { - case "ArraySubType": - value = (int)data [pos++]; - value |= ((int)data [pos++]) << 8; - value |= ((int)data [pos++]) << 16; - value |= ((int)data [pos++]) << 24; - subtype = (UnmanagedType)value; - break; - case "SizeConst": - value = (int)data [pos++]; - value |= ((int)data [pos++]) << 8; - value |= ((int)data [pos++]) << 16; - value |= ((int)data [pos++]) << 24; - sizeConst = value; - hasSize = true; - break; - case "SafeArraySubType": - value = (int)data[pos++]; - value |= ((int)data[pos++]) << 8; - value |= ((int)data[pos++]) << 16; - value |= ((int)data[pos++]) << 24; - subtype = (UnmanagedType)value; - break; - case "IidParameterIndex": - pos += 4; - break; - case "SafeArrayUserDefinedSubType": - decode_string (data, pos, out pos); - break; - case "SizeParamIndex": - value = (int)data [pos++]; - value |= ((int)data [pos++]) << 8; - sizeParamIndex = value; - hasSize = true; - break; - case "MarshalType": - marshalTypeName = decode_string (data, pos, out pos); - break; - case "MarshalTypeRef": - marshalTypeName = decode_string (data, pos, out pos); - if (marshalTypeName != null) - marshalTypeRef = Type.GetType (marshalTypeName); - break; - case "MarshalCookie": - marshalCookie = decode_string (data, pos, out pos); - break; - default: - throw new Exception ("Unknown MarshalAsAttribute field: " + named_name); - } - } - - switch ((UnmanagedType)utype) { - case UnmanagedType.LPArray: - if (hasSize) - return UnmanagedMarshal.DefineLPArrayInternal (subtype, sizeConst, sizeParamIndex); - else - return UnmanagedMarshal.DefineLPArray (subtype); -#if FEATURE_COMINTEROP - case UnmanagedType.SafeArray: - return UnmanagedMarshal.DefineSafeArray (subtype); -#endif - case UnmanagedType.ByValArray: - if (!is_field) - throw new ArgumentException ("Specified unmanaged type is only valid on fields"); - - return UnmanagedMarshal.DefineByValArray (sizeConst); - case UnmanagedType.ByValTStr: - return UnmanagedMarshal.DefineByValTStr (sizeConst); -#if FEATURE_COMINTEROP - case UnmanagedType.CustomMarshaler: - return UnmanagedMarshal.DefineCustom (marshalTypeRef, marshalCookie, marshalTypeName, Guid.Empty); -#endif - default: - return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype); - } - } - - static Type elementTypeToType (int elementType) { - /* Partition II, section 23.1.16 */ - switch (elementType) { - case 0x02: - return typeof (bool); - case 0x03: - return typeof (char); - case 0x04: - return typeof (sbyte); - case 0x05: - return typeof (byte); - case 0x06: - return typeof (short); - case 0x07: - return typeof (ushort); - case 0x08: - return typeof (int); - case 0x09: - return typeof (uint); - case 0x0a: - return typeof (long); - case 0x0b: - return typeof (ulong); - case 0x0c: - return typeof (float); - case 0x0d: - return typeof (double); - case 0x0e: - return typeof (string); - default: - throw new Exception ("Unknown element type '" + elementType + "'"); - } - } - - static object decode_cattr_value (Type t, byte[] data, int pos, out int rpos) { - switch (Type.GetTypeCode (t)) { - case TypeCode.String: - if (data [pos] == 0xff) { - rpos = pos + 1; - return null; - } - int len = decode_len (data, pos, out pos); - rpos = pos + len; - return string_from_bytes (data, pos, len); - case TypeCode.Int32: - rpos = pos + 4; - return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24); - case TypeCode.Boolean: - rpos = pos + 1; - return (data [pos] == 0) ? false : true; - case TypeCode.Object: - int subtype = data [pos]; - pos += 1; - - if (subtype >= 0x02 && subtype <= 0x0e) - return decode_cattr_value (elementTypeToType (subtype), data, pos, out rpos); - else - throw new Exception ("Subtype '" + subtype + "' of type object not yet handled in decode_cattr_value"); - default: - throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value."); - } - } - - internal struct CustomAttributeInfo { - public ConstructorInfo ctor; - public object[] ctorArgs; - public string[] namedParamNames; - public object[] namedParamValues; - } - - internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) { - byte[] data = customBuilder.Data; - ConstructorInfo ctor = customBuilder.Ctor; - int pos = 0; - - CustomAttributeInfo info = new CustomAttributeInfo (); - - // Prolog - if (data.Length < 2) - throw new Exception ("Custom attr length is only '" + data.Length + "'"); - if ((data [0] != 0x1) || (data [1] != 0x00)) - throw new Exception ("Prolog invalid"); - pos = 2; - - ParameterInfo [] pi = GetParameters (ctor); - info.ctor = ctor; - info.ctorArgs = new object [pi.Length]; - for (int i = 0; i < pi.Length; ++i) - info.ctorArgs [i] = decode_cattr_value (pi [i].ParameterType, data, pos, out pos); - - int num_named = data [pos] + (data [pos + 1] * 256); - pos += 2; - - info.namedParamNames = new string [num_named]; - info.namedParamValues = new object [num_named]; - for (int i = 0; i < num_named; ++i) { - int named_type = data [pos++]; - int data_type = data [pos++]; - string enum_type_name = null; - - if (data_type == 0x55) { - int len2 = decode_len (data, pos, out pos); - enum_type_name = string_from_bytes (data, pos, len2); - pos += len2; - } - - int len = decode_len (data, pos, out pos); - string name = string_from_bytes (data, pos, len); - info.namedParamNames [i] = name; - pos += len; - - if (named_type == 0x53) { - /* Field */ - FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance); - if (fi == null) - throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'"); - - object val = decode_cattr_value (fi.FieldType, data, pos, out pos); - if (enum_type_name != null) { - Type enumType = Type.GetType (enum_type_name); - val = Enum.ToObject (enumType, val); - } - - info.namedParamValues [i] = val; - } - else - // FIXME: - throw new Exception ("Unknown named type: " + named_type); - } - - return info; - } - - static ParameterInfo [] GetParameters (ConstructorInfo ctor) - { - ConstructorBuilder cb = ctor as ConstructorBuilder; - if (cb != null) - return cb.GetParametersInternal (); - - return ctor.GetParametersInternal (); - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DerivedTypes.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DerivedTypes.Mono.cs deleted file mode 100644 index 4b0361ce699..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DerivedTypes.Mono.cs +++ /dev/null @@ -1,470 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit.DerivedTypes.cs -// -// Authors: -// Rodrigo Kumpera <rkumpera@novell.com> -// -// -// Copyright (C) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System.Reflection; -using System.Reflection.Emit; -using System.Collections; -using System.Runtime.CompilerServices; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; -using System.Text; - - -namespace System.Reflection.Emit -{ - [StructLayout (LayoutKind.Sequential)] - abstract partial class SymbolType : TypeInfo - { - internal Type m_baseType; - - internal SymbolType (Type elementType) - { - this.m_baseType = elementType; - } - - internal abstract String FormatName (string elementName); - - protected override bool IsArrayImpl () - { - return false; - } - - protected override bool IsByRefImpl () - { - return false; - } - - protected override bool IsPointerImpl () - { - return false; - } - - public override Type MakeArrayType () - { - return new ArrayType (this, 0); - } - - public override Type MakeArrayType (int rank) - { - if (rank < 1) - throw new IndexOutOfRangeException (); - return new ArrayType (this, rank); - } - - public override Type MakeByRefType () - { - return new ByRefType (this); - } - - public override Type MakePointerType () - { - return new PointerType (this); - } - - public override string ToString () - { - return FormatName (m_baseType.ToString ()); - } - - public override string AssemblyQualifiedName { - get { - string fullName = FormatName (m_baseType.FullName); - if (fullName == null) - return null; - return fullName + ", " + m_baseType.Assembly.FullName; - } - } - - - public override string FullName { - get { - return FormatName (m_baseType.FullName); - } - } - - public override string Name { - get { - return FormatName (m_baseType.Name); - } - } - - public override Type UnderlyingSystemType { - get { - return this; - } - } - - internal override bool IsUserType { - get { - return m_baseType.IsUserType; - } - } - - // Called from the runtime to return the corresponding finished Type object - internal override Type RuntimeResolve () { - return InternalResolve (); - } - - public override Guid GUID - { - get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } - } - - public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, - Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override Module Module - { - get - { - Type baseType; - - for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType) baseType).m_baseType); - - return baseType.Module; - } - } - public override Assembly Assembly - { - get - { - Type baseType; - - for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType) baseType).m_baseType); - - return baseType.Assembly; - } - } - - public override RuntimeTypeHandle TypeHandle - { - get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } - } - - public override String Namespace - { - get { return m_baseType.Namespace; } - } - - public override Type BaseType - { - get { return typeof(System.Array); } - } - - protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder, - CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder, - CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override MethodInfo[] GetMethods(BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override FieldInfo GetField(String name, BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override FieldInfo[] GetFields(BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override Type GetInterface(String name,bool ignoreCase) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override Type[] GetInterfaces() - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override EventInfo GetEvent(String name,BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override EventInfo[] GetEvents() - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, - Type returnType, Type[] types, ParameterModifier[] modifiers) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override Type[] GetNestedTypes(BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override Type GetNestedType(String name, BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override MemberInfo[] GetMembers(BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override InterfaceMapping GetInterfaceMap(Type interfaceType) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override EventInfo[] GetEvents(BindingFlags bindingAttr) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - protected override TypeAttributes GetAttributeFlagsImpl() - { - // Return the attribute flags of the base type? - Type baseType; - for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType); - return baseType.Attributes; - } - - protected override bool IsPrimitiveImpl() - { - return false; - } - - protected override bool IsValueTypeImpl() - { - return false; - } - - protected override bool IsCOMObjectImpl() - { - return false; - } - - public override bool IsConstructedGenericType - { - get - { - return false; - } - } - - public override Type GetElementType() - { - return m_baseType; - } - - protected override bool HasElementTypeImpl() - { - return m_baseType != null; - } - - public override Object[] GetCustomAttributes(bool inherit) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override Object[] GetCustomAttributes(Type attributeType, bool inherit) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); - } - } - - [StructLayout (LayoutKind.Sequential)] - internal class ArrayType : SymbolType - { - int rank; - - internal ArrayType (Type elementType, int rank) : base (elementType) - { - this.rank = rank; - } - - internal int GetEffectiveRank () - { - return rank; - } - - internal override Type InternalResolve () - { - Type et = m_baseType.InternalResolve (); - if (rank == 0) - return et.MakeArrayType (); - return et.MakeArrayType (rank); - } - - internal override Type RuntimeResolve () - { - Type et = m_baseType.RuntimeResolve (); - if (rank == 0) - return et.MakeArrayType (); - return et.MakeArrayType (rank); - } - - protected override bool IsArrayImpl () - { - return true; - } - - public override bool IsSZArray { - get { - return rank == 0; - } - } - - public override int GetArrayRank () - { - return (rank == 0) ? 1 : rank; - } - - internal override String FormatName (string elementName) - { - if (elementName == null) - return null; - StringBuilder sb = new StringBuilder (elementName); - sb.Append ("["); - for (int i = 1; i < rank; ++i) - sb.Append (","); - if (rank == 1) - sb.Append ("*"); - sb.Append ("]"); - return sb.ToString (); - } - } - - [StructLayout (LayoutKind.Sequential)] - internal class ByRefType : SymbolType - { - internal ByRefType (Type elementType) : base (elementType) - { - } - - internal override Type InternalResolve () - { - return m_baseType.InternalResolve ().MakeByRefType (); - } - - protected override bool IsByRefImpl () - { - return true; - } - - internal override String FormatName (string elementName) - { - if (elementName == null) - return null; - return elementName + "&"; - } - - public override Type MakeArrayType () - { - throw new ArgumentException ("Cannot create an array type of a byref type"); - } - - public override Type MakeArrayType (int rank) - { - throw new ArgumentException ("Cannot create an array type of a byref type"); - } - - public override Type MakeByRefType () - { - throw new ArgumentException ("Cannot create a byref type of an already byref type"); - } - - public override Type MakePointerType () - { - throw new ArgumentException ("Cannot create a pointer type of a byref type"); - } - } - - [StructLayout (LayoutKind.Sequential)] - internal class PointerType : SymbolType - { - internal PointerType (Type elementType) : base (elementType) - { - } - - internal override Type InternalResolve () - { - return m_baseType.InternalResolve ().MakePointerType (); - } - - protected override bool IsPointerImpl () - { - return true; - } - - internal override String FormatName (string elementName) - { - if (elementName == null) - return null; - return elementName + "*"; - } - } - -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs deleted file mode 100644 index 9501a83f44b..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs +++ /dev/null @@ -1,133 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit/DynamicILInfo.cs -// -// Author: -// Zoltan Varga (vargaz@gmail.com) -// -// Copyright (C) 2007 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - - [ComVisible (true)] - public class DynamicILInfo { - - DynamicMethod method; - - internal DynamicILInfo () - { - } - - internal DynamicILInfo (DynamicMethod method) - { - this.method = method; - } - - public DynamicMethod DynamicMethod { - get { - return method; - } - } - - // FIXME: - public int GetTokenFor (byte[] signature) { - throw new NotImplementedException (); - } - - public int GetTokenFor (DynamicMethod method) { - return this.method.GetILGenerator ().TokenGenerator.GetToken (method, false); - } - - public int GetTokenFor (RuntimeFieldHandle field) { - return this.method.GetILGenerator ().TokenGenerator.GetToken (FieldInfo.GetFieldFromHandle (field), false); - } - - public int GetTokenFor (RuntimeMethodHandle method) { - MethodBase mi = MethodBase.GetMethodFromHandle (method); - return this.method.GetILGenerator ().TokenGenerator.GetToken (mi, false); - } - - public int GetTokenFor (RuntimeTypeHandle type) { - Type t = Type.GetTypeFromHandle (type); - return this.method.GetILGenerator ().TokenGenerator.GetToken (t, false); - } - - public int GetTokenFor (string literal) { - return method.GetILGenerator ().TokenGenerator.GetToken (literal); - } - - // FIXME: - public int GetTokenFor (RuntimeMethodHandle method, RuntimeTypeHandle contextType) { - throw new NotImplementedException (); - } - - // FIXME: - public int GetTokenFor (RuntimeFieldHandle field, RuntimeTypeHandle contextType) { - throw new NotImplementedException (); - } - - public void SetCode (byte[] code, int maxStackSize) { - if (code == null) - throw new ArgumentNullException ("code"); - method.GetILGenerator ().SetCode (code, maxStackSize); - } - - [CLSCompliantAttribute(false)] - public unsafe void SetCode (byte* code, int codeSize, int maxStackSize) { - if (code == null) - throw new ArgumentNullException ("code"); - method.GetILGenerator ().SetCode (code, codeSize, maxStackSize); - } - - // FIXME: - public void SetExceptions (byte[] exceptions) { - throw new NotImplementedException (); - } - - // FIXME: - [CLSCompliantAttribute(false)] - public unsafe void SetExceptions (byte* exceptions, int exceptionsSize) { - throw new NotImplementedException (); - } - - // FIXME: - public void SetLocalSignature (byte[] localSignature) { - throw new NotImplementedException (); - } - - [CLSCompliantAttribute(false)] - public unsafe void SetLocalSignature (byte* localSignature, int signatureSize) { - byte[] b = new byte [signatureSize]; - for (int i = 0; i < signatureSize; ++i) - b [i] = localSignature [i]; - } - } -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs deleted file mode 100644 index 13589e2c1cb..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs +++ /dev/null @@ -1,481 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit.DynamicMethod.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// Zoltan Varga (vargaz@freemail.hu) -// -// (C) 2003 Ximian, Inc. http://www.ximian.com -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE - -using System; -using System.Text; -using System.Reflection; -using System.Reflection.Emit; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - - [ComVisible (true)] - [StructLayout (LayoutKind.Sequential)] - public sealed class DynamicMethod : MethodInfo { - -#pragma warning disable 169, 414, 649 - #region Sync with reflection.h - private RuntimeMethodHandle mhandle; - private string name; - private Type returnType; - private Type[] parameters; - private MethodAttributes attributes; - private CallingConventions callingConvention; - private Module module; - private bool skipVisibility; - private bool init_locals = true; - private ILGenerator ilgen; - private int nrefs; - private object[] refs; - private IntPtr referenced_by; - private Type owner; - #endregion -#pragma warning restore 169, 414, 649 - - private Delegate deleg; - private RuntimeMethodInfo method; - private ParameterBuilder[] pinfo; - internal bool creating; - private DynamicILInfo il_info; - - public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m) : this (name, returnType, parameterTypes, m, false) { - } - - public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner) : this (name, returnType, parameterTypes, owner, false) { - } - - public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, m, skipVisibility) { - } - - public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, skipVisibility) { - } - - public DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) : this (name, attributes, callingConvention, returnType, parameterTypes, owner, owner != null ? owner.Module : null, skipVisibility, false, true) { - } - - public DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) : this (name, attributes, callingConvention, returnType, parameterTypes, null, m, skipVisibility, false, false) { - } - - public DynamicMethod (string name, Type returnType, Type[] parameterTypes) : this (name, returnType, parameterTypes, false) { - } - - // FIXME: "Visibility is not restricted" - public DynamicMethod (string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility) - : this (name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, null, restrictedSkipVisibility, true, false) - { - } - - DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type [] parameterTypes, Type owner, Module m, bool skipVisibility, bool anonHosted, bool typeOwner) - { - if (name == null) - throw new ArgumentNullException (nameof (name)); - if (returnType == null) - returnType = typeof (void); - if (owner == null && typeOwner) - throw new ArgumentNullException (nameof (owner)); - if ((m == null) && !anonHosted) - throw new ArgumentNullException (nameof (m)); - if (parameterTypes != null) { - for (int i = 0; i < parameterTypes.Length; ++i) - if (parameterTypes [i] == null) - throw new ArgumentException ($"Parameter {i} is null"); - } - if (owner != null && (owner.IsArray || owner.IsInterface)) { - throw new ArgumentException ("Owner can't be an array or an interface."); - } - - if (m == null) - m = AnonHostModuleHolder.AnonHostModule; - - this.name = name; - this.attributes = attributes | MethodAttributes.Static; - this.callingConvention = callingConvention; - this.returnType = returnType; - this.parameters = parameterTypes; - this.owner = owner; - this.module = m; - this.skipVisibility = skipVisibility; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void create_dynamic_method (DynamicMethod m); - - private void CreateDynMethod () { - // Clearing of ilgen in create_dynamic_method is not yet synchronized for multiple threads - lock (this) { - if (mhandle.Value == IntPtr.Zero) { - if (ilgen == null || ilgen.ILOffset == 0) - throw new InvalidOperationException ("Method '" + name + "' does not have a method body."); - - ilgen.label_fixup (this); - - // Have to create all DynamicMethods referenced by this one - try { - // Used to avoid cycles - creating = true; - if (refs != null) { - for (int i = 0; i < refs.Length; ++i) { - if (refs [i] is DynamicMethod) { - DynamicMethod m = (DynamicMethod)refs [i]; - if (!m.creating) - m.CreateDynMethod (); - } - } - } - } finally { - creating = false; - } - create_dynamic_method (this); - ilgen = null; - } - } - } - - [ComVisible (true)] - sealed override - public Delegate CreateDelegate (Type delegateType) - { - if (delegateType == null) - throw new ArgumentNullException ("delegateType"); - if (deleg != null) - return deleg; - - CreateDynMethod (); - - deleg = Delegate.CreateDelegate (delegateType, null, this); - return deleg; - } - - [ComVisible (true)] - sealed override - public Delegate CreateDelegate (Type delegateType, object target) - { - if (delegateType == null) - throw new ArgumentNullException ("delegateType"); - - CreateDynMethod (); - - /* Can't cache the delegate since it is different for each target */ - return Delegate.CreateDelegate (delegateType, target, this); - } - - public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string parameterName) - { - // - // Extension: Mono allows position == 0 for the return attribute - // - if ((position < 0) || (position > parameters.Length)) - throw new ArgumentOutOfRangeException ("position"); - - RejectIfCreated (); - - ParameterBuilder pb = new ParameterBuilder (this, position, attributes, parameterName); - if (pinfo == null) - pinfo = new ParameterBuilder [parameters.Length + 1]; - pinfo [position] = pb; - return pb; - } - - public override MethodInfo GetBaseDefinition () { - return this; - } - - public override object[] GetCustomAttributes (bool inherit) { - // support for MethodImplAttribute PCA - return new Object[] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) }; - } - - public override object[] GetCustomAttributes (Type attributeType, - bool inherit) { - if (attributeType == null) - throw new ArgumentNullException ("attributeType"); - - if (attributeType.IsAssignableFrom (typeof (MethodImplAttribute))) - return new Object[] { new MethodImplAttribute ((MethodImplOptions)GetMethodImplementationFlags()) }; - else - return Array.Empty<object> (); - } - - public DynamicILInfo GetDynamicILInfo () { - if (il_info == null) - il_info = new DynamicILInfo (this); - return il_info; - } - - public ILGenerator GetILGenerator () { - return GetILGenerator (64); - } - - public ILGenerator GetILGenerator (int streamSize) { - if (((GetMethodImplementationFlags () & MethodImplAttributes.CodeTypeMask) != - MethodImplAttributes.IL) || - ((GetMethodImplementationFlags () & MethodImplAttributes.ManagedMask) != - MethodImplAttributes.Managed)) - throw new InvalidOperationException ("Method body should not exist."); - if (ilgen != null) - return ilgen; - ilgen = new ILGenerator (Module, new DynamicMethodTokenGenerator (this), streamSize); - return ilgen; - } - - public override MethodImplAttributes GetMethodImplementationFlags () { - return MethodImplAttributes.IL | MethodImplAttributes.Managed | MethodImplAttributes.NoInlining; - } - - public override ParameterInfo[] GetParameters () - { - return GetParametersInternal (); - } - - internal override ParameterInfo[] GetParametersInternal () - { - if (parameters == null) - return Array.Empty<ParameterInfo> (); - - ParameterInfo[] retval = new ParameterInfo [parameters.Length]; - for (int i = 0; i < parameters.Length; i++) { - retval [i] = RuntimeParameterInfo.New (pinfo?[i + 1], parameters [i], this, i + 1); - } - return retval; - } - - internal override int GetParametersCount () - { - return parameters == null ? 0 : parameters.Length; - } - - internal override Type GetParameterType (int pos) { - return parameters [pos]; - } - - /* - public override object Invoke (object obj, object[] parameters) { - CreateDynMethod (); - if (method == null) - method = new RuntimeMethodInfo (mhandle); - return method.Invoke (obj, parameters); - } - */ - - public override object Invoke (object obj, BindingFlags invokeAttr, - Binder binder, object[] parameters, - CultureInfo culture) - { - try { - CreateDynMethod (); - if (method == null) - method = new RuntimeMethodInfo (mhandle); - - return method.Invoke (obj, invokeAttr, binder, parameters, culture); - } - catch (MethodAccessException mae) { - throw new TargetInvocationException ("Method cannot be invoked.", mae); - } - } - - public override bool IsDefined (Type attributeType, bool inherit) { - if (attributeType == null) - throw new ArgumentNullException ("attributeType"); - - if (attributeType.IsAssignableFrom (typeof (MethodImplAttribute))) - return true; - else - return false; - } - - public override string ToString () { - var sbName = new ValueStringBuilder (MethodNameBufferSize); - sbName.Append (ReturnType.FormatTypeName ()); - sbName.Append (' '); - sbName.Append (Name); - sbName.Append ('('); - AppendParameters (ref sbName, parameters ?? Array.Empty<Type> (), CallingConvention); - sbName.Append (')'); - return sbName.ToString (); - } - - public override MethodAttributes Attributes { - get { - return attributes; - } - } - - public override CallingConventions CallingConvention { - get { - return callingConvention; - } - } - - public override Type DeclaringType { - get { - return null; - } - } - - public bool InitLocals { - get { - return init_locals; - } - set { - init_locals = value; - } - } - - public override RuntimeMethodHandle MethodHandle { - get { - return mhandle; - } - } - - public override Module Module { - get { - return module; - } - } - - public override string Name { - get { - return name; - } - } - - public override Type ReflectedType { - get { - return null; - } - } - - public override ParameterInfo ReturnParameter { - get { - if (deleg == null) { - return new RuntimeParameterInfo ((ParameterBuilder) null, returnType, this, -1); - } - return deleg.Method.ReturnParameter; - } - } - - public override Type ReturnType { - get { - return returnType; - } - } - - // FIXME: "Not implemented" - public override ICustomAttributeProvider ReturnTypeCustomAttributes { - get { - throw new NotImplementedException (); - } - } - -/* - public override int MetadataToken { - get { - return 0; - } - } -*/ - - private void RejectIfCreated () { - if (mhandle.Value != IntPtr.Zero) - throw new InvalidOperationException ("Type definition of the method is complete."); - } - - internal int AddRef (object reference) { - if (refs == null) - refs = new object [4]; - if (nrefs >= refs.Length - 1) { - object [] new_refs = new object [refs.Length * 2]; - System.Array.Copy (refs, new_refs, refs.Length); - refs = new_refs; - } - refs [nrefs] = reference; - /* Reserved by the runtime */ - refs [nrefs + 1] = null; - nrefs += 2; - return nrefs - 1; - } - - // This class takes care of constructing the module in a thread safe manner - static class AnonHostModuleHolder - { - public static readonly Module anon_host_module; - - static AnonHostModuleHolder () { - AssemblyName aname = new AssemblyName (); - aname.Name = "Anonymously Hosted DynamicMethods Assembly"; - AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly (aname, AssemblyBuilderAccess.Run); - - anon_host_module = ab.ManifestModule; - } - - public static Module AnonHostModule { - get { - return anon_host_module; - } - } - } - } - - internal class DynamicMethodTokenGenerator : TokenGenerator { - - private DynamicMethod m; - - public DynamicMethodTokenGenerator (DynamicMethod m) { - this.m = m; - } - - public int GetToken (string str) { - return m.AddRef (str); - } - - public int GetToken (MethodBase method, Type[] opt_param_types) { - throw new InvalidOperationException (); - } - - public int GetToken (MemberInfo member, bool create_open_instance) { - return m.AddRef (member); - } - - public int GetToken (SignatureHelper helper) { - return m.AddRef (helper); - } - } -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.notsupported.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.notsupported.cs deleted file mode 100644 index 825790bd32b..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.notsupported.cs +++ /dev/null @@ -1,156 +0,0 @@ -#nullable disable - -// -// DynamicMethod.cs -// -// Authors: -// Marek Safar (marek.safar@gmail.com) -// -// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if !MONO_FEATURE_SRE - -using System.Globalization; - -namespace System.Reflection.Emit -{ - public sealed class DynamicMethod : MethodInfo - { - public DynamicMethod (string name, Type returnType, Type[] parameterTypes) - { - throw new PlatformNotSupportedException (); - } - - public DynamicMethod (string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility) - { - throw new PlatformNotSupportedException (); - } - - public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m) - { - throw new PlatformNotSupportedException (); - } - - public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner) - { - throw new PlatformNotSupportedException (); - } - - public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) - { - throw new PlatformNotSupportedException (); - } - - public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) - { - throw new PlatformNotSupportedException (); - } - - public DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) - { - throw new PlatformNotSupportedException (); - } - - public DynamicMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) - { - throw new PlatformNotSupportedException (); - } - - public override MethodAttributes Attributes { - get { - throw new PlatformNotSupportedException (); - } - } - - public override CallingConventions CallingConvention { - get { - throw new PlatformNotSupportedException (); - } - } - - public override Type DeclaringType { - get { - throw new PlatformNotSupportedException (); - } - } - - public bool InitLocals { get; set; } - - public override MethodImplAttributes MethodImplementationFlags { - get { - throw new PlatformNotSupportedException (); - } - } - - public override string Name { - get { - throw new PlatformNotSupportedException (); - } - } - - public override ParameterInfo ReturnParameter { - get { - throw new PlatformNotSupportedException (); - } - } - - public override Type ReturnType { - get { - throw new PlatformNotSupportedException (); - } - } - - public ILGenerator GetILGenerator () - { - throw new PlatformNotSupportedException (); - } - - public ILGenerator GetILGenerator (int streamSize) - { - throw new PlatformNotSupportedException (); - } - - public override ParameterInfo[] GetParameters () - { - throw new PlatformNotSupportedException (); - } - - public override RuntimeMethodHandle MethodHandle { get { throw new PlatformNotSupportedException (); } } - public override Type ReflectedType { get { throw new PlatformNotSupportedException (); } } - public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new PlatformNotSupportedException (); } } - - public override object[] GetCustomAttributes (bool inherit) { throw new PlatformNotSupportedException (); } - public override object[] GetCustomAttributes (Type attributeType, bool inherit) { throw new PlatformNotSupportedException (); } - public override MethodImplAttributes GetMethodImplementationFlags () { throw new PlatformNotSupportedException (); } - public override MethodInfo GetBaseDefinition () { throw new PlatformNotSupportedException (); } - - public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new PlatformNotSupportedException (); } - - public override bool IsDefined (Type attributeType, bool inherit) { throw new PlatformNotSupportedException (); } - - public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string parameterName) => throw new PlatformNotSupportedException (); - public DynamicILInfo GetDynamicILInfo () => throw new PlatformNotSupportedException (); - } -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.Mono.cs deleted file mode 100644 index 961ea6ad69c..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.Mono.cs +++ /dev/null @@ -1,432 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// System.Reflection.Emit/EnumBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - public sealed partial class EnumBuilder : TypeInfo - { - private TypeBuilder _tb; - private FieldBuilder _underlyingField; - private Type _underlyingType; - - internal EnumBuilder (ModuleBuilder mb, string name, TypeAttributes visibility, Type underlyingType) - { - if ((visibility & ~TypeAttributes.VisibilityMask) != 0) - throw new ArgumentException (SR.Argument_ShouldOnlySetVisibilityFlags, nameof (name)); - if ((visibility & TypeAttributes.VisibilityMask) >= TypeAttributes.NestedPublic && (visibility & TypeAttributes.VisibilityMask) <= TypeAttributes.NestedFamORAssem) - throw new ArgumentException (); - _tb = new TypeBuilder (mb, name, (visibility | TypeAttributes.Sealed), - typeof(Enum), null, PackingSize.Unspecified, 0, null); - _underlyingType = underlyingType; - _underlyingField = _tb.DefineField ("value__", underlyingType, - (FieldAttributes.SpecialName | FieldAttributes.Private | FieldAttributes.RTSpecialName)); - setup_enum_type (_tb); - } - - internal TypeBuilder GetTypeBuilder () - { - return _tb; - } - - internal override Type InternalResolve () - { - return _tb.InternalResolve (); - } - - internal override Type RuntimeResolve () { - return _tb.RuntimeResolve (); - } - - public override Assembly Assembly { - get { - return _tb.Assembly; - } - } - - public override string AssemblyQualifiedName { - get { - return _tb.AssemblyQualifiedName; - } - } - - public override Type BaseType { - get { - return _tb.BaseType; - } - } - - public override Type DeclaringType { - get { - return _tb.DeclaringType; - } - } - - public override string FullName { - get { - return _tb.FullName; - } - } - - public override Guid GUID { - get { - return _tb.GUID; - } - } - - public override Module Module { - get { - return _tb.Module; - } - } - - public override string Name { - get { - return _tb.Name; - } - } - - public override string Namespace { - get { - return _tb.Namespace; - } - } - - public override Type ReflectedType { - get { - return _tb.ReflectedType; - } - } - - public override RuntimeTypeHandle TypeHandle { - get { - return _tb.TypeHandle; - } - } - - public TypeToken TypeToken { - get { - return _tb.TypeToken; - } - } - - public FieldBuilder UnderlyingField { - get { - return _underlyingField; - } - } - - public override Type UnderlyingSystemType { - get { - return _underlyingType; - } - } - - public Type CreateType () - { - Type res = _tb.CreateType (); - return res; - } - - public TypeInfo CreateTypeInfo() - { - return _tb.CreateTypeInfo (); - } - - public override Type GetEnumUnderlyingType () - { - return _underlyingType; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern void setup_enum_type (Type t); - - public FieldBuilder DefineLiteral (string literalName, object literalValue) - { - Type fieldType = this; - FieldBuilder fieldBuilder = _tb.DefineField (literalName, - fieldType, (FieldAttributes.Literal | - (FieldAttributes.Static | FieldAttributes.Public))); - fieldBuilder.SetConstant (literalValue); - return fieldBuilder; - } - - protected override TypeAttributes GetAttributeFlagsImpl () - { - return _tb.attrs; - } - - protected override ConstructorInfo GetConstructorImpl ( - BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, - Type[] types, ParameterModifier[] modifiers) - { - return _tb.GetConstructor (bindingAttr, binder, callConvention, types, - modifiers); - } - - [ComVisible (true)] - public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) - { - return _tb.GetConstructors (bindingAttr); - } - - public override object[] GetCustomAttributes(bool inherit) - { - return _tb.GetCustomAttributes (inherit); - } - - public override object[] GetCustomAttributes(Type attributeType, bool inherit) - { - if (attributeType == null) - return _tb.GetCustomAttributes (inherit); - else - return _tb.GetCustomAttributes (attributeType, inherit); - } - - public override Type GetElementType() - { - return _tb.GetElementType (); - } - - public override EventInfo GetEvent( string name, BindingFlags bindingAttr) - { - return _tb.GetEvent (name, bindingAttr); - } - - public override EventInfo[] GetEvents() - { - return _tb.GetEvents (); - } - - public override EventInfo[] GetEvents( BindingFlags bindingAttr) - { - return _tb.GetEvents (bindingAttr); - } - - public override FieldInfo GetField( string name, BindingFlags bindingAttr) - { - return _tb.GetField (name, bindingAttr); - } - - public override FieldInfo[] GetFields( BindingFlags bindingAttr) - { - return _tb.GetFields (bindingAttr); - } - - public override Type GetInterface (string name, bool ignoreCase) - { - return _tb.GetInterface (name, ignoreCase); - } - - [ComVisible (true)] - public override InterfaceMapping GetInterfaceMap (Type interfaceType) - { - return _tb.GetInterfaceMap (interfaceType); - } - - public override Type[] GetInterfaces() - { - return _tb.GetInterfaces (); - } - - public override MemberInfo[] GetMember (string name, MemberTypes type, BindingFlags bindingAttr) - { - return _tb.GetMember (name, type, bindingAttr); - } - - public override MemberInfo[] GetMembers(BindingFlags bindingAttr) - { - return _tb.GetMembers (bindingAttr); - } - - protected override MethodInfo GetMethodImpl ( - string name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, - ParameterModifier[] modifiers) - { - if (types == null) { - return _tb.GetMethod (name, bindingAttr); - } - - return _tb.GetMethod (name, bindingAttr, binder, - callConvention, types, modifiers); - } - - public override MethodInfo[] GetMethods (BindingFlags bindingAttr) - { - return _tb.GetMethods (bindingAttr); - } - - public override Type GetNestedType (string name, BindingFlags bindingAttr) - { - return _tb.GetNestedType (name, bindingAttr); - } - - public override Type[] GetNestedTypes (BindingFlags bindingAttr) - { - return _tb.GetNestedTypes (bindingAttr); - } - - public override PropertyInfo[] GetProperties (BindingFlags bindingAttr) - { - return _tb.GetProperties (bindingAttr); - } - - protected override PropertyInfo GetPropertyImpl ( - string name, BindingFlags bindingAttr, Binder binder, - Type returnType, Type[] types, - ParameterModifier[] modifiers) - { - throw CreateNotSupportedException (); - } - - protected override bool HasElementTypeImpl () - { - return _tb.HasElementType; - } - - public override object InvokeMember ( - string name, BindingFlags invokeAttr, Binder binder, - object target, object[] args, - ParameterModifier[] modifiers, CultureInfo culture, - string[] namedParameters) - { - return _tb.InvokeMember (name, invokeAttr, binder, target, - args, modifiers, culture, namedParameters); - } - - protected override bool IsArrayImpl() - { - return false; - } - - protected override bool IsByRefImpl() - { - return false; - } - - protected override bool IsCOMObjectImpl() - { - return false; - } - - protected override bool IsPointerImpl() - { - return false; - } - - protected override bool IsPrimitiveImpl() - { - return false; - } - - protected override bool IsValueTypeImpl() - { - return true; - } - - public override bool IsSZArray { - get { - return false; - } - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - return _tb.IsDefined (attributeType, inherit); - } - - public override Type MakeArrayType () - { - return new ArrayType (this, 0); - } - - public override Type MakeArrayType (int rank) - { - if (rank < 1) - throw new IndexOutOfRangeException (); - return new ArrayType (this, rank); - } - - public override Type MakeByRefType () - { - return new ByRefType (this); - } - - public override Type MakePointerType () - { - return new PointerType (this); - } - - public void SetCustomAttribute (CustomAttributeBuilder customBuilder) - { - _tb.SetCustomAttribute (customBuilder); - } - - [ComVisible (true)] - public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute) - { - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } - - private Exception CreateNotSupportedException () - { - return new NotSupportedException ("The invoked member is not supported in a dynamic module."); - } - - internal override bool IsUserType { - get { - return false; - } - } - - public override bool IsConstructedGenericType { - get { return false; } - } - - public override bool IsAssignableFrom (TypeInfo typeInfo) - { - return base.IsAssignableFrom (typeInfo); - } - - public override bool IsTypeDefinition => true; - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs deleted file mode 100644 index 5957bce7ed1..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs +++ /dev/null @@ -1,143 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// System.Reflection.Emit/EventBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - [StructLayout (LayoutKind.Sequential)] - public sealed partial class EventBuilder { -#pragma warning disable 169, 414 - internal string name; - Type type; - TypeBuilder typeb; - CustomAttributeBuilder[] cattrs; - internal MethodBuilder add_method; - internal MethodBuilder remove_method; - internal MethodBuilder raise_method; - internal MethodBuilder[] other_methods; - internal EventAttributes attrs; - int table_idx; -#pragma warning restore 169, 414 - - internal EventBuilder (TypeBuilder tb, string eventName, EventAttributes eventAttrs, Type eventType) { - name = eventName; - attrs = eventAttrs; - type = eventType; - typeb = tb; - table_idx = get_next_table_index (this, 0x14, 1); - } - - internal int get_next_table_index (object obj, int table, int count) { - return typeb.get_next_table_index (obj, table, count); - } - - public void AddOtherMethod( MethodBuilder mdBuilder) { - if (mdBuilder == null) - throw new ArgumentNullException ("mdBuilder"); - RejectIfCreated (); - if (other_methods != null) { - MethodBuilder[] newv = new MethodBuilder [other_methods.Length + 1]; - other_methods.CopyTo (newv, 0); - other_methods = newv; - } else { - other_methods = new MethodBuilder [1]; - } - other_methods [other_methods.Length - 1] = mdBuilder; - } - - public EventToken GetEventToken () { - return new EventToken (0x14000000 | table_idx); - } - public void SetAddOnMethod( MethodBuilder mdBuilder) { - if (mdBuilder == null) - throw new ArgumentNullException ("mdBuilder"); - RejectIfCreated (); - add_method = mdBuilder; - } - public void SetRaiseMethod( MethodBuilder mdBuilder) { - if (mdBuilder == null) - throw new ArgumentNullException ("mdBuilder"); - RejectIfCreated (); - raise_method = mdBuilder; - } - public void SetRemoveOnMethod( MethodBuilder mdBuilder) { - if (mdBuilder == null) - throw new ArgumentNullException ("mdBuilder"); - RejectIfCreated (); - remove_method = mdBuilder; - } - - public void SetCustomAttribute( CustomAttributeBuilder customBuilder) { - if (customBuilder == null) - throw new ArgumentNullException ("customBuilder"); - RejectIfCreated (); - string attrname = customBuilder.Ctor.ReflectedType.FullName; - if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") { - attrs |= EventAttributes.SpecialName; - return; - } - if (cattrs != null) { - CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; - cattrs.CopyTo (new_array, 0); - new_array [cattrs.Length] = customBuilder; - cattrs = new_array; - } else { - cattrs = new CustomAttributeBuilder [1]; - cattrs [0] = customBuilder; - } - } - - [ComVisible (true)] - public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) - throw new ArgumentNullException ("con"); - if (binaryAttribute == null) - throw new ArgumentNullException ("binaryAttribute"); - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } - - private void RejectIfCreated () { - if (typeb.is_created) - throw new InvalidOperationException ("Type definition of the method is complete."); - } - } -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventOnTypeBuilderInst.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventOnTypeBuilderInst.cs deleted file mode 100644 index a1dff8fc9db..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/EventOnTypeBuilderInst.cs +++ /dev/null @@ -1,135 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit/EventOnTypeBuilderInst.cs -// -// Author: -// Rodrigo Kumpera (rkumpera@novell.com) -// -// -// Copyright (C) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Collections; -using System.Globalization; -using System.Reflection; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit -{ - /* - * This class represents an event of an instantiation of a generic type builder. - */ - [StructLayout (LayoutKind.Sequential)] - internal class EventOnTypeBuilderInst : EventInfo - { - TypeBuilderInstantiation instantiation; - EventBuilder event_builder; - EventInfo event_info; - - internal EventOnTypeBuilderInst (TypeBuilderInstantiation instantiation, EventBuilder evt) - { - this.instantiation = instantiation; - this.event_builder = evt; - } - - internal EventOnTypeBuilderInst (TypeBuilderInstantiation instantiation, EventInfo evt) - { - this.instantiation = instantiation; - this.event_info = evt; - } - - public override EventAttributes Attributes { - get { return event_builder != null ? event_builder.attrs : event_info.Attributes; } - } - - public override MethodInfo GetAddMethod (bool nonPublic) - { - MethodInfo add = event_builder != null ? event_builder.add_method : event_info.GetAddMethod (nonPublic); - if (add == null || (!nonPublic && !add.IsPublic)) - return null; - return TypeBuilder.GetMethod (instantiation, add); - } - - public override MethodInfo GetRaiseMethod (bool nonPublic) - { - MethodInfo raise = event_builder != null ? event_builder.raise_method : event_info.GetRaiseMethod (nonPublic); - if (raise == null || (!nonPublic && !raise.IsPublic)) - return null; - return TypeBuilder.GetMethod (instantiation, raise); - } - - public override MethodInfo GetRemoveMethod (bool nonPublic) - { - MethodInfo remove = event_builder != null ? event_builder.remove_method : event_info.GetRemoveMethod (nonPublic); - if (remove == null || (!nonPublic && !remove.IsPublic)) - return null; - return TypeBuilder.GetMethod (instantiation, remove); - } - - public override MethodInfo[] GetOtherMethods (bool nonPublic) - { - MethodInfo[] other = event_builder != null ? event_builder.other_methods : event_info.GetOtherMethods (nonPublic); - if (other == null) - return new MethodInfo [0]; - - ArrayList ar = new ArrayList (); - foreach (MethodInfo method in other) { - if (nonPublic || method.IsPublic) - ar.Add (TypeBuilder.GetMethod (instantiation, method)); - } - MethodInfo[] res = new MethodInfo [ar.Count]; - ar.CopyTo (res, 0); - return res; - } - - public override Type DeclaringType { - get { return instantiation; } - } - - public override string Name { - get { return event_builder != null ? event_builder.name : event_info.Name; } - } - - public override Type ReflectedType { - get { return instantiation; } - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - throw new NotSupportedException (); - } - - public override object [] GetCustomAttributes (bool inherit) - { - throw new NotSupportedException (); - } - - public override object [] GetCustomAttributes (Type attributeType, bool inherit) - { - throw new NotSupportedException (); - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs deleted file mode 100644 index a16592e68a7..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs +++ /dev/null @@ -1,241 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// System.Reflection.Emit/FieldBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001-2002 Ximian, Inc. http://www.ximian.com -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - [StructLayout (LayoutKind.Sequential)] - public sealed partial class FieldBuilder : FieldInfo { - -#pragma warning disable 169, 414 - private FieldAttributes attrs; - private Type type; - private String name; - private object def_value; - private int offset; - internal TypeBuilder typeb; - private byte[] rva_data; - private CustomAttributeBuilder[] cattrs; - private UnmanagedMarshal marshal_info; - private RuntimeFieldHandle handle; - private Type[] modReq; - private Type[] modOpt; -#pragma warning restore 169, 414 - - internal FieldBuilder (TypeBuilder tb, string fieldName, Type type, FieldAttributes attributes, Type[] modReq, Type[] modOpt) - { - if (type == null) - throw new ArgumentNullException ("type"); - - attrs = attributes; - name = fieldName; - this.type = type; - this.modReq = modReq; - this.modOpt = modOpt; - offset = -1; - typeb = tb; - - ((ModuleBuilder) tb.Module).RegisterToken (this, GetToken ().Token); - } - - public override FieldAttributes Attributes { - get { return attrs; } - } - - public override Type DeclaringType { - get { return typeb; } - } - - public override RuntimeFieldHandle FieldHandle { - get { - throw CreateNotSupportedException (); - } - } - - public override Type FieldType { - get { return type; } - } - - public override string Name { - get { return name; } - } - - public override Type ReflectedType { - get { return typeb; } - } - - public override object[] GetCustomAttributes(bool inherit) { - /* - * On MS.NET, this always returns not_supported, but we can't do this - * since there would be no way to obtain custom attributes of - * dynamically created ctors. - */ - if (typeb.is_created) - return CustomAttribute.GetCustomAttributes (this, inherit); - else - throw CreateNotSupportedException (); - } - - public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - if (typeb.is_created) - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - else - throw CreateNotSupportedException (); - } - - public override int MetadataToken { get { return ((ModuleBuilder) typeb.Module).GetToken (this); } } - - public FieldToken GetToken() { - return new FieldToken (MetadataToken, type); - } - - public override object GetValue(object obj) { - throw CreateNotSupportedException (); - } - - public override bool IsDefined( Type attributeType, bool inherit) { - throw CreateNotSupportedException (); - } - - internal override int GetFieldOffset () { - /* FIXME: */ - return 0; - } - - internal void SetRVAData (byte[] data) { - rva_data = (byte[])data.Clone (); - } - - public void SetConstant( object defaultValue) { - RejectIfCreated (); - - /*if (defaultValue.GetType() != type) - throw new ArgumentException ("Constant doesn't match field type");*/ - def_value = defaultValue; - } - - public void SetCustomAttribute (CustomAttributeBuilder customBuilder) { - RejectIfCreated (); - - if (customBuilder == null) - throw new ArgumentNullException ("customBuilder"); - - string attrname = customBuilder.Ctor.ReflectedType.FullName; - if (attrname == "System.Runtime.InteropServices.FieldOffsetAttribute") { - byte[] data = customBuilder.Data; - offset = (int)data [2]; - offset |= ((int)data [3]) << 8; - offset |= ((int)data [4]) << 16; - offset |= ((int)data [5]) << 24; - return; - } else if (attrname == "System.NonSerializedAttribute") { - attrs |= FieldAttributes.NotSerialized; - return; - } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") { - attrs |= FieldAttributes.SpecialName; - return; - } else if (attrname == "System.Runtime.InteropServices.MarshalAsAttribute") { - attrs |= FieldAttributes.HasFieldMarshal; - marshal_info = CustomAttributeBuilder.get_umarshal (customBuilder, true); - /* FIXME: check for errors */ - return; - } - if (cattrs != null) { - CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; - cattrs.CopyTo (new_array, 0); - new_array [cattrs.Length] = customBuilder; - cattrs = new_array; - } else { - cattrs = new CustomAttributeBuilder [1]; - cattrs [0] = customBuilder; - } - } - - [ComVisible (true)] - public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) { - RejectIfCreated (); - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } - - public void SetOffset( int iOffset) { - RejectIfCreated (); - if (iOffset < 0) - throw new ArgumentException ("Negative field offset is not allowed"); - offset = iOffset; - } - - public override void SetValue( object obj, object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { - throw CreateNotSupportedException (); - } - - private Exception CreateNotSupportedException () - { - return new NotSupportedException ("The invoked member is not supported in a dynamic module."); - } - - private void RejectIfCreated () - { - if (typeb.is_created) - throw new InvalidOperationException ("Unable to change after type has been created."); - } - - internal void ResolveUserTypes () { - type = TypeBuilder.ResolveUserType (type); - TypeBuilder.ResolveUserTypes (modReq); - TypeBuilder.ResolveUserTypes (modOpt); - if (marshal_info != null) - marshal_info.marshaltyperef = TypeBuilder.ResolveUserType (marshal_info.marshaltyperef); - } - - internal FieldInfo RuntimeResolve () { - // typeb.CreateType() populates this.handle - var type_handle = new RuntimeTypeHandle (typeb.CreateType () as RuntimeType); - return FieldInfo.GetFieldFromHandle (handle, type_handle); - } - - public override Module Module { - get { - return base.Module; - } - } - } -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/FieldOnTypeBuilderInst.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/FieldOnTypeBuilderInst.cs deleted file mode 100644 index a9fc114d4cd..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/FieldOnTypeBuilderInst.cs +++ /dev/null @@ -1,140 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit/FieldOnTypeBuilderInst.cs -// -// Author: -// Zoltan Varga (vargaz@gmail.com) -// -// -// Copyright (C) 2008 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Globalization; -using System.Reflection; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit -{ - /* - * This class represents a field of an instantiation of a generic type builder. - */ - [StructLayout (LayoutKind.Sequential)] - internal class FieldOnTypeBuilderInst : FieldInfo - { - #region Keep in sync with object-internals.h - internal TypeBuilderInstantiation instantiation; - internal FieldInfo fb; - #endregion - - public FieldOnTypeBuilderInst (TypeBuilderInstantiation instantiation, FieldInfo fb) { - this.instantiation = instantiation; - this.fb = fb; - } - - // - // MemberInfo members - // - - public override Type DeclaringType { - get { - return instantiation; - } - } - - public override string Name { - get { - return fb.Name; - } - } - - public override Type ReflectedType { - get { - return instantiation; - } - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - throw new NotSupportedException (); - } - - public override object [] GetCustomAttributes (bool inherit) - { - throw new NotSupportedException (); - } - - public override object [] GetCustomAttributes (Type attributeType, bool inherit) - { - throw new NotSupportedException (); - } - - public override string ToString () - { - return fb.FieldType.ToString () + " " + Name; - } - // - // FieldInfo members - // - - public override FieldAttributes Attributes { - get { - return fb.Attributes; - } - } - - public override RuntimeFieldHandle FieldHandle { - get { - throw new NotSupportedException (); - } - } - - public override int MetadataToken { - get { - throw new InvalidOperationException (); - } - } - - public override Type FieldType { - get { - throw new NotSupportedException (); - } - } - - public override object GetValue(object obj) { - throw new NotSupportedException (); - } - - public override void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { - throw new NotSupportedException (); - } - - // Called from the runtime to return the corresponding finished FieldInfo object - internal FieldInfo RuntimeResolve () { - var type = instantiation.RuntimeResolve (); - return type.GetField (fb); - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs deleted file mode 100644 index 4d78390b2e1..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs +++ /dev/null @@ -1,476 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit.GenericTypeParameterBuilder -// -// Martin Baulig (martin@ximian.com) -// -// (C) 2004 Novell, Inc. -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System.Reflection; -using System.Reflection.Emit; -using System.Collections; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Globalization; -using System.Runtime.Serialization; - -namespace System.Reflection.Emit -{ - [ComVisible (true)] - [StructLayout (LayoutKind.Sequential)] - public sealed class GenericTypeParameterBuilder : - TypeInfo - { - #region Sync with reflection.h - private TypeBuilder tbuilder; - private MethodBuilder mbuilder; - private string name; - private int index; - private Type base_type; -#pragma warning disable 414 - private Type[] iface_constraints; - private CustomAttributeBuilder[] cattrs; - private GenericParameterAttributes attrs; -#pragma warning restore - #endregion - - public void SetBaseTypeConstraint (Type baseTypeConstraint) - { - this.base_type = baseTypeConstraint ?? typeof (object); - } - - [ComVisible (true)] - public void SetInterfaceConstraints (params Type[] interfaceConstraints) - { - this.iface_constraints = interfaceConstraints; - } - - public void SetGenericParameterAttributes (GenericParameterAttributes genericParameterAttributes) - { - this.attrs = genericParameterAttributes; - } - - internal GenericTypeParameterBuilder (TypeBuilder tbuilder, - MethodBuilder mbuilder, - string name, int index) - { - this.tbuilder = tbuilder; - this.mbuilder = mbuilder; - this.name = name; - this.index = index; - } - - internal override Type InternalResolve () - { - if (mbuilder != null) - return MethodBase.GetMethodFromHandle (mbuilder.MethodHandleInternal, mbuilder.TypeBuilder.InternalResolve ().TypeHandle).GetGenericArguments () [index]; - return tbuilder.InternalResolve ().GetGenericArguments () [index]; - } - - internal override Type RuntimeResolve () - { - if (mbuilder != null) - return MethodBase.GetMethodFromHandle (mbuilder.MethodHandleInternal, mbuilder.TypeBuilder.RuntimeResolve ().TypeHandle).GetGenericArguments () [index]; - return tbuilder.RuntimeResolve ().GetGenericArguments () [index]; - } - - [ComVisible (true)] - public override bool IsSubclassOf (Type c) - { - throw not_supported (); - } - - protected override TypeAttributes GetAttributeFlagsImpl () - { - return TypeAttributes.Public; - } - - protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, - Binder binder, - CallingConventions callConvention, - Type[] types, - ParameterModifier[] modifiers) - { - throw not_supported (); - } - - [ComVisible (true)] - public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr) - { - throw not_supported (); - } - - public override EventInfo GetEvent (string name, BindingFlags bindingAttr) - { - throw not_supported (); - } - - public override EventInfo[] GetEvents () - { - throw not_supported (); - } - - public override EventInfo[] GetEvents (BindingFlags bindingAttr) - { - throw not_supported (); - } - - public override FieldInfo GetField (string name, BindingFlags bindingAttr) - { - throw not_supported (); - } - - public override FieldInfo[] GetFields (BindingFlags bindingAttr) - { - throw not_supported (); - } - - public override Type GetInterface (string name, bool ignoreCase) - { - throw not_supported (); - } - - public override Type[] GetInterfaces () - { - throw not_supported (); - } - - public override MemberInfo[] GetMembers (BindingFlags bindingAttr) - { - throw not_supported (); - } - - public override MemberInfo[] GetMember (string name, MemberTypes type, BindingFlags bindingAttr) - { - throw not_supported (); - } - - public override MethodInfo [] GetMethods (BindingFlags bindingAttr) - { - throw not_supported (); - } - - protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, - Binder binder, - CallingConventions callConvention, - Type[] types, ParameterModifier[] modifiers) - { - throw not_supported (); - } - - public override Type GetNestedType (string name, BindingFlags bindingAttr) - { - throw not_supported (); - } - - public override Type[] GetNestedTypes (BindingFlags bindingAttr) - { - throw not_supported (); - } - - public override PropertyInfo [] GetProperties (BindingFlags bindingAttr) - { - throw not_supported (); - } - - protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, - Binder binder, Type returnType, - Type[] types, - ParameterModifier[] modifiers) - { - throw not_supported (); - } - - protected override bool HasElementTypeImpl () - { - return false; - } - - public override bool IsAssignableFrom (Type c) - { - throw not_supported (); - } - - public override bool IsAssignableFrom (TypeInfo typeInfo) - { - if (typeInfo == null) - return false; - - return IsAssignableFrom (typeInfo.AsType ()); - } - - public override bool IsInstanceOfType (object o) - { - throw not_supported (); - } - - protected override bool IsArrayImpl () - { - return false; - } - - protected override bool IsByRefImpl () - { - return false; - } - - protected override bool IsCOMObjectImpl () - { - return false; - } - - protected override bool IsPointerImpl () - { - return false; - } - - protected override bool IsPrimitiveImpl () - { - return false; - } - - protected override bool IsValueTypeImpl () - { - return base_type != null ? base_type.IsValueType : false; - } - - public override bool IsSZArray { - get { - return false; - } - } - - public override object InvokeMember (string name, BindingFlags invokeAttr, - Binder binder, object target, object[] args, - ParameterModifier[] modifiers, - CultureInfo culture, string[] namedParameters) - { - throw not_supported (); - } - - public override Type GetElementType () - { - throw not_supported (); - } - - public override Type UnderlyingSystemType { - get { - return this; - } - } - - public override Assembly Assembly { - get { return tbuilder.Assembly; } - } - - public override string AssemblyQualifiedName { - get { return null; } - } - - public override Type BaseType { - get { return base_type; } - } - - public override string FullName { - get { return null; } - } - - public override Guid GUID { - get { throw not_supported (); } - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - throw not_supported (); - } - - public override object[] GetCustomAttributes (bool inherit) - { - throw not_supported (); - } - - public override object[] GetCustomAttributes (Type attributeType, bool inherit) - { - throw not_supported (); - } - - [ComVisible (true)] - public override InterfaceMapping GetInterfaceMap (Type interfaceType) - { - throw not_supported (); - } - - public override string Name { - get { return name; } - } - - public override string Namespace { - get { return null; } - } - - public override Module Module { - get { return tbuilder.Module; } - } - - public override Type DeclaringType { - get { return mbuilder != null ? mbuilder.DeclaringType : tbuilder; } - } - - public override Type ReflectedType { - get { return DeclaringType; } - } - - public override RuntimeTypeHandle TypeHandle { - get { throw not_supported (); } - } - - public override Type[] GetGenericArguments () - { - throw new InvalidOperationException (); - } - - public override Type GetGenericTypeDefinition () - { - throw new InvalidOperationException (); - } - - public override bool ContainsGenericParameters { - get { return true; } - } - - public override bool IsGenericParameter { - get { return true; } - } - - public override bool IsGenericType { - get { return false; } - } - - public override bool IsGenericTypeDefinition { - get { return false; } - } - - public override GenericParameterAttributes GenericParameterAttributes { - get { - return attrs; - } - } - - public override int GenericParameterPosition { - get { return index; } - } - - public override Type[] GetGenericParameterConstraints () - { - throw new InvalidOperationException (); - } - - public override MethodBase DeclaringMethod { - get { return mbuilder; } - } - - public void SetCustomAttribute (CustomAttributeBuilder customBuilder) - { - if (customBuilder == null) - throw new ArgumentNullException ("customBuilder"); - - if (cattrs != null) { - CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; - cattrs.CopyTo (new_array, 0); - new_array [cattrs.Length] = customBuilder; - cattrs = new_array; - } else { - cattrs = new CustomAttributeBuilder [1]; - cattrs [0] = customBuilder; - } - } - - // FIXME: "unverified implementation" - public void SetCustomAttribute (ConstructorInfo con, byte [] binaryAttribute) - { - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } - - private Exception not_supported () - { - return new NotSupportedException (); - } - - public override string ToString () - { - return name; - } - - // FIXME: - public override bool Equals (object o) - { - return base.Equals (o); - } - - // FIXME: - public override int GetHashCode () - { - return base.GetHashCode (); - } - - public override Type MakeArrayType () - { - return new ArrayType (this, 0); - } - - public override Type MakeArrayType (int rank) - { - if (rank < 1) - throw new IndexOutOfRangeException (); - return new ArrayType (this, rank); - } - - public override Type MakeByRefType () - { - return new ByRefType (this); - } - - public override Type MakeGenericType (params Type[] typeArguments) - { - throw new InvalidOperationException (Environment.GetResourceString ("Arg_NotGenericTypeDefinition")); - } - - public override Type MakePointerType () - { - return new PointerType (this); - } - - internal override bool IsUserType { - get { - return false; - } - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs deleted file mode 100644 index 4a513c5d22c..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs +++ /dev/null @@ -1,1173 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// System.Reflection.Emit/ILGenerator.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -#if MONO_FEATURE_SRE -using System; -using System.Collections.Generic; -using System.Diagnostics.SymbolStore; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - - internal struct ILExceptionBlock { - public const int CATCH = 0; - public const int FILTER = 1; - public const int FINALLY = 2; - public const int FAULT = 4; - public const int FILTER_START = -1; - - internal Type extype; - internal int type; - internal int start; - internal int len; - internal int filter_offset; - - internal void Debug () { -#if FALSE - System.Console.Write ("\ttype="+type.ToString()+" start="+start.ToString()+" len="+len.ToString()); - if (extype != null) - System.Console.WriteLine (" extype="+extype.ToString()); - else - System.Console.WriteLine (String.Empty); -#endif - } - } - internal struct ILExceptionInfo { -#pragma warning disable 169 -#pragma warning disable 414 - internal ILExceptionBlock[] handlers; - internal int start; - internal int len; - internal Label end; -#pragma warning restore 169 -#pragma warning restore 414 - - internal int NumHandlers () - { - return handlers.Length; - } - - internal void AddCatch (Type extype, int offset) - { - int i; - End (offset); - add_block (offset); - i = handlers.Length - 1; - handlers [i].type = ILExceptionBlock.CATCH; - handlers [i].start = offset; - handlers [i].extype = extype; - } - - internal void AddFinally (int offset) - { - int i; - End (offset); - add_block (offset); - i = handlers.Length - 1; - handlers [i].type = ILExceptionBlock.FINALLY; - handlers [i].start = offset; - handlers [i].extype = null; - } - - internal void AddFault (int offset) - { - int i; - End (offset); - add_block (offset); - i = handlers.Length - 1; - handlers [i].type = ILExceptionBlock.FAULT; - handlers [i].start = offset; - handlers [i].extype = null; - } - - internal void AddFilter (int offset) - { - int i; - End (offset); - add_block (offset); - i = handlers.Length - 1; - handlers [i].type = ILExceptionBlock.FILTER_START; - handlers [i].extype = null; - handlers [i].filter_offset = offset; - } - - internal void End (int offset) - { - if (handlers == null) - return; - int i = handlers.Length - 1; - if (i >= 0) - handlers [i].len = offset - handlers [i].start; - } - - internal int LastClauseType () - { - if (handlers != null) - return handlers [handlers.Length-1].type; - else - return ILExceptionBlock.CATCH; - } - - internal void PatchFilterClause (int start) - { - if (handlers != null && handlers.Length > 0) { - handlers [handlers.Length - 1].start = start; - handlers [handlers.Length - 1].type = ILExceptionBlock.FILTER; - } - } - - internal void Debug (int b) - { -#if FALSE - System.Console.WriteLine ("Handler {0} at {1}, len: {2}", b, start, len); - for (int i = 0; i < handlers.Length; ++i) - handlers [i].Debug (); -#endif - } - - void add_block (int offset) - { - if (handlers != null) { - int i = handlers.Length; - ILExceptionBlock[] new_b = new ILExceptionBlock [i + 1]; - System.Array.Copy (handlers, new_b, i); - handlers = new_b; - handlers [i].len = offset - handlers [i].start; - } else { - handlers = new ILExceptionBlock [1]; - len = offset - start; - } - } - } - - internal struct ILTokenInfo { - public MemberInfo member; - public int code_pos; - } - - internal interface TokenGenerator { - int GetToken (string str); - - int GetToken (MemberInfo member, bool create_open_instance); - - int GetToken (MethodBase method, Type[] opt_param_types); - - int GetToken (SignatureHelper helper); - } - - [StructLayout (LayoutKind.Sequential)] - public partial class ILGenerator { - private struct LabelFixup { - public int offset; // The number of bytes between pos and the - // offset of the jump - public int pos; // Where offset of the label is placed - public int label_idx; // The label to jump to - }; - - struct LabelData { - public LabelData (int addr, int maxStack) - { - this.addr = addr; - this.maxStack = maxStack; - } - - public int addr; - public int maxStack; - } - - #region Sync with reflection.h - private byte[] code; - private int code_len; - private int max_stack; - private int cur_stack; - private LocalBuilder[] locals; - private ILExceptionInfo[] ex_handlers; - private int num_token_fixups; - private object token_fixups; - #endregion - - private LabelData [] labels; - private int num_labels; - private LabelFixup[] fixups; - private int num_fixups; - internal Module module; - private int cur_block; - private Stack open_blocks; - private TokenGenerator token_gen; - - const int defaultFixupSize = 4; - const int defaultLabelsSize = 4; - const int defaultExceptionStackSize = 2; - - List<SequencePointList> sequencePointLists; - SequencePointList currentSequence; - - internal ILGenerator (Module m, TokenGenerator token_gen, int size) - { - if (size < 0) - size = 128; - code = new byte [size]; - module = m; - this.token_gen = token_gen; - } - - private void make_room (int nbytes) - { - if (code_len + nbytes < code.Length) - return; - byte[] new_code = new byte [(code_len + nbytes) * 2 + 128]; - System.Array.Copy (code, 0, new_code, 0, code.Length); - code = new_code; - } - - private void emit_int (int val) - { - code [code_len++] = (byte) (val & 0xFF); - code [code_len++] = (byte) ((val >> 8) & 0xFF); - code [code_len++] = (byte) ((val >> 16) & 0xFF); - code [code_len++] = (byte) ((val >> 24) & 0xFF); - } - - /* change to pass by ref to avoid copy */ - private void ll_emit (OpCode opcode) - { - /* - * there is already enough room allocated in code. - */ - if (opcode.Size == 2) - code [code_len++] = (byte)(opcode.Value >> 8); - code [code_len++] = (byte)(opcode.Value & 0xff); - /* - * We should probably keep track of stack needs here. - * Or we may want to run the verifier on the code before saving it - * (this may be needed anyway when the ILGenerator is not used...). - */ - switch (opcode.StackBehaviourPush) { - case StackBehaviour.Push1: - case StackBehaviour.Pushi: - case StackBehaviour.Pushi8: - case StackBehaviour.Pushr4: - case StackBehaviour.Pushr8: - case StackBehaviour.Pushref: - case StackBehaviour.Varpush: /* again we are conservative and assume it pushes 1 */ - cur_stack ++; - break; - case StackBehaviour.Push1_push1: - cur_stack += 2; - break; - } - if (max_stack < cur_stack) - max_stack = cur_stack; - - /* - * Note that we adjust for the pop behaviour _after_ setting max_stack. - */ - switch (opcode.StackBehaviourPop) { - case StackBehaviour.Varpop: - break; /* we are conservative and assume it doesn't decrease the stack needs */ - case StackBehaviour.Pop1: - case StackBehaviour.Popi: - case StackBehaviour.Popref: - cur_stack --; - break; - case StackBehaviour.Pop1_pop1: - case StackBehaviour.Popi_pop1: - case StackBehaviour.Popi_popi: - case StackBehaviour.Popi_popi8: - case StackBehaviour.Popi_popr4: - case StackBehaviour.Popi_popr8: - case StackBehaviour.Popref_pop1: - case StackBehaviour.Popref_popi: - cur_stack -= 2; - break; - case StackBehaviour.Popi_popi_popi: - case StackBehaviour.Popref_popi_popi: - case StackBehaviour.Popref_popi_popi8: - case StackBehaviour.Popref_popi_popr4: - case StackBehaviour.Popref_popi_popr8: - case StackBehaviour.Popref_popi_popref: - cur_stack -= 3; - break; - } - } - - private static int target_len (OpCode opcode) - { - if (opcode.OperandType == OperandType.InlineBrTarget) - return 4; - return 1; - } - - private void InternalEndClause () - { - switch (ex_handlers [cur_block].LastClauseType ()) { - case ILExceptionBlock.CATCH: - case ILExceptionBlock.FILTER: - case ILExceptionBlock.FILTER_START: - // how could we optimize code size here? - Emit (OpCodes.Leave, ex_handlers [cur_block].end); - break; - case ILExceptionBlock.FAULT: - case ILExceptionBlock.FINALLY: - Emit (OpCodes.Endfinally); - break; - } - } - - public virtual void BeginCatchBlock (Type exceptionType) - { - if (open_blocks == null) - open_blocks = new Stack (defaultExceptionStackSize); - - if (open_blocks.Count <= 0) - throw new NotSupportedException ("Not in an exception block"); - if (exceptionType != null && exceptionType.IsUserType) - throw new NotSupportedException ("User defined subclasses of System.Type are not yet supported."); - if (ex_handlers [cur_block].LastClauseType () == ILExceptionBlock.FILTER_START) { - if (exceptionType != null) - throw new ArgumentException ("Do not supply an exception type for filter clause"); - Emit (OpCodes.Endfilter); - ex_handlers [cur_block].PatchFilterClause (code_len); - } else { - InternalEndClause (); - ex_handlers [cur_block].AddCatch (exceptionType, code_len); - } - - cur_stack = 1; // the exception object is on the stack by default - if (max_stack < cur_stack) - max_stack = cur_stack; - - //System.Console.WriteLine ("Begin catch Block: {0} {1}",exceptionType.ToString(), max_stack); - } - - public virtual void BeginExceptFilterBlock () - { - if (open_blocks == null) - open_blocks = new Stack (defaultExceptionStackSize); - - if (open_blocks.Count <= 0) - throw new NotSupportedException ("Not in an exception block"); - InternalEndClause (); - - ex_handlers [cur_block].AddFilter (code_len); - } - - public virtual Label BeginExceptionBlock () - { - //System.Console.WriteLine ("Begin Block"); - if (open_blocks == null) - open_blocks = new Stack (defaultExceptionStackSize); - - if (ex_handlers != null) { - cur_block = ex_handlers.Length; - ILExceptionInfo[] new_ex = new ILExceptionInfo [cur_block + 1]; - System.Array.Copy (ex_handlers, new_ex, cur_block); - ex_handlers = new_ex; - } else { - ex_handlers = new ILExceptionInfo [1]; - cur_block = 0; - } - open_blocks.Push (cur_block); - ex_handlers [cur_block].start = code_len; - return ex_handlers [cur_block].end = DefineLabel (); - } - - public virtual void BeginFaultBlock() - { - if (open_blocks == null) - open_blocks = new Stack (defaultExceptionStackSize); - - if (open_blocks.Count <= 0) - throw new NotSupportedException ("Not in an exception block"); - - if (ex_handlers [cur_block].LastClauseType () == ILExceptionBlock.FILTER_START) { - Emit (OpCodes.Leave, ex_handlers [cur_block].end); - ex_handlers [cur_block].PatchFilterClause (code_len); - } - - InternalEndClause (); - //System.Console.WriteLine ("Begin fault Block"); - ex_handlers [cur_block].AddFault (code_len); - } - - public virtual void BeginFinallyBlock() - { - if (open_blocks == null) - open_blocks = new Stack (defaultExceptionStackSize); - - if (open_blocks.Count <= 0) - throw new NotSupportedException ("Not in an exception block"); - - InternalEndClause (); - - if (ex_handlers [cur_block].LastClauseType () == ILExceptionBlock.FILTER_START) { - Emit (OpCodes.Leave, ex_handlers [cur_block].end); - ex_handlers [cur_block].PatchFilterClause (code_len); - } - - //System.Console.WriteLine ("Begin finally Block"); - ex_handlers [cur_block].AddFinally (code_len); - } - - public virtual void BeginScope () - { } - - public virtual LocalBuilder DeclareLocal (Type localType) - { - return DeclareLocal (localType, false); - } - - - public virtual LocalBuilder DeclareLocal (Type localType, bool pinned) - { - if (localType == null) - throw new ArgumentNullException ("localType"); - if (localType.IsUserType) - throw new NotSupportedException ("User defined subclasses of System.Type are not yet supported."); - LocalBuilder res = new LocalBuilder (localType, this); - res.is_pinned = pinned; - - if (locals != null) { - LocalBuilder[] new_l = new LocalBuilder [locals.Length + 1]; - System.Array.Copy (locals, new_l, locals.Length); - new_l [locals.Length] = res; - locals = new_l; - } else { - locals = new LocalBuilder [1]; - locals [0] = res; - } - res.position = (ushort)(locals.Length - 1); - return res; - } - - public virtual Label DefineLabel () - { - if (labels == null) - labels = new LabelData [defaultLabelsSize]; - else if (num_labels >= labels.Length) { - LabelData [] t = new LabelData [labels.Length * 2]; - Array.Copy (labels, t, labels.Length); - labels = t; - } - - labels [num_labels] = new LabelData (-1, 0); - - return new Label (num_labels++); - } - - public virtual void Emit (OpCode opcode) - { - make_room (2); - ll_emit (opcode); - } - - public virtual void Emit (OpCode opcode, Byte arg) - { - make_room (3); - ll_emit (opcode); - code [code_len++] = arg; - } - - [ComVisible (true)] - public virtual void Emit (OpCode opcode, ConstructorInfo con) - { - int token = token_gen.GetToken (con, true); - make_room (6); - ll_emit (opcode); - emit_int (token); - - if (opcode.StackBehaviourPop == StackBehaviour.Varpop) - cur_stack -= con.GetParametersCount (); - } - - public virtual void Emit (OpCode opcode, double arg) - { - byte[] s = System.BitConverter.GetBytes (arg); - make_room (10); - ll_emit (opcode); - if (BitConverter.IsLittleEndian){ - System.Array.Copy (s, 0, code, code_len, 8); - code_len += 8; - } else { - code [code_len++] = s [7]; - code [code_len++] = s [6]; - code [code_len++] = s [5]; - code [code_len++] = s [4]; - code [code_len++] = s [3]; - code [code_len++] = s [2]; - code [code_len++] = s [1]; - code [code_len++] = s [0]; - } - } - - public virtual void Emit (OpCode opcode, FieldInfo field) - { - int token = token_gen.GetToken (field, true); - make_room (6); - ll_emit (opcode); - emit_int (token); - } - - public virtual void Emit (OpCode opcode, Int16 arg) - { - make_room (4); - ll_emit (opcode); - code [code_len++] = (byte) (arg & 0xFF); - code [code_len++] = (byte) ((arg >> 8) & 0xFF); - } - - public virtual void Emit (OpCode opcode, int arg) - { - make_room (6); - ll_emit (opcode); - emit_int (arg); - } - - public virtual void Emit (OpCode opcode, long arg) - { - make_room (10); - ll_emit (opcode); - code [code_len++] = (byte) (arg & 0xFF); - code [code_len++] = (byte) ((arg >> 8) & 0xFF); - code [code_len++] = (byte) ((arg >> 16) & 0xFF); - code [code_len++] = (byte) ((arg >> 24) & 0xFF); - code [code_len++] = (byte) ((arg >> 32) & 0xFF); - code [code_len++] = (byte) ((arg >> 40) & 0xFF); - code [code_len++] = (byte) ((arg >> 48) & 0xFF); - code [code_len++] = (byte) ((arg >> 56) & 0xFF); - } - - public virtual void Emit (OpCode opcode, Label label) - { - int tlen = target_len (opcode); - make_room (6); - ll_emit (opcode); - if (cur_stack > labels [label.m_label].maxStack) - labels [label.m_label].maxStack = cur_stack; - - if (fixups == null) - fixups = new LabelFixup [defaultFixupSize]; - else if (num_fixups >= fixups.Length) { - LabelFixup[] newf = new LabelFixup [fixups.Length * 2]; - System.Array.Copy (fixups, newf, fixups.Length); - fixups = newf; - } - fixups [num_fixups].offset = tlen; - fixups [num_fixups].pos = code_len; - fixups [num_fixups].label_idx = label.m_label; - num_fixups++; - code_len += tlen; - - } - - public virtual void Emit (OpCode opcode, Label[] labels) - { - if (labels == null) - throw new ArgumentNullException ("labels"); - - /* opcode needs to be switch. */ - int count = labels.Length; - make_room (6 + count * 4); - ll_emit (opcode); - - for (int i = 0; i < count; ++i) - if (cur_stack > this.labels [labels [i].m_label].maxStack) - this.labels [labels [i].m_label].maxStack = cur_stack; - - emit_int (count); - if (fixups == null) - fixups = new LabelFixup [defaultFixupSize + count]; - else if (num_fixups + count >= fixups.Length) { - LabelFixup[] newf = new LabelFixup [count + fixups.Length * 2]; - System.Array.Copy (fixups, newf, fixups.Length); - fixups = newf; - } - - // ECMA 335, Partition III, p94 (7-10) - // - // The switch instruction implements a jump table. The format of - // the instruction is an unsigned int32 representing the number of targets N, - // followed by N int32 values specifying jump targets: these targets are - // represented as offsets (positive or negative) from the beginning of the - // instruction following this switch instruction. - // - // We must make sure it gets an offset from the *end* of the last label - // (eg, the beginning of the instruction following this). - // - // remaining is the number of bytes from the current instruction to the - // instruction that will be emitted. - - for (int i = 0, remaining = count * 4; i < count; ++i, remaining -= 4) { - fixups [num_fixups].offset = remaining; - fixups [num_fixups].pos = code_len; - fixups [num_fixups].label_idx = labels [i].m_label; - num_fixups++; - code_len += 4; - } - } - - public virtual void Emit (OpCode opcode, LocalBuilder local) - { - if (local == null) - throw new ArgumentNullException ("local"); - if (local.ilgen != this) - throw new ArgumentException ("Trying to emit a local from a different ILGenerator."); - - uint pos = local.position; - bool load_addr = false; - bool is_store = false; - bool is_load = false; - make_room (6); - - /* inline the code from ll_emit () to optimize il code size */ - if (opcode.StackBehaviourPop == StackBehaviour.Pop1) { - cur_stack --; - is_store = true; - } else if (opcode.StackBehaviourPush == StackBehaviour.Push1 || opcode.StackBehaviourPush == StackBehaviour.Pushi) { - cur_stack++; - is_load = true; - if (cur_stack > max_stack) - max_stack = cur_stack; - load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi; - } - if (load_addr) { - if (pos < 256) { - code [code_len++] = (byte)0x12; - code [code_len++] = (byte)pos; - } else { - code [code_len++] = (byte)0xfe; - code [code_len++] = (byte)0x0d; - code [code_len++] = (byte)(pos & 0xff); - code [code_len++] = (byte)((pos >> 8) & 0xff); - } - } else { - if (is_store) { - if (pos < 4) { - code [code_len++] = (byte)(0x0a + pos); - } else if (pos < 256) { - code [code_len++] = (byte)0x13; - code [code_len++] = (byte)pos; - } else { - code [code_len++] = (byte)0xfe; - code [code_len++] = (byte)0x0e; - code [code_len++] = (byte)(pos & 0xff); - code [code_len++] = (byte)((pos >> 8) & 0xff); - } - } else if (is_load) { - if (pos < 4) { - code [code_len++] = (byte)(0x06 + pos); - } else if (pos < 256) { - code [code_len++] = (byte)0x11; - code [code_len++] = (byte)pos; - } else { - code [code_len++] = (byte)0xfe; - code [code_len++] = (byte)0x0c; - code [code_len++] = (byte)(pos & 0xff); - code [code_len++] = (byte)((pos >> 8) & 0xff); - } - } else { - ll_emit (opcode); - } - } - } - - public virtual void Emit (OpCode opcode, MethodInfo meth) - { - if (meth == null) - throw new ArgumentNullException ("meth"); - - // For compatibility with MS - if ((meth is DynamicMethod) && ((opcode == OpCodes.Ldftn) || (opcode == OpCodes.Ldvirtftn) || (opcode == OpCodes.Ldtoken))) - throw new ArgumentException ("Ldtoken, Ldftn and Ldvirtftn OpCodes cannot target DynamicMethods."); - - int token = token_gen.GetToken (meth, true); - make_room (6); - ll_emit (opcode); - Type declaringType = meth.DeclaringType; - emit_int (token); - if (meth.ReturnType != typeof (void)) - cur_stack ++; - - if (opcode.StackBehaviourPop == StackBehaviour.Varpop) - cur_stack -= meth.GetParametersCount (); - } - - private void Emit (OpCode opcode, MethodInfo method, int token) - { - make_room (6); - ll_emit (opcode); - emit_int (token); - if (method.ReturnType != typeof (void)) - cur_stack ++; - - if (opcode.StackBehaviourPop == StackBehaviour.Varpop) - cur_stack -= method.GetParametersCount (); - } - - [CLSCompliant(false)] - public void Emit (OpCode opcode, sbyte arg) - { - make_room (3); - ll_emit (opcode); - code [code_len++] = (byte)arg; - } - - public virtual void Emit (OpCode opcode, SignatureHelper signature) - { - int token = token_gen.GetToken (signature); - make_room (6); - ll_emit (opcode); - emit_int (token); - } - - public virtual void Emit (OpCode opcode, float arg) - { - byte[] s = System.BitConverter.GetBytes (arg); - make_room (6); - ll_emit (opcode); - if (BitConverter.IsLittleEndian){ - System.Array.Copy (s, 0, code, code_len, 4); - code_len += 4; - } else { - code [code_len++] = s [3]; - code [code_len++] = s [2]; - code [code_len++] = s [1]; - code [code_len++] = s [0]; - } - } - - public virtual void Emit (OpCode opcode, string str) - { - int token = token_gen.GetToken (str); - make_room (6); - ll_emit (opcode); - emit_int (token); - } - - public virtual void Emit (OpCode opcode, Type cls) - { - if (cls != null && cls.IsByRef) - throw new ArgumentException ("Cannot get TypeToken for a ByRef type."); - - make_room (6); - ll_emit (opcode); - int token = token_gen.GetToken (cls, opcode != OpCodes.Ldtoken); - emit_int (token); - } - - // FIXME: vararg methods are not supported - public virtual void EmitCall (OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) - { - if (methodInfo == null) - throw new ArgumentNullException ("methodInfo"); - short value = opcode.Value; - if (!(value == OpCodes.Call.Value || value == OpCodes.Callvirt.Value)) - throw new NotSupportedException ("Only Call and CallVirt are allowed"); - if ((methodInfo.CallingConvention & CallingConventions.VarArgs) == 0) - optionalParameterTypes = null; - if (optionalParameterTypes != null){ - if ((methodInfo.CallingConvention & CallingConventions.VarArgs) == 0){ - throw new InvalidOperationException ("Method is not VarArgs method and optional types were passed"); - } - - int token = token_gen.GetToken (methodInfo, optionalParameterTypes); - Emit (opcode, methodInfo, token); - return; - } - Emit (opcode, methodInfo); - } - - public virtual void EmitCalli (OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) - { - // GetMethodSigHelper expects a ModuleBuilder or null, and module might be - // a normal module when using dynamic methods. - SignatureHelper helper = SignatureHelper.GetMethodSigHelper (module as ModuleBuilder, 0, unmanagedCallConv, returnType, parameterTypes); - Emit (opcode, helper); - } - - public virtual void EmitCalli (OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) - { - if (optionalParameterTypes != null) - throw new NotImplementedException (); - - SignatureHelper helper = SignatureHelper.GetMethodSigHelper (module as ModuleBuilder, callingConvention, 0, returnType, parameterTypes); - Emit (opcode, helper); - } - - static Type GetConsoleType () - { - return Type.GetType ("System.Console, System.Console", throwOnError: true); - } - - public virtual void EmitWriteLine (FieldInfo fld) - { - if (fld == null) - throw new ArgumentNullException ("fld"); - - // The MS implementation does not check for valuetypes here but it - // should. Also, it should check that if the field is not static, - // then it is a member of this type. - if (fld.IsStatic) - Emit (OpCodes.Ldsfld, fld); - else { - Emit (OpCodes.Ldarg_0); - Emit (OpCodes.Ldfld, fld); - } - Emit (OpCodes.Call, GetConsoleType ().GetMethod ("WriteLine", new Type[1] { fld.FieldType })); - } - - public virtual void EmitWriteLine (LocalBuilder localBuilder) - { - if (localBuilder == null) - throw new ArgumentNullException ("localBuilder"); - if (localBuilder.LocalType is TypeBuilder) - throw new ArgumentException ("Output streams do not support TypeBuilders."); - // The MS implementation does not check for valuetypes here but it - // should. - Emit (OpCodes.Ldloc, localBuilder); - Emit (OpCodes.Call, GetConsoleType ().GetMethod ("WriteLine", new Type[1] { localBuilder.LocalType })); - } - - public virtual void EmitWriteLine (string value) - { - Emit (OpCodes.Ldstr, value); - Emit (OpCodes.Call, GetConsoleType ().GetMethod ("WriteLine", new Type[1] { typeof(string)})); - } - - public virtual void EndExceptionBlock () - { - if (open_blocks == null) - open_blocks = new Stack (defaultExceptionStackSize); - - if (open_blocks.Count <= 0) - throw new NotSupportedException ("Not in an exception block"); - - if (ex_handlers [cur_block].LastClauseType () == ILExceptionBlock.FILTER_START) - throw new InvalidOperationException ("Incorrect code generation for exception block."); - - InternalEndClause (); - MarkLabel (ex_handlers [cur_block].end); - ex_handlers [cur_block].End (code_len); - ex_handlers [cur_block].Debug (cur_block); - //System.Console.WriteLine ("End Block {0} (handlers: {1})", cur_block, ex_handlers [cur_block].NumHandlers ()); - open_blocks.Pop (); - if (open_blocks.Count > 0) - cur_block = (int)open_blocks.Peek (); - //Console.WriteLine ("curblock restored to {0}", cur_block); - //throw new NotImplementedException (); - } - - public virtual void EndScope () - { } - - public virtual void MarkLabel (Label loc) - { - if (loc.m_label < 0 || loc.m_label >= num_labels) - throw new System.ArgumentException ("The label is not valid"); - if (labels [loc.m_label].addr >= 0) - throw new System.ArgumentException ("The label was already defined"); - labels [loc.m_label].addr = code_len; - if (labels [loc.m_label].maxStack > cur_stack) - cur_stack = labels [loc.m_label].maxStack; - } - - public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine, - int startColumn, int endLine, int endColumn) - { - if (currentSequence == null || currentSequence.Document != document) { - if (sequencePointLists == null) - sequencePointLists = new List<SequencePointList> (); - currentSequence = new SequencePointList (document); - sequencePointLists.Add (currentSequence); - } - - currentSequence.AddSequencePoint (code_len, startLine, startColumn, endLine, endColumn); - } - -/* - internal void GenerateDebugInfo (ISymbolWriter symbolWriter) - { - if (sequencePointLists != null) { - SequencePointList first = (SequencePointList) sequencePointLists [0]; - SequencePointList last = (SequencePointList) sequencePointLists [sequencePointLists.Count - 1]; - symbolWriter.SetMethodSourceRange (first.Document, first.StartLine, first.StartColumn, last.Document, last.EndLine, last.EndColumn); - - foreach (SequencePointList list in sequencePointLists) - symbolWriter.DefineSequencePoints (list.Document, list.GetOffsets(), list.GetLines(), list.GetColumns(), list.GetEndLines(), list.GetEndColumns()); - - if (locals != null) { - foreach (LocalBuilder local in locals) { - if (local.Name != null && local.Name.Length > 0) { - SignatureHelper sighelper = SignatureHelper.GetLocalVarSigHelper (module as ModuleBuilder); - sighelper.AddArgument (local.LocalType); - byte[] signature = sighelper.GetSignature (); - symbolWriter.DefineLocalVariable (local.Name, FieldAttributes.Public, signature, SymAddressKind.ILOffset, local.position, 0, 0, local.StartOffset, local.EndOffset); - } - } - } - sequencePointLists = null; - } - } -*/ - - internal bool HasDebugInfo - { - get { return sequencePointLists != null; } - } - - public virtual void ThrowException (Type excType) - { - if (excType == null) - throw new ArgumentNullException ("excType"); - if (! ((excType == typeof (Exception)) || - excType.IsSubclassOf (typeof (Exception)))) - throw new ArgumentException ("Type should be an exception type", "excType"); - ConstructorInfo ctor = excType.GetConstructor (Type.EmptyTypes); - if (ctor == null) - throw new ArgumentException ("Type should have a default constructor", "excType"); - Emit (OpCodes.Newobj, ctor); - Emit (OpCodes.Throw); - } - - // FIXME: "Not implemented" - public virtual void UsingNamespace (String usingNamespace) - { - throw new NotImplementedException (); - } - - internal void label_fixup (MethodBase mb) - { - for (int i = 0; i < num_fixups; ++i) { - if (labels [fixups [i].label_idx].addr < 0) - throw new ArgumentException (string.Format ("Label #{0} is not marked in method `{1}'", fixups [i].label_idx + 1, mb.Name)); - // Diff is the offset from the end of the jump instruction to the address of the label - int diff = labels [fixups [i].label_idx].addr - (fixups [i].pos + fixups [i].offset); - if (fixups [i].offset == 1) { - code [fixups [i].pos] = (byte)((sbyte) diff); - } else { - int old_cl = code_len; - code_len = fixups [i].pos; - emit_int (diff); - code_len = old_cl; - } - } - } - - // Used by DynamicILGenerator and MethodBuilder.SetMethodBody - internal void SetCode (byte[] code, int max_stack) { - // Make a copy to avoid possible security problems - this.code = (byte[])code.Clone (); - this.code_len = code.Length; - this.max_stack = max_stack; - this.cur_stack = 0; - } - - internal unsafe void SetCode (byte *code, int code_size, int max_stack) { - // Make a copy to avoid possible security problems - this.code = new byte [code_size]; - for (int i = 0; i < code_size; ++i) - this.code [i] = code [i]; - this.code_len = code_size; - this.max_stack = max_stack; - this.cur_stack = 0; - } - - internal TokenGenerator TokenGenerator { - get { - return token_gen; - } - } - - public virtual int ILOffset { - get { return code_len; } - } - } - - internal class SequencePointList - { - ISymbolDocumentWriter doc; - SequencePoint[] points; - int count; - const int arrayGrow = 10; - - public SequencePointList (ISymbolDocumentWriter doc) - { - this.doc = doc; - } - - public ISymbolDocumentWriter Document { - get { return doc; } - } - - public int[] GetOffsets() - { - int[] data = new int [count]; - for (int n=0; n<count; n++) data [n] = points[n].Offset; - return data; - } - public int[] GetLines() - { - int[] data = new int [count]; - for (int n=0; n<count; n++) data [n] = points[n].Line; - return data; - } - public int[] GetColumns() - { - int[] data = new int [count]; - for (int n=0; n<count; n++) data [n] = points[n].Col; - return data; - } - public int[] GetEndLines() - { - int[] data = new int [count]; - for (int n=0; n<count; n++) data [n] = points[n].EndLine; - return data; - } - public int[] GetEndColumns() - { - int[] data = new int [count]; - for (int n=0; n<count; n++) data [n] = points[n].EndCol; - return data; - } - public int StartLine { - get { return points[0].Line; } - } - public int EndLine { - get { return points[count - 1].Line; } - } - public int StartColumn { - get { return points[0].Col; } - } - public int EndColumn { - get { return points[count - 1].Col; } - } - - public void AddSequencePoint (int offset, int line, int col, int endLine, int endCol) - { - SequencePoint s = new SequencePoint (); - s.Offset = offset; - s.Line = line; - s.Col = col; - s.EndLine = endLine; - s.EndCol = endCol; - - if (points == null) { - points = new SequencePoint [arrayGrow]; - } else if (count >= points.Length) { - SequencePoint[] temp = new SequencePoint [count + arrayGrow]; - Array.Copy (points, temp, points.Length); - points = temp; - } - - points [count] = s; - count++; - } - } - - struct SequencePoint { - public int Offset; - public int Line; - public int Col; - public int EndLine; - public int EndCol; - } - - class Stack - { - Object[] _array; - int _size; - int _version; - - private const int _defaultCapacity = 10; - - public Stack() - { - _array = new Object[_defaultCapacity]; - _size = 0; - _version = 0; - } - - public Stack(int initialCapacity) - { - if (initialCapacity < 0) - throw new ArgumentOutOfRangeException(nameof(initialCapacity), SR.ArgumentOutOfRange_NeedNonNegNum); - - if (initialCapacity < _defaultCapacity) - initialCapacity = _defaultCapacity; - _array = new Object[initialCapacity]; - _size = 0; - _version = 0; - } - - public virtual int Count - { - get - { - return _size; - } - } - - public virtual Object Peek() - { - if (_size == 0) - throw new InvalidOperationException (); - - return _array[_size - 1]; - } - - public virtual Object Pop() - { - if (_size == 0) - throw new InvalidOperationException (); - - _version++; - Object obj = _array[--_size]; - _array[_size] = null; - return obj; - } - - public virtual void Push(Object obj) - { - if (_size == _array.Length) - { - Object[] newArray = new Object[2 * _array.Length]; - Array.Copy(_array, 0, newArray, 0, _size); - _array = newArray; - } - _array[_size++] = obj; - _version++; - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/LocalBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/LocalBuilder.Mono.cs deleted file mode 100644 index 583600a2575..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/LocalBuilder.Mono.cs +++ /dev/null @@ -1,111 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// System.Reflection.Emit/LocalBuilder.cs -// -// Authors: -// Paolo Molaro (lupus@ximian.com) -// Martin Baulig (martin@gnome.org) -// Miguel de Icaza (miguel@ximian.com) -// -// (C) 2001, 2002 Ximian, Inc. http://www.ximian.com -// - -using System; -using System.Reflection; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Diagnostics.SymbolStore; - -namespace System.Reflection.Emit { - [StructLayout (LayoutKind.Sequential)] - public sealed partial class LocalBuilder : LocalVariableInfo - { - // Needs to have the same layout as RuntimeLocalVariableInfo - #region Sync with reflection.h - internal Type type; - internal bool is_pinned; - internal ushort position; - private string name; - #endregion - - internal ILGenerator ilgen; - int startOffset; - int endOffset; - - internal LocalBuilder (Type t, ILGenerator ilgen) - { - this.type = t; - this.ilgen = ilgen; - } - - public void SetLocalSymInfo (string name, int startOffset, int endOffset) - { - this.name = name; - this.startOffset = startOffset; - this.endOffset = endOffset; - } - - public void SetLocalSymInfo (string name) - { - SetLocalSymInfo (name, 0, 0); - } - - public override Type LocalType - { - get { - return type; - } - } - - public override bool IsPinned - { - get { - return is_pinned; - } - } - - public override int LocalIndex - { - get { - return position; - } - } - - internal string Name { - get { return name; } - } - - internal int StartOffset { - get { return startOffset; } - } - - internal int EndOffset { - get { return endOffset; } - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs deleted file mode 100644 index 8d2caaf23dc..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs +++ /dev/null @@ -1,743 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit/MethodBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Diagnostics.SymbolStore; -using System.Collections.Generic; - -namespace System.Reflection.Emit -{ - [StructLayout (LayoutKind.Sequential)] - public sealed partial class MethodBuilder : MethodInfo - { -#pragma warning disable 169, 414 - private RuntimeMethodHandle mhandle; - private Type rtype; - internal Type[] parameters; - private MethodAttributes attrs; /* It's used directly by MCS */ - private MethodImplAttributes iattrs; - private string name; - private int table_idx; - private byte[] code; - private ILGenerator ilgen; - private TypeBuilder type; - internal ParameterBuilder[] pinfo; - private CustomAttributeBuilder[] cattrs; - private MethodInfo[] override_methods; - private string pi_dll; - private string pi_entry; - private CharSet charset; - private uint extra_flags; /* this encodes set_last_error etc */ - private CallingConvention native_cc; - private CallingConventions call_conv; - private bool init_locals = true; - private IntPtr generic_container; - internal GenericTypeParameterBuilder[] generic_params; - private Type[] returnModReq; - private Type[] returnModOpt; - private Type[][] paramModReq; - private Type[][] paramModOpt; - private object permissions; -#pragma warning restore 169, 414 - RuntimeMethodInfo created; - - internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt) - { - this.name = name; - this.attrs = attributes; - this.call_conv = callingConvention; - this.rtype = returnType; - this.returnModReq = returnModReq; - this.returnModOpt = returnModOpt; - this.paramModReq = paramModReq; - this.paramModOpt = paramModOpt; - // The MSDN docs does not specify this, but the MS MethodBuilder - // appends a HasThis flag if the method is not static - if ((attributes & MethodAttributes.Static) == 0) - this.call_conv |= CallingConventions.HasThis; - if (parameterTypes != null) { - for (int i = 0; i < parameterTypes.Length; ++i) - if (parameterTypes [i] == null) - throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes"); - - this.parameters = new Type [parameterTypes.Length]; - System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length); - } - type = tb; - table_idx = get_next_table_index (this, 0x06, 1); - - ((ModuleBuilder)tb.Module).RegisterToken (this, GetToken ().Token); - } - - internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, - CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt, - String dllName, String entryName, CallingConvention nativeCConv, CharSet nativeCharset) - : this (tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt) - { - pi_dll = dllName; - pi_entry = entryName; - native_cc = nativeCConv; - charset = nativeCharset; - } - - public override bool ContainsGenericParameters { - get { throw new NotSupportedException (); } - } - - public bool InitLocals { - get {return init_locals;} - set {init_locals = value;} - } - - internal TypeBuilder TypeBuilder { - get {return type;} - } - - public override RuntimeMethodHandle MethodHandle { - get { - throw NotSupported (); - } - } - - internal RuntimeMethodHandle MethodHandleInternal { - get { - return mhandle; - } - } - - public override Type ReturnType { - get { return rtype; } - } - - public override Type ReflectedType { - get { return type; } - } - - public override Type DeclaringType { - get { return type; } - } - - public override string Name { - get { return name; } - } - - public override MethodAttributes Attributes { - get { return attrs; } - } - - public override ICustomAttributeProvider ReturnTypeCustomAttributes { - get { return null; } - } - - public override CallingConventions CallingConvention { - get { return call_conv; } - } - - // FIXME: "Not implemented" - public string Signature { - get { - throw new NotImplementedException (); - } - } - - /* Used by mcs */ - internal bool BestFitMapping { - set { - extra_flags = (uint) ((extra_flags & ~0x30) | (uint)(value ? 0x10 : 0x20)); - } - } - - /* Used by mcs */ - internal bool ThrowOnUnmappableChar { - set { - extra_flags = (uint) ((extra_flags & ~0x3000) | (uint)(value ? 0x1000 : 0x2000)); - } - } - - /* Used by mcs */ - internal bool ExactSpelling { - set { - extra_flags = (uint) ((extra_flags & ~0x01) | (uint)(value ? 0x01 : 0x00)); - } - } - - /* Used by mcs */ - internal bool SetLastError { - set { - extra_flags = (uint) ((extra_flags & ~0x40) | (uint)(value ? 0x40 : 0x00)); - } - } - - public MethodToken GetToken() - { - return new MethodToken(0x06000000 | table_idx); - } - - public override MethodInfo GetBaseDefinition() - { - return this; - } - - public override MethodImplAttributes GetMethodImplementationFlags() - { - return iattrs; - } - - public override ParameterInfo[] GetParameters() - { - if (!type.is_created) - throw NotSupported (); - - return GetParametersInternal (); - } - - internal override ParameterInfo[] GetParametersInternal () - { - if (parameters == null) - return null; - - ParameterInfo[] retval = new ParameterInfo [parameters.Length]; - for (int i = 0; i < parameters.Length; i++) { - retval [i] = RuntimeParameterInfo.New (pinfo?[i + 1], parameters [i], this, i + 1); - } - return retval; - } - - internal override int GetParametersCount () - { - if (parameters == null) - return 0; - - return parameters.Length; - } - - internal override Type GetParameterType (int pos) { - return parameters [pos]; - } - - internal MethodBase RuntimeResolve () { - return type.RuntimeResolve ().GetMethod (this); - } - - public Module GetModule () - { - return type.Module; - } - - public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - throw NotSupported (); - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - throw NotSupported (); - } - - public override object[] GetCustomAttributes (bool inherit) - { - /* - * On MS.NET, this always returns not_supported, but we can't do this - * since there would be no way to obtain custom attributes of - * dynamically created ctors. - */ - if (type.is_created) - return CustomAttribute.GetCustomAttributes (this, inherit); - else - throw NotSupported (); - } - - public override object[] GetCustomAttributes (Type attributeType, bool inherit) - { - if (type.is_created) - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - else - throw NotSupported (); - } - - public ILGenerator GetILGenerator () - { - return GetILGenerator (64); - } - - public ILGenerator GetILGenerator (int size) - { - if (((iattrs & MethodImplAttributes.CodeTypeMask) != - MethodImplAttributes.IL) || - ((iattrs & MethodImplAttributes.ManagedMask) != - MethodImplAttributes.Managed)) - throw new InvalidOperationException ("Method body should not exist."); - if (ilgen != null) - return ilgen; - ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size); - return ilgen; - } - - public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName) - { - RejectIfCreated (); - - // - // Extension: Mono allows position == 0 for the return attribute - // - if ((position < 0) || parameters == null || (position > parameters.Length)) - throw new ArgumentOutOfRangeException ("position"); - - ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName); - if (pinfo == null) - pinfo = new ParameterBuilder [parameters.Length + 1]; - pinfo [position] = pb; - return pb; - } - - internal void check_override () - { - if (override_methods != null) { - foreach (var m in override_methods) { - if (m.IsVirtual && !IsVirtual) - throw new TypeLoadException (String.Format("Method '{0}' override '{1}' but it is not virtual", name, m)); - } - } - } - - internal void fixup () - { - if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) { - // do not allow zero length method body on MS.NET 2.0 (and higher) - if (((ilgen == null) || (ilgen.ILOffset == 0)) && (code == null || code.Length == 0)) - throw new InvalidOperationException ( - String.Format ("Method '{0}.{1}' does not have a method body.", - DeclaringType.FullName, Name)); - } - if (ilgen != null) - ilgen.label_fixup (this); - } - - internal void ResolveUserTypes () { - rtype = TypeBuilder.ResolveUserType (rtype); - TypeBuilder.ResolveUserTypes (parameters); - TypeBuilder.ResolveUserTypes (returnModReq); - TypeBuilder.ResolveUserTypes (returnModOpt); - if (paramModReq != null) { - foreach (var types in paramModReq) - TypeBuilder.ResolveUserTypes (types); - } - if (paramModOpt != null) { - foreach (var types in paramModOpt) - TypeBuilder.ResolveUserTypes (types); - } - } -/* - internal void GenerateDebugInfo (ISymbolWriter symbolWriter) - { - if (ilgen != null && ilgen.HasDebugInfo) { - SymbolToken token = new SymbolToken (GetToken().Token); - symbolWriter.OpenMethod (token); - symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name)); - ilgen.GenerateDebugInfo (symbolWriter); - symbolWriter.CloseMethod (); - } - } -*/ - public void SetCustomAttribute (CustomAttributeBuilder customBuilder) - { - if (customBuilder == null) - throw new ArgumentNullException ("customBuilder"); - - switch (customBuilder.Ctor.ReflectedType.FullName) { - case "System.Runtime.CompilerServices.MethodImplAttribute": - byte[] data = customBuilder.Data; - int impla; // the (stupid) ctor takes a short or an int ... - impla = (int)data [2]; - impla |= ((int)data [3]) << 8; - iattrs |= (MethodImplAttributes)impla; - return; - - case "System.Runtime.InteropServices.DllImportAttribute": - CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder); - bool preserveSig = true; - - /* - * It would be easier to construct a DllImportAttribute from - * the custom attribute builder, but the DllImportAttribute - * does not contain all the information required here, ie. - * - some parameters, like BestFitMapping has three values - * ("on", "off", "missing"), but DllImportAttribute only - * contains two (on/off). - * - PreserveSig is true by default, while it is false by - * default in DllImportAttribute. - */ - - pi_dll = (string)attr.ctorArgs[0]; - if (pi_dll == null || pi_dll.Length == 0) - throw new ArgumentException ("DllName cannot be empty"); - - native_cc = System.Runtime.InteropServices.CallingConvention.Winapi; - - for (int i = 0; i < attr.namedParamNames.Length; ++i) { - string name = attr.namedParamNames [i]; - object value = attr.namedParamValues [i]; - - if (name == "CallingConvention") - native_cc = (CallingConvention)value; - else if (name == "CharSet") - charset = (CharSet)value; - else if (name == "EntryPoint") - pi_entry = (string)value; - else if (name == "ExactSpelling") - ExactSpelling = (bool)value; - else if (name == "SetLastError") - SetLastError = (bool)value; - else if (name == "PreserveSig") - preserveSig = (bool)value; - else if (name == "BestFitMapping") - BestFitMapping = (bool)value; - else if (name == "ThrowOnUnmappableChar") - ThrowOnUnmappableChar = (bool)value; - } - - attrs |= MethodAttributes.PinvokeImpl; - if (preserveSig) - iattrs |= MethodImplAttributes.PreserveSig; - return; - - case "System.Runtime.InteropServices.PreserveSigAttribute": - iattrs |= MethodImplAttributes.PreserveSig; - return; - case "System.Runtime.CompilerServices.SpecialNameAttribute": - attrs |= MethodAttributes.SpecialName; - return; - case "System.Security.SuppressUnmanagedCodeSecurityAttribute": - attrs |= MethodAttributes.HasSecurity; - break; - } - - if (cattrs != null) { - CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; - cattrs.CopyTo (new_array, 0); - new_array [cattrs.Length] = customBuilder; - cattrs = new_array; - } else { - cattrs = new CustomAttributeBuilder [1]; - cattrs [0] = customBuilder; - } - } - - [ComVisible (true)] - public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute) - { - if (con == null) - throw new ArgumentNullException ("con"); - if (binaryAttribute == null) - throw new ArgumentNullException ("binaryAttribute"); - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } - - public void SetImplementationFlags (MethodImplAttributes attributes) - { - RejectIfCreated (); - iattrs = attributes; - } - - public override string ToString() - { - return "MethodBuilder [" + type.Name + "::" + name + "]"; - } - - // FIXME: - public override bool Equals (object obj) - { - return base.Equals (obj); - } - - public override int GetHashCode () - { - return name.GetHashCode (); - } - - internal override int get_next_table_index (object obj, int table, int count) - { - return type.get_next_table_index (obj, table, count); - } - - void ExtendArray<T> (ref T[] array, T elem) { - if (array == null) { - array = new T [1]; - } else { - var newa = new T [array.Length + 1]; - Array.Copy (array, newa, array.Length); - array = newa; - } - array [array.Length - 1] = elem; - } - - internal void set_override (MethodInfo mdecl) - { - ExtendArray<MethodInfo> (ref override_methods, mdecl); - } - - private void RejectIfCreated () - { - if (type.is_created) - throw new InvalidOperationException ("Type definition of the method is complete."); - } - - private Exception NotSupported () - { - return new NotSupportedException ("The invoked member is not supported in a dynamic module."); - } - - public override MethodInfo MakeGenericMethod (params Type [] typeArguments) - { - if (!IsGenericMethodDefinition) - throw new InvalidOperationException ("Method is not a generic method definition"); - if (typeArguments == null) - throw new ArgumentNullException ("typeArguments"); - if (generic_params.Length != typeArguments.Length) - throw new ArgumentException ("Incorrect length", "typeArguments"); - foreach (Type type in typeArguments) { - if (type == null) - throw new ArgumentNullException ("typeArguments"); - } - - return new MethodOnTypeBuilderInst (this, typeArguments); - } - - public override bool IsGenericMethodDefinition { - get { - return generic_params != null; - } - } - - public override bool IsGenericMethod { - get { - return generic_params != null; - } - } - - public override MethodInfo GetGenericMethodDefinition () - { - if (!IsGenericMethodDefinition) - throw new InvalidOperationException (); - - return this; - } - - public override Type[] GetGenericArguments () - { - if (generic_params == null) - return null; - - Type[] result = new Type [generic_params.Length]; - for (int i = 0; i < generic_params.Length; i++) - result [i] = generic_params [i]; - - return result; - } - - public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names) - { - if (names == null) - throw new ArgumentNullException ("names"); - if (names.Length == 0) - throw new ArgumentException ("", "names"); - type.check_not_created (); - generic_params = new GenericTypeParameterBuilder [names.Length]; - for (int i = 0; i < names.Length; i++) { - string item = names [i]; - if (item == null) - throw new ArgumentNullException ("names"); - generic_params [i] = new GenericTypeParameterBuilder (type, this, item, i); - } - - return generic_params; - } - - public void SetReturnType (Type returnType) - { - rtype = returnType; - } - - public void SetParameters (params Type[] parameterTypes) - { - if (parameterTypes != null) { - for (int i = 0; i < parameterTypes.Length; ++i) - if (parameterTypes [i] == null) - throw new ArgumentNullException (nameof (parameterTypes), "Elements of the parameterTypes array cannot be null"); - - this.parameters = new Type [parameterTypes.Length]; - System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length); - } - } - - public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) - { - SetReturnType (returnType); - SetParameters (parameterTypes); - this.returnModReq = returnTypeRequiredCustomModifiers; - this.returnModOpt = returnTypeOptionalCustomModifiers; - this.paramModReq = parameterTypeRequiredCustomModifiers; - this.paramModOpt = parameterTypeOptionalCustomModifiers; - } - - public override Module Module { - get { - return GetModule (); - } - } - - public override ParameterInfo ReturnParameter { - get { - if (!type.is_created) - throw new InvalidOperationException (SR.InvalidOperation_TypeNotCreated); - if (created == null) - created = (RuntimeMethodInfo)MethodBase.GetMethodFromHandle (mhandle); - return created.ReturnParameter; - } - } - } - - [StructLayout(LayoutKind.Sequential)] - readonly struct ExceptionHandler : IEquatable<ExceptionHandler> - { - internal readonly int m_exceptionClass; - internal readonly int m_tryStartOffset; - internal readonly int m_tryEndOffset; - internal readonly int m_filterOffset; - internal readonly int m_handlerStartOffset; - internal readonly int m_handlerEndOffset; - internal readonly ExceptionHandlingClauseOptions m_kind; - - public int ExceptionTypeToken - { - get { return m_exceptionClass; } - } - - public int TryOffset - { - get { return m_tryStartOffset; } - } - - public int TryLength - { - get { return m_tryEndOffset - m_tryStartOffset; } - } - - public int FilterOffset - { - get { return m_filterOffset; } - } - - public int HandlerOffset - { - get { return m_handlerStartOffset; } - } - - public int HandlerLength - { - get { return m_handlerEndOffset - m_handlerStartOffset; } - } - - public ExceptionHandlingClauseOptions Kind - { - get { return m_kind; } - } - - internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset, - int kind, int exceptionTypeToken) - { - m_tryStartOffset = tryStartOffset; - m_tryEndOffset = tryEndOffset; - m_filterOffset = filterOffset; - m_handlerStartOffset = handlerStartOffset; - m_handlerEndOffset = handlerEndOffset; - m_kind = (ExceptionHandlingClauseOptions)kind; - m_exceptionClass = exceptionTypeToken; - } - - private static bool IsValidKind(ExceptionHandlingClauseOptions kind) - { - switch (kind) - { - case ExceptionHandlingClauseOptions.Clause: - case ExceptionHandlingClauseOptions.Filter: - case ExceptionHandlingClauseOptions.Finally: - case ExceptionHandlingClauseOptions.Fault: - return true; - - default: - return false; - } - } - - public override int GetHashCode() - { - return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind; - } - - public override bool Equals(Object obj) - { - return obj is ExceptionHandler && Equals((ExceptionHandler)obj); - } - - public bool Equals(ExceptionHandler other) - { - return - other.m_exceptionClass == m_exceptionClass && - other.m_tryStartOffset == m_tryStartOffset && - other.m_tryEndOffset == m_tryEndOffset && - other.m_filterOffset == m_filterOffset && - other.m_handlerStartOffset == m_handlerStartOffset && - other.m_handlerEndOffset == m_handlerEndOffset && - other.m_kind == m_kind; - } - - public static bool operator ==(ExceptionHandler left, ExceptionHandler right) - { - return left.Equals(right); - } - - public static bool operator !=(ExceptionHandler left, ExceptionHandler right) - { - return !left.Equals(right); - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs deleted file mode 100644 index 49b2d39e962..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs +++ /dev/null @@ -1,315 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit/MethodOnTypeBuilderInst.cs -// -// Author: -// Zoltan Varga (vargaz@gmail.com) -// -// -// Copyright (C) 2008 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Globalization; -using System.Reflection; -using System.Text; -using System.Runtime.InteropServices; - - -namespace System.Reflection.Emit -{ - /* - * This class represents a method of an instantiation of a generic type builder. - */ - [StructLayout (LayoutKind.Sequential)] - internal class MethodOnTypeBuilderInst : MethodInfo - { - #region Keep in sync with object-internals.h - Type instantiation; - MethodInfo base_method; /*This is the base method definition, it must be non-inflated and belong to a non-inflated type.*/ - Type[] method_arguments; - #endregion - MethodInfo generic_method_definition; - - public MethodOnTypeBuilderInst (TypeBuilderInstantiation instantiation, MethodInfo base_method) - { - this.instantiation = instantiation; - this.base_method = base_method; - } - - internal MethodOnTypeBuilderInst (MethodOnTypeBuilderInst gmd, Type[] typeArguments) - { - this.instantiation = gmd.instantiation; - this.base_method = gmd.base_method; - this.method_arguments = new Type [typeArguments.Length]; - typeArguments.CopyTo (this.method_arguments, 0); - this.generic_method_definition = gmd; - } - - internal MethodOnTypeBuilderInst (MethodInfo method, Type[] typeArguments) - { - this.instantiation = method.DeclaringType; - this.base_method = ExtractBaseMethod (method); - this.method_arguments = new Type [typeArguments.Length]; - typeArguments.CopyTo (this.method_arguments, 0); - if (base_method != method) - this.generic_method_definition = method; - } - - static MethodInfo ExtractBaseMethod (MethodInfo info) - { - if (info is MethodBuilder) - return info; - if (info is MethodOnTypeBuilderInst) - return ((MethodOnTypeBuilderInst)info).base_method; - - if (info.IsGenericMethod) - info = info.GetGenericMethodDefinition (); - - Type t = info.DeclaringType; - if (!t.IsGenericType || t.IsGenericTypeDefinition) - return info; - - return (MethodInfo)t.Module.ResolveMethod (info.MetadataToken); - } - - internal Type[] GetTypeArgs () - { - if (!instantiation.IsGenericType || instantiation.IsGenericParameter) - return null; - - return instantiation.GetGenericArguments (); - } - - // Called from the runtime to return the corresponding finished MethodInfo object - internal MethodInfo RuntimeResolve () { - var type = instantiation.InternalResolve (); - var m = type.GetMethod (base_method); - if (method_arguments != null) { - var args = new Type [method_arguments.Length]; - for (int i = 0; i < method_arguments.Length; ++i) - args [i] = method_arguments [i].InternalResolve (); - m = m.MakeGenericMethod (args); - } - return m; - } - - // - // MemberInfo members - // - - public override Type DeclaringType { - get { - return instantiation; - } - } - - public override string Name { - get { - return base_method.Name; - } - } - - public override Type ReflectedType { - get { - return instantiation; - } - } - - public override Type ReturnType { - get { - return base_method.ReturnType; - } - } - - public override Module Module { - get { - return base_method.Module; - } - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - throw new NotSupportedException (); - } - - public override object [] GetCustomAttributes (bool inherit) - { - throw new NotSupportedException (); - } - - public override object [] GetCustomAttributes (Type attributeType, bool inherit) - { - throw new NotSupportedException (); - } - - public override string ToString () - { - //IEnumerable`1 get_Item(TKey) - StringBuilder sb = new StringBuilder (ReturnType.ToString ()); - sb.Append (" "); - sb.Append (base_method.Name); - sb.Append ("("); - sb.Append (")"); - return sb.ToString (); - } - // - // MethodBase members - // - - public override MethodImplAttributes GetMethodImplementationFlags () - { - return base_method.GetMethodImplementationFlags (); - } - - public override ParameterInfo [] GetParameters () - { - return GetParametersInternal (); - } - - internal override ParameterInfo [] GetParametersInternal () - { - throw new NotSupportedException (); - } - - public override int MetadataToken { - get { - return base.MetadataToken; - } - } - - internal override int GetParametersCount () - { - return base_method.GetParametersCount (); - } - - public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - throw new NotSupportedException (); - } - - public override RuntimeMethodHandle MethodHandle { - get { - throw new NotSupportedException (); - } - } - - public override MethodAttributes Attributes { - get { - return base_method.Attributes; - } - } - - public override CallingConventions CallingConvention { - get { - return base_method.CallingConvention; - } - } - - public override MethodInfo MakeGenericMethod (params Type [] methodInstantiation) - { - if (!base_method.IsGenericMethodDefinition || (method_arguments != null)) - throw new InvalidOperationException ("Method is not a generic method definition"); - - if (methodInstantiation == null) - throw new ArgumentNullException ("methodInstantiation"); - - if (base_method.GetGenericArguments ().Length != methodInstantiation.Length) - throw new ArgumentException ("Incorrect length", "methodInstantiation"); - - foreach (Type type in methodInstantiation) { - if (type == null) - throw new ArgumentNullException ("methodInstantiation"); - } - - return new MethodOnTypeBuilderInst (this, methodInstantiation); - } - - public override Type [] GetGenericArguments () - { - if (!base_method.IsGenericMethodDefinition) - return null; - Type[] source = method_arguments ?? base_method.GetGenericArguments (); - Type[] result = new Type [source.Length]; - source.CopyTo (result, 0); - return result; - } - - public override MethodInfo GetGenericMethodDefinition () - { - return generic_method_definition ?? base_method; - } - - public override bool ContainsGenericParameters { - get { - if (base_method.ContainsGenericParameters) - return true; - if (!base_method.IsGenericMethodDefinition) - throw new NotSupportedException (); - if (method_arguments == null) - return true; - foreach (Type t in method_arguments) { - if (t.ContainsGenericParameters) - return true; - } - return false; - } - } - - public override bool IsGenericMethodDefinition { - get { - return base_method.IsGenericMethodDefinition && method_arguments == null; - } - } - - public override bool IsGenericMethod { - get { - return base_method.IsGenericMethodDefinition; - } - } - - // - // MethodInfo members - // - - public override MethodInfo GetBaseDefinition () - { - throw new NotSupportedException (); - } - - public override ParameterInfo ReturnParameter { - get { - throw new NotSupportedException(); - } - } - - public override ICustomAttributeProvider ReturnTypeCustomAttributes { - get { - throw new NotSupportedException (); - } - } - } -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs deleted file mode 100644 index 9df938b13c6..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs +++ /dev/null @@ -1,932 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// System.Reflection.Emit/ModuleBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.Collections; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Diagnostics.SymbolStore; -using System.IO; -using System.Globalization; - -namespace System.Reflection.Emit { - [StructLayout (LayoutKind.Sequential)] - public partial class ModuleBuilder : Module { - -#pragma warning disable 169, 414 - #region Sync with object-internals.h - // This class inherits from Module, but the runtime expects it to have the same layout as MonoModule - #region Sync with MonoModule - internal IntPtr _impl; /* a pointer to a MonoImage */ - internal Assembly assembly; - internal string fqname; - internal string name; - internal string scopename; - internal bool is_resource; - internal int token; - #endregion - private UIntPtr dynamic_image; /* GC-tracked */ - private int num_types; - private TypeBuilder[] types; - private CustomAttributeBuilder[] cattrs; - private byte[] guid; - private int table_idx; - internal AssemblyBuilder assemblyb; - private MethodBuilder[] global_methods; - private FieldBuilder[] global_fields; - bool is_main; - private object resources; - private IntPtr unparented_classes; - private int[] table_indexes; - #endregion -#pragma warning restore 169, 414 - - private TypeBuilder global_type; - private Type global_type_created; - // name_cache keys are display names - Dictionary<TypeName, TypeBuilder> name_cache; - Dictionary<string, int> us_string_cache; - ModuleBuilderTokenGenerator token_gen; - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void basic_init (ModuleBuilder ab); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void set_wrappers_type (ModuleBuilder mb, Type ab); - - internal ModuleBuilder (AssemblyBuilder assb, string name, bool emitSymbolInfo) { - this.name = this.scopename = name; - this.fqname = name; - this.assembly = this.assemblyb = assb; - guid = Guid.NewGuid ().ToByteArray (); - table_idx = get_next_table_index (this, 0x00, 1); - name_cache = new Dictionary<TypeName, TypeBuilder> (); - us_string_cache = new Dictionary<string, int> (512); - - basic_init (this); - - CreateGlobalType (); - - TypeBuilder tb = new TypeBuilder (this, TypeAttributes.Abstract, 0xFFFFFF); /*last valid token*/ - Type type = tb.CreateType (); - set_wrappers_type (this, type); - } - - public override string FullyQualifiedName { - get { - string fullyQualifiedName = fqname; - if (fullyQualifiedName == null) - return null; - if (assemblyb.AssemblyDir != null) { - fullyQualifiedName = Path.Combine (assemblyb.AssemblyDir, fullyQualifiedName); - fullyQualifiedName = Path.GetFullPath (fullyQualifiedName); - } - - return fullyQualifiedName; - } - } - - public bool IsTransient () { - return true; - } - - public void CreateGlobalFunctions () - { - if (global_type_created != null) - throw new InvalidOperationException ("global methods already created"); - if (global_type != null) - global_type_created = global_type.CreateType (); - } - - public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) { - if (data == null) - throw new ArgumentNullException ("data"); - - var maskedAttributes = attributes & ~FieldAttributes.ReservedMask; - FieldBuilder fb = DefineDataImpl (name, data.Length, maskedAttributes | FieldAttributes.HasFieldRVA); - fb.SetRVAData (data); - - return fb; - } - - public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes) - { - return DefineDataImpl (name, size, attributes & ~FieldAttributes.ReservedMask); - } - - private FieldBuilder DefineDataImpl (string name, int size, FieldAttributes attributes) - { - if (name == null) - throw new ArgumentNullException ("name"); - if (name == String.Empty) - throw new ArgumentException ("name cannot be empty", "name"); - if (global_type_created != null) - throw new InvalidOperationException ("global fields already created"); - if ((size <= 0) || (size >= 0x3f0000)) - throw new ArgumentException ("Data size must be > 0 and < 0x3f0000", null as string); - - CreateGlobalType (); - - string typeName = "$ArrayType$" + size; - Type datablobtype = GetType (typeName, false, false); - if (datablobtype == null) { - TypeBuilder tb = DefineType (typeName, - TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed, - typeof (ValueType), null, PackingSize.Size1, size); - tb.CreateType (); - datablobtype = tb; - } - FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static); - - if (global_fields != null) { - FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1]; - System.Array.Copy (global_fields, new_fields, global_fields.Length); - new_fields [global_fields.Length] = fb; - global_fields = new_fields; - } else { - global_fields = new FieldBuilder [1]; - global_fields [0] = fb; - } - return fb; - } - - private void addGlobalMethod (MethodBuilder mb) { - if (global_methods != null) { - MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1]; - System.Array.Copy (global_methods, new_methods, global_methods.Length); - new_methods [global_methods.Length] = mb; - global_methods = new_methods; - } else { - global_methods = new MethodBuilder [1]; - global_methods [0] = mb; - } - } - - public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) - { - return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes); - } - - public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { - return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); - } - - public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) - { - if (name == null) - throw new ArgumentNullException ("name"); - if ((attributes & MethodAttributes.Static) == 0) - throw new ArgumentException ("global methods must be static"); - if (global_type_created != null) - throw new InvalidOperationException ("global methods already created"); - CreateGlobalType (); - MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); - - addGlobalMethod (mb); - return mb; - } - - public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { - return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); - } - - public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { - if (name == null) - throw new ArgumentNullException ("name"); - if ((attributes & MethodAttributes.Static) == 0) - throw new ArgumentException ("global methods must be static"); - if (global_type_created != null) - throw new InvalidOperationException ("global methods already created"); - CreateGlobalType (); - MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); - - addGlobalMethod (mb); - return mb; - } - - public TypeBuilder DefineType (string name) { - return DefineType (name, 0); - } - - public TypeBuilder DefineType (string name, TypeAttributes attr) { - if ((attr & TypeAttributes.Interface) != 0) - return DefineType (name, attr, null, null); - return DefineType (name, attr, typeof(object), null); - } - - public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) { - return DefineType (name, attr, parent, null); - } - - private void AddType (TypeBuilder tb) - { - if (types != null) { - if (types.Length == num_types) { - TypeBuilder[] new_types = new TypeBuilder [types.Length * 2]; - System.Array.Copy (types, new_types, num_types); - types = new_types; - } - } else { - types = new TypeBuilder [1]; - } - types [num_types] = tb; - num_types ++; - } - - private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) { - if (name == null) - throw new ArgumentNullException ("fullname"); - TypeIdentifier ident = TypeIdentifiers.FromInternal (name); - if (name_cache.ContainsKey (ident)) - throw new ArgumentException ("Duplicate type name within an assembly."); - TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packingSize, typesize, null); - AddType (res); - - name_cache.Add (ident, res); - - return res; - } - - internal void RegisterTypeName (TypeBuilder tb, TypeName name) - { - name_cache.Add (name, tb); - } - - internal TypeBuilder GetRegisteredType (TypeName name) - { - TypeBuilder result = null; - name_cache.TryGetValue (name, out result); - return result; - } - - [ComVisible (true)] - public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) { - return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); - } - - public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) { - return DefineType (name, attr, parent, null, PackingSize.Unspecified, typesize); - } - - public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) { - return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize); - } - - public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) { - return DefineType (name, attr, parent, null, packingSize, typesize); - } - - public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { - return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes); - } - - public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) { - TypeIdentifier ident = TypeIdentifiers.FromInternal (name); - if (name_cache.ContainsKey (ident)) - throw new ArgumentException ("Duplicate type name within an assembly."); - - EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType); - TypeBuilder res = eb.GetTypeBuilder (); - AddType (res); - name_cache.Add (ident, res); - return eb; - } - - [ComVisible (true)] - public override Type GetType( string className) { - return GetType (className, false, false); - } - - [ComVisible (true)] - public override Type GetType( string className, bool ignoreCase) { - return GetType (className, false, ignoreCase); - } - - private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, TypeName className) { - int i; - for (i = 0; i < validElementsInArray; ++i) { - if (String.Compare (className.DisplayName, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) { - return arr [i]; - } - } - return null; - } - - private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, TypeName className) { - int i; - for (i = 0; i < validElementsInArray; ++i) { - if (String.Compare (className.DisplayName, arr [i].Name, true, CultureInfo.InvariantCulture) == 0) - return arr [i]; - } - return null; - } - - private TypeBuilder GetMaybeNested (TypeBuilder t, IEnumerable<TypeName> nested) { - TypeBuilder result = t; - - foreach (TypeName pname in nested) { - if (result.subtypes == null) - return null; - result = search_nested_in_array(result.subtypes, result.subtypes.Length, pname); - if (result == null) - return null; - } - return result; - } - - [ComVisible (true)] - public override Type GetType (string className, bool throwOnError, bool ignoreCase) - { - if (className == null) - throw new ArgumentNullException ("className"); - if (className.Length == 0) - throw new ArgumentException ("className"); - - TypeBuilder result = null; - - if (types == null && throwOnError) - throw new TypeLoadException (className); - - TypeSpec ts = TypeSpec.Parse (className); - - if (!ignoreCase) { - var displayNestedName = ts.TypeNameWithoutModifiers(); - name_cache.TryGetValue (displayNestedName, out result); - } else { - if (types != null) - result = search_in_array (types, num_types, ts.Name); - if (!ts.IsNested && result != null) { - result = GetMaybeNested (result, ts.Nested); - } - } - if ((result == null) && throwOnError) - throw new TypeLoadException (className); - if (result != null && (ts.HasModifiers || ts.IsByRef)) { - Type mt = result; - if (result is TypeBuilder) { - var tb = result as TypeBuilder; - if (tb.is_created) - mt = tb.CreateType (); - } - foreach (var mod in ts.Modifiers) { - if (mod is PointerSpec) - mt = mt.MakePointerType (); - else if (mod is ArraySpec) { - var spec = mod as ArraySpec; - if (spec.IsBound) - return null; - if (spec.Rank == 1) - mt = mt.MakeArrayType (); - else - mt = mt.MakeArrayType (spec.Rank); - } - } - if (ts.IsByRef) - mt = mt.MakeByRefType (); - result = mt as TypeBuilder; - if (result == null) - return mt; - } - if (result != null && result.is_created) - return result.CreateType (); - else - return result; - } - - internal int get_next_table_index (object obj, int table, int count) { - if (table_indexes == null) { - table_indexes = new int [64]; - for (int i=0; i < 64; ++i) - table_indexes [i] = 1; - /* allow room for .<Module> in TypeDef table */ - table_indexes [0x02] = 2; - } - // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString()); - var index = table_indexes [table]; - table_indexes [table] += count; - return index; - } - - public void SetCustomAttribute (CustomAttributeBuilder customBuilder) - { - if (customBuilder == null) - throw new ArgumentNullException (nameof (customBuilder)); - if (cattrs != null) { - CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; - cattrs.CopyTo (new_array, 0); - new_array [cattrs.Length] = customBuilder; - cattrs = new_array; - } else { - cattrs = new CustomAttributeBuilder [1]; - cattrs [0] = customBuilder; - } - } - - [ComVisible (true)] - public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) { - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } -/* - internal ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType) - { - if (symbolWriter != null) - return symbolWriter.DefineDocument (url, language, languageVendor, documentType); - else - return null; - } -*/ - public override Type [] GetTypes () - { - if (types == null) - return Type.EmptyTypes; - - int n = num_types; - Type [] copy = new Type [n]; - Array.Copy (types, copy, n); - - // MS replaces the typebuilders with their created types - for (int i = 0; i < copy.Length; ++i) - if (types [i].is_created) - copy [i] = types [i].CreateType (); - - return copy; - } - - public MethodToken GetMethodToken (MethodInfo method) - { - if (method == null) - throw new ArgumentNullException ("method"); - - return new MethodToken (GetToken (method)); - } - - public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) - { - return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes)); - } - - [ComVisible (true)] - public MethodToken GetConstructorToken (ConstructorInfo con) - { - if (con == null) - throw new ArgumentNullException ("con"); - - return new MethodToken (GetToken (con)); - } - - public FieldToken GetFieldToken (FieldInfo field) - { - if (field == null) - throw new ArgumentNullException ("field"); - - throw new NotImplementedException (); - //return new FieldToken (GetToken (field)); - } - - // FIXME: - public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength) - { - throw new NotImplementedException (); - } - - public SignatureToken GetSignatureToken (SignatureHelper sigHelper) - { - if (sigHelper == null) - throw new ArgumentNullException ("sigHelper"); - return new SignatureToken (GetToken (sigHelper)); - } - - public StringToken GetStringConstant (string str) - { - if (str == null) - throw new ArgumentNullException ("str"); - return new StringToken (GetToken (str)); - } - - public TypeToken GetTypeToken (Type type) - { - if (type == null) - throw new ArgumentNullException ("type"); - if (type.IsByRef) - throw new ArgumentException ("type can't be a byref type", "type"); - if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ()) - throw new InvalidOperationException ("a non-transient module can't reference a transient module"); - return new TypeToken (GetToken (type)); - } - - public TypeToken GetTypeToken (string name) - { - return GetTypeToken (GetType (name)); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern int getUSIndex (ModuleBuilder mb, string str); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern int getToken (ModuleBuilder mb, object obj, bool create_open_instance); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern int getMethodToken (ModuleBuilder mb, MethodBase method, - Type[] opt_param_types); - - internal int GetToken (string str) - { - int result; - if (!us_string_cache.TryGetValue (str, out result)) { - result = getUSIndex (this, str); - us_string_cache [str] = result; - } - - return result; - } - - static int typeref_tokengen = 0x01ffffff; - static int typedef_tokengen = 0x02ffffff; - static int typespec_tokengen = 0x1bffffff; - static int memberref_tokengen = 0x0affffff; - static int methoddef_tokengen = 0x06ffffff; - Dictionary<MemberInfo, int> inst_tokens, inst_tokens_open; - - // - // Assign a pseudo token to the various TypeBuilderInst objects, so the runtime - // doesn't have to deal with them. - // For Run assemblies, the tokens will not be fixed up, so the runtime will - // still encounter these objects, it will resolve them by calling their - // RuntimeResolve () methods. - // - int GetPseudoToken (MemberInfo member, bool create_open_instance) - { - int token; - var dict = create_open_instance ? inst_tokens_open : inst_tokens; - if (dict == null) { - dict = new Dictionary<MemberInfo, int> (ReferenceEqualityComparer<MemberInfo>.Instance); - if (create_open_instance) - inst_tokens_open = dict; - else - inst_tokens = dict; - } else if (dict.TryGetValue (member, out token)) { - return token; - } - - // Count backwards to avoid collisions with the tokens - // allocated by the runtime - if (member is TypeBuilderInstantiation || member is SymbolType) - token = typespec_tokengen --; - else if (member is FieldOnTypeBuilderInst) - token = memberref_tokengen --; - else if (member is ConstructorOnTypeBuilderInst) - token = memberref_tokengen --; - else if (member is MethodOnTypeBuilderInst) - token = memberref_tokengen --; - else if (member is FieldBuilder) - token = memberref_tokengen --; - else if (member is TypeBuilder) { - if (create_open_instance && (member as TypeBuilder).ContainsGenericParameters) - token = typespec_tokengen --; - else if (member.Module == this) - token = typedef_tokengen --; - else - token = typeref_tokengen --; - } else if (member is EnumBuilder) { - token = GetPseudoToken ((member as EnumBuilder).GetTypeBuilder(), create_open_instance); - dict[member] = token; - // n.b. don't register with the runtime, the TypeBuilder already did it. - return token; - } else if (member is ConstructorBuilder) { - if (member.Module == this && !(member as ConstructorBuilder).TypeBuilder.ContainsGenericParameters) - token = methoddef_tokengen --; - else - token = memberref_tokengen --; - } else if (member is MethodBuilder) { - var mb = member as MethodBuilder; - if (member.Module == this && !mb.TypeBuilder.ContainsGenericParameters && !mb.IsGenericMethodDefinition) - token = methoddef_tokengen --; - else - token = memberref_tokengen --; - } else if (member is GenericTypeParameterBuilder) { - token = typespec_tokengen --; - } else - throw new NotImplementedException (); - - dict [member] = token; - RegisterToken (member, token); - return token; - } - - internal int GetToken (MemberInfo member) { - if (member is ConstructorBuilder || member is MethodBuilder || member is FieldBuilder) - return GetPseudoToken (member, false); - return getToken (this, member, true); - } - - internal int GetToken (MemberInfo member, bool create_open_instance) { - if (member is TypeBuilderInstantiation || member is FieldOnTypeBuilderInst || member is ConstructorOnTypeBuilderInst || member is MethodOnTypeBuilderInst || member is SymbolType || member is FieldBuilder || member is TypeBuilder || member is ConstructorBuilder || member is MethodBuilder || member is GenericTypeParameterBuilder || - member is EnumBuilder) - return GetPseudoToken (member, create_open_instance); - return getToken (this, member, create_open_instance); - } - - internal int GetToken (MethodBase method, IEnumerable<Type> opt_param_types) { - if (method is ConstructorBuilder || method is MethodBuilder) - return GetPseudoToken (method, false); - - if (opt_param_types == null) - return getToken (this, method, true); - - var optParamTypes = new List<Type> (opt_param_types); - return getMethodToken (this, method, optParamTypes.ToArray ()); - } - - internal int GetToken (MethodBase method, Type[] opt_param_types) { - if (method is ConstructorBuilder || method is MethodBuilder) - return GetPseudoToken (method, false); - return getMethodToken (this, method, opt_param_types); - } - - internal int GetToken (SignatureHelper helper) { - return getToken (this, helper, true); - } - - /* - * Register the token->obj mapping with the runtime so the Module.Resolve... - * methods will work for obj. - */ - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern void RegisterToken (object obj, int token); - - /* - * Returns MemberInfo registered with the given token. - */ - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern object GetRegisteredToken (int token); - - internal TokenGenerator GetTokenGenerator () { - if (token_gen == null) - token_gen = new ModuleBuilderTokenGenerator (this); - return token_gen; - } - - // Called from the runtime to return the corresponding finished reflection object - internal static object RuntimeResolve (object obj) { - if (obj is MethodBuilder) - return (obj as MethodBuilder).RuntimeResolve (); - if (obj is ConstructorBuilder) - return (obj as ConstructorBuilder).RuntimeResolve (); - if (obj is FieldBuilder) - return (obj as FieldBuilder).RuntimeResolve (); - if (obj is GenericTypeParameterBuilder) - return (obj as GenericTypeParameterBuilder).RuntimeResolve (); - if (obj is FieldOnTypeBuilderInst) - return (obj as FieldOnTypeBuilderInst).RuntimeResolve (); - if (obj is MethodOnTypeBuilderInst) - return (obj as MethodOnTypeBuilderInst).RuntimeResolve (); - if (obj is ConstructorOnTypeBuilderInst) - return (obj as ConstructorOnTypeBuilderInst).RuntimeResolve (); - if (obj is Type) - return (obj as Type).RuntimeResolve (); - throw new NotImplementedException (obj.GetType ().FullName); - } - - internal string FileName { - get { - return fqname; - } - } - - internal bool IsMain { - set { - is_main = value; - } - } - - internal void CreateGlobalType () { - if (global_type == null) - global_type = new TypeBuilder (this, 0, 1); - } - - public override Assembly Assembly { - get { return assemblyb; } - } - - public override string Name { - get { return name; } - } - - public override string ScopeName { - get { return name; } - } - - public override Guid ModuleVersionId { - get { - return new Guid (guid); - } - } - - public override bool IsResource () - { - return false; - } - - protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) - { - if (global_type_created == null) - return null; - if (types == null) - return global_type_created.GetMethod (name); - return global_type_created.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers); - } - - public override FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - return RuntimeModule.ResolveField (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments); - } - - public override MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - return RuntimeModule.ResolveMember (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments); - } - - internal MemberInfo ResolveOrGetRegisteredToken (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) - { - ResolveTokenError error; - MemberInfo m = RuntimeModule.ResolveMemberToken (_impl, metadataToken, RuntimeModule.ptrs_from_types (genericTypeArguments), RuntimeModule.ptrs_from_types (genericMethodArguments), out error); - if (m != null) - return m; - - m = GetRegisteredToken (metadataToken) as MemberInfo; - if (m == null) - throw RuntimeModule.resolve_token_exception (Name, metadataToken, error, "MemberInfo"); - else - return m; - } - - public override MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - return RuntimeModule.ResolveMethod (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments); - } - - public override string ResolveString (int metadataToken) { - return RuntimeModule.ResolveString (this, _impl, metadataToken); - } - - public override byte[] ResolveSignature (int metadataToken) { - return RuntimeModule.ResolveSignature (this, _impl, metadataToken); - } - - public override Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - return RuntimeModule.ResolveType (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments); - } - - public override bool Equals (object obj) - { - return base.Equals (obj); - } - - public override int GetHashCode () - { - return base.GetHashCode (); - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - return base.IsDefined (attributeType, inherit); - } - - public override object[] GetCustomAttributes (bool inherit) - { - return GetCustomAttributes (null, inherit); - } - - public override object[] GetCustomAttributes (Type attributeType, bool inherit) - { - if (cattrs == null || cattrs.Length == 0) - return Array.Empty<object> (); - - if (attributeType is TypeBuilder) - throw new InvalidOperationException ("First argument to GetCustomAttributes can't be a TypeBuilder"); - - List<object> results = new List<object> (); - for (int i=0; i < cattrs.Length; i++) { - Type t = cattrs [i].Ctor.GetType (); - - if (t is TypeBuilder) - throw new InvalidOperationException ("Can't construct custom attribute for TypeBuilder type"); - - if (attributeType == null || attributeType.IsAssignableFrom (t)) - results.Add (cattrs [i].Invoke ()); - } - - return results.ToArray (); - } - - public override IList<CustomAttributeData> GetCustomAttributesData () - { - return CustomAttributeData.GetCustomAttributes (this); - } - - public override FieldInfo GetField (string name, BindingFlags bindingAttr) - { - if (global_type_created == null) - throw new InvalidOperationException ("Module-level fields cannot be retrieved until after the CreateGlobalFunctions method has been called for the module."); - return global_type_created.GetField (name, bindingAttr); - } - - public override FieldInfo[] GetFields (BindingFlags bindingFlags) - { - if (global_type_created == null) - throw new InvalidOperationException ("Module-level fields cannot be retrieved until after the CreateGlobalFunctions method has been called for the module."); - return global_type_created.GetFields (bindingFlags); - } - - public override MethodInfo[] GetMethods (BindingFlags bindingFlags) - { - if (global_type_created == null) - throw new InvalidOperationException ("Module-level methods cannot be retrieved until after the CreateGlobalFunctions method has been called for the module."); - return global_type_created.GetMethods (bindingFlags); - } - - public override int MetadataToken { - get { - return RuntimeModule.get_MetadataToken (this); - } - } - } - - internal class ModuleBuilderTokenGenerator : TokenGenerator { - - private ModuleBuilder mb; - - public ModuleBuilderTokenGenerator (ModuleBuilder mb) { - this.mb = mb; - } - - public int GetToken (string str) { - return mb.GetToken (str); - } - - public int GetToken (MemberInfo member, bool create_open_instance) { - return mb.GetToken (member, create_open_instance); - } - - public int GetToken (MethodBase method, Type[] opt_param_types) { - return mb.GetToken (method, opt_param_types); - } - - public int GetToken (SignatureHelper helper) { - return mb.GetToken (helper); - } - } - - internal sealed class ReferenceEqualityComparer<T> : IEqualityComparer<T> where T : class - { - internal static readonly ReferenceEqualityComparer<T> Instance = new ReferenceEqualityComparer<T>(); - - private ReferenceEqualityComparer() - { - } - - public bool Equals(T x, T y) - { - return ReferenceEquals (x, y); - } - - public int GetHashCode(T obj) - { - return RuntimeHelpers.GetHashCode (obj); - } - } - -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MonoArrayMethod.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MonoArrayMethod.cs deleted file mode 100644 index eebe6efc687..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MonoArrayMethod.cs +++ /dev/null @@ -1,158 +0,0 @@ -#nullable disable - -// -// System.Reflection/MonoMethod.cs -// The class used to represent methods from the mono runtime. -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection { - [StructLayout (LayoutKind.Sequential)] - internal class MonoArrayMethod: MethodInfo { -#pragma warning disable 649 - internal RuntimeMethodHandle mhandle; - internal Type parent; - internal Type ret; - internal Type[] parameters; - internal string name; - internal int table_idx; - internal CallingConventions call_conv; -#pragma warning restore 649 - - internal MonoArrayMethod (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { - name = methodName; - parent = arrayClass; - ret = returnType; - parameters = (Type[])parameterTypes.Clone(); - call_conv = callingConvention; - } - - // FIXME: "Always returns this" - public override MethodInfo GetBaseDefinition() { - return this; /* FIXME */ - } - public override Type ReturnType { - get { - return ret; - } - } - - // FIXME: "Not implemented. Always returns null" - public override ICustomAttributeProvider ReturnTypeCustomAttributes { - get {return null;} - } - - // FIXME: "Not implemented. Always returns zero" - public override MethodImplAttributes GetMethodImplementationFlags() { - return (MethodImplAttributes)0; - } - - // FIXME: "Not implemented. Always returns an empty array" - public override ParameterInfo[] GetParameters() - { - return GetParametersInternal (); - } - - internal override ParameterInfo[] GetParametersInternal () - { - return Array.Empty<ParameterInfo> (); - } - - // FIXME: "Not implemented. Always returns 0" - internal override int GetParametersCount () - { - return 0; - } - - // FIXME: "Not implemented" - public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { - throw new NotImplementedException (); - } - - public override RuntimeMethodHandle MethodHandle { - get {return mhandle;} - } - - // FIXME: "Not implemented. Always returns zero" - public override MethodAttributes Attributes { - get { - return (MethodAttributes)0; - } - } - - public override Type ReflectedType { - get { - return parent; - } - } - public override Type DeclaringType { - get { - return parent; - } - } - public override string Name { - get { - return name; - } - } - - public override bool IsDefined (Type attributeType, bool inherit) { - return CustomAttribute.IsDefined (this, attributeType, inherit); - } - - public override object[] GetCustomAttributes( bool inherit) { - return CustomAttribute.GetCustomAttributes (this, inherit); - } - public override object[] GetCustomAttributes( Type attributeType, bool inherit) { - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - } - - public override string ToString () { - string parms = String.Empty; - ParameterInfo[] p = GetParameters (); - for (int i = 0; i < p.Length; ++i) { - if (i > 0) - parms = parms + ", "; - parms = parms + p [i].ParameterType.Name; - } - if (ReturnType != null) - return ReturnType.Name+" "+Name+"("+parms+")"; - else - return "void "+Name+"("+parms+")"; - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.Mono.cs deleted file mode 100644 index 70a8fad0456..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.Mono.cs +++ /dev/null @@ -1,146 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - - -// -// System.Reflection.Emit/ParameterBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - [StructLayout (LayoutKind.Sequential)] - public partial class ParameterBuilder - { -#pragma warning disable 169, 414 - private MethodBase methodb; /* MethodBuilder, ConstructorBuilder or DynamicMethod */ - private string name; - private CustomAttributeBuilder[] cattrs; - private UnmanagedMarshal marshal_info; - private ParameterAttributes attrs; - private int position; - private int table_idx; - object def_value; -#pragma warning restore 169, 414 - - internal ParameterBuilder (MethodBase mb, int pos, ParameterAttributes attributes, string strParamName) { - name = strParamName; - position = pos; - attrs = attributes; - methodb = mb; - if (mb is DynamicMethod) - table_idx = 0; - else - table_idx = mb.get_next_table_index (this, 0x08, 1); - } - - public virtual int Attributes { - get {return (int)attrs;} - } - public bool IsIn { - get {return ((int)attrs & (int)ParameterAttributes.In) != 0;} - } - public bool IsOut { - get {return ((int)attrs & (int)ParameterAttributes.Out) != 0;} - } - public bool IsOptional { - get {return ((int)attrs & (int)ParameterAttributes.Optional) != 0;} - } - public virtual string Name { - get {return name;} - } - public virtual int Position { - get {return position;} - } - - public virtual ParameterToken GetToken() { - return new ParameterToken (0x08 | table_idx); - } - - public virtual void SetConstant (object defaultValue) - { - if (position > 0) { - TypeBuilder.SetConstantValue (methodb.GetParameterType (position - 1), - defaultValue, ref defaultValue); - } - - def_value = defaultValue; - attrs |= ParameterAttributes.HasDefault; - } - - public void SetCustomAttribute( CustomAttributeBuilder customBuilder) { - string attrname = customBuilder.Ctor.ReflectedType.FullName; - if (attrname == "System.Runtime.InteropServices.InAttribute") { - attrs |= ParameterAttributes.In; - return; - } else if (attrname == "System.Runtime.InteropServices.OutAttribute") { - attrs |= ParameterAttributes.Out; - return; - } else if (attrname == "System.Runtime.InteropServices.OptionalAttribute") { - attrs |= ParameterAttributes.Optional; - return; - } else if (attrname == "System.Runtime.InteropServices.MarshalAsAttribute") { - attrs |= ParameterAttributes.HasFieldMarshal; - marshal_info = CustomAttributeBuilder.get_umarshal (customBuilder, false); - /* FIXME: check for errors */ - return; - } else if (attrname == "System.Runtime.InteropServices.DefaultParameterValueAttribute") { - /* MS.NET doesn't handle this attribute but we handle it for consistency */ - CustomAttributeBuilder.CustomAttributeInfo cinfo = CustomAttributeBuilder.decode_cattr (customBuilder); - /* FIXME: check for type compatibility */ - SetConstant (cinfo.ctorArgs [0]); - return; - } - - if (cattrs != null) { - CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; - cattrs.CopyTo (new_array, 0); - new_array [cattrs.Length] = customBuilder; - cattrs = new_array; - } else { - cattrs = new CustomAttributeBuilder [1]; - cattrs [0] = customBuilder; - } - } - - [ComVisible (true)] - public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) { - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } - } -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs deleted file mode 100644 index 5cd1b5b160e..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs +++ /dev/null @@ -1,218 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// System.Reflection.Emit/PropertyBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - [StructLayout (LayoutKind.Sequential)] - public sealed partial class PropertyBuilder : PropertyInfo { - -// Managed version of MonoReflectionPropertyBuilder -#pragma warning disable 169, 414 - private PropertyAttributes attrs; - private string name; - private Type type; - private Type[] parameters; - private CustomAttributeBuilder[] cattrs; - private object def_value; - private MethodBuilder set_method; - private MethodBuilder get_method; - private int table_idx = 0; - internal TypeBuilder typeb; - private Type[] returnModReq; - private Type[] returnModOpt; - private Type[][] paramModReq; - private Type[][] paramModOpt; - CallingConventions callingConvention; -#pragma warning restore 169, 414 - - internal PropertyBuilder (TypeBuilder tb, string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt) - { - this.name = name; - this.attrs = attributes; - this.callingConvention = callingConvention; - this.type = returnType; - this.returnModReq = returnModReq; - this.returnModOpt = returnModOpt; - this.paramModReq = paramModReq; - this.paramModOpt = paramModOpt; - if (parameterTypes != null) { - this.parameters = new Type [parameterTypes.Length]; - System.Array.Copy (parameterTypes, this.parameters, this.parameters.Length); - } - typeb = tb; - table_idx = tb.get_next_table_index (this, 0x17, 1); - } - - public override PropertyAttributes Attributes { - get {return attrs;} - } - public override bool CanRead { - get {return get_method != null;} - } - public override bool CanWrite { - get {return set_method != null;} - } - public override Type DeclaringType { - get {return typeb;} - } - public override string Name { - get {return name;} - } - public PropertyToken PropertyToken { - get {return new PropertyToken ();} - } - public override Type PropertyType { - get {return type;} - } - public override Type ReflectedType { - get {return typeb;} - } - - public void AddOtherMethod (MethodBuilder mdBuilder) - { - if (mdBuilder == null) - throw new ArgumentNullException (nameof (mdBuilder)); - typeb.check_not_created (); - } - - public override MethodInfo[] GetAccessors( bool nonPublic) { - return null; - } - public override object[] GetCustomAttributes(bool inherit) { - throw not_supported (); - } - public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - throw not_supported (); - } - public override MethodInfo GetGetMethod( bool nonPublic) { - return get_method; - } - public override ParameterInfo[] GetIndexParameters() { - throw not_supported (); - } - public override MethodInfo GetSetMethod( bool nonPublic) { - return set_method; - } - - public override object GetValue (object obj, object[] index) - { - throw not_supported (); - } - - public override object GetValue (object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) - { - throw not_supported (); - } - public override bool IsDefined( Type attributeType, bool inherit) { - throw not_supported (); - } - public void SetConstant (object defaultValue) - { - typeb.check_not_created (); - def_value = defaultValue; - } - - public void SetCustomAttribute (CustomAttributeBuilder customBuilder) - { - if (customBuilder == null) - throw new ArgumentNullException (nameof (customBuilder)); - typeb.check_not_created (); - string attrname = customBuilder.Ctor.ReflectedType.FullName; - if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") { - attrs |= PropertyAttributes.SpecialName; - return; - } - - if (cattrs != null) { - CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; - cattrs.CopyTo (new_array, 0); - new_array [cattrs.Length] = customBuilder; - cattrs = new_array; - } else { - cattrs = new CustomAttributeBuilder [1]; - cattrs [0] = customBuilder; - } - } - - [ComVisible (true)] - public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute) { - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } - - public void SetGetMethod (MethodBuilder mdBuilder) - { - typeb.check_not_created (); - if (mdBuilder == null) - throw new ArgumentNullException (nameof (mdBuilder)); - get_method = mdBuilder; - } - - public void SetSetMethod (MethodBuilder mdBuilder) - { - if (mdBuilder == null) - throw new ArgumentNullException (nameof (mdBuilder)); - set_method = mdBuilder; - } - - public override void SetValue (object obj, object value, object[] index) - { - throw not_supported (); - } - - public override void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) - { - throw not_supported (); - } - - public override Module Module { - get { - return base.Module; - } - } - - private Exception not_supported () - { - return new NotSupportedException ("The invoked member is not supported in a dynamic module."); - } - } -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyOnTypeBuilderInst.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyOnTypeBuilderInst.cs deleted file mode 100644 index d705521b990..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/PropertyOnTypeBuilderInst.cs +++ /dev/null @@ -1,165 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit/PropertyOnTypeBuilderInst.cs -// -// Author: -// Rodrigo Kumpera (rkumpera@novell.com) -// -// -// Copyright (C) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Globalization; -using System.Reflection; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit -{ - /* - * This class represents a property of an instantiation of a generic type builder. - */ - [StructLayout (LayoutKind.Sequential)] - internal class PropertyOnTypeBuilderInst : PropertyInfo - { - TypeBuilderInstantiation instantiation; - PropertyInfo prop; - - internal PropertyOnTypeBuilderInst (TypeBuilderInstantiation instantiation, PropertyInfo prop) - { - this.instantiation = instantiation; - this.prop = prop; - } - - public override PropertyAttributes Attributes { - get { throw new NotSupportedException (); } - } - - public override bool CanRead { - get { throw new NotSupportedException (); } - } - - public override bool CanWrite { - get { throw new NotSupportedException (); } - } - - public override Type PropertyType { - get { return instantiation.InflateType (prop.PropertyType); } - } - - public override Type DeclaringType { - get { return instantiation.InflateType (prop.DeclaringType); } - } - - public override Type ReflectedType { - get { return instantiation; } - } - - public override string Name { - get { return prop.Name; } - } - - public override MethodInfo[] GetAccessors (bool nonPublic) - { - MethodInfo getter = GetGetMethod (nonPublic); - MethodInfo setter = GetSetMethod (nonPublic); - - int methods = 0; - if (getter != null) - ++methods; - if (setter != null) - ++methods; - - MethodInfo[] res = new MethodInfo [methods]; - - methods = 0; - if (getter != null) - res [methods++] = getter; - if (setter != null) - res [methods] = setter; - - return res; - } - - - public override MethodInfo GetGetMethod (bool nonPublic) - { - MethodInfo mi = prop.GetGetMethod (nonPublic); - if (mi != null && prop.DeclaringType == instantiation.generic_type) { - mi = TypeBuilder.GetMethod (instantiation, mi); - } - return mi; - } - - public override ParameterInfo[] GetIndexParameters() - { - MethodInfo method = GetGetMethod (true); - if (method != null) - return method.GetParameters (); - - return Array.Empty<ParameterInfo> (); - } - - public override MethodInfo GetSetMethod (bool nonPublic) - { - MethodInfo mi = prop.GetSetMethod (nonPublic); - if (mi != null && prop.DeclaringType == instantiation.generic_type) { - mi = TypeBuilder.GetMethod (instantiation, mi); - } - return mi; - } - - public override string ToString () - { - return String.Format("{0} {1}", PropertyType, Name); - } - - public override object GetValue (object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) - { - throw new NotSupportedException (); - } - - public override void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) - { - throw new NotSupportedException (); - } - - public override bool IsDefined( Type attributeType, bool inherit) - { - throw new NotSupportedException (); - } - - public override object[] GetCustomAttributes(bool inherit) - { - throw new NotSupportedException (); - } - - public override object[] GetCustomAttributes(Type attributeType, bool inherit) - { - throw new NotSupportedException (); - } - } -} - -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs deleted file mode 100644 index 078d9354d9d..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs +++ /dev/null @@ -1,410 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// System.Reflection.Emit/SignatureHelper.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -#if MONO_FEATURE_SRE -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit { - [StructLayout (LayoutKind.Sequential)] - public sealed class SignatureHelper { - internal enum SignatureHelperType { - HELPER_FIELD, - HELPER_LOCAL, - HELPER_METHOD, - HELPER_PROPERTY - } - - private ModuleBuilder module; // can be null in 2.0 - private Type[] arguments; - private SignatureHelperType type; - private Type returnType; - private CallingConventions callConv; - private CallingConvention unmanagedCallConv; -#pragma warning disable 649 - private Type[][] modreqs; - private Type[][] modopts; -#pragma warning restore 649 - - internal SignatureHelper (ModuleBuilder module, SignatureHelperType type) - { - this.type = type; - this.module = module; - } - - public static SignatureHelper GetFieldSigHelper (Module mod) - { - if (mod != null && !(mod is ModuleBuilder)) - throw new ArgumentException ("ModuleBuilder is expected"); - - return new SignatureHelper ((ModuleBuilder) mod, SignatureHelperType.HELPER_FIELD); - } - - public static SignatureHelper GetLocalVarSigHelper (Module mod) - { - if (mod != null && !(mod is ModuleBuilder)) - throw new ArgumentException ("ModuleBuilder is expected"); - - return new SignatureHelper ((ModuleBuilder) mod, SignatureHelperType.HELPER_LOCAL); - } - - public static SignatureHelper GetLocalVarSigHelper () - { - return new SignatureHelper (null, SignatureHelperType.HELPER_LOCAL); - } - - public static SignatureHelper GetMethodSigHelper (CallingConventions callingConvention, Type returnType) - { - return GetMethodSigHelper (null, callingConvention, (CallingConvention)0, returnType, null); - } - - public static SignatureHelper GetMethodSigHelper (CallingConvention unmanagedCallingConvention, Type returnType) - { - return GetMethodSigHelper (null, CallingConventions.Standard, unmanagedCallingConvention, returnType, null); - } - - public static SignatureHelper GetMethodSigHelper (Module mod, CallingConventions callingConvention, Type returnType) - { - return GetMethodSigHelper (mod, callingConvention, (CallingConvention)0, returnType, null); - } - - public static SignatureHelper GetMethodSigHelper (Module mod, CallingConvention unmanagedCallConv, Type returnType) - { - return GetMethodSigHelper (mod, CallingConventions.Standard, unmanagedCallConv, returnType, null); - } - - public static SignatureHelper GetMethodSigHelper (Module mod, Type returnType, Type[] parameterTypes) - { - return GetMethodSigHelper (mod, CallingConventions.Standard, (CallingConvention)0, returnType, parameterTypes); - } - - // FIXME: "Not implemented" - public static SignatureHelper GetPropertySigHelper (Module mod, Type returnType, Type[] parameterTypes) - { - throw new NotImplementedException (); - } - - // FIXME: "Not implemented" - public static SignatureHelper GetPropertySigHelper (Module mod, Type returnType, - Type [] requiredReturnTypeCustomModifiers, - Type [] optionalReturnTypeCustomModifiers, - Type [] parameterTypes, - Type [] [] requiredParameterTypeCustomModifiers, - Type [] [] optionalParameterTypeCustomModifiers) - { - throw new NotImplementedException (); - } - - // FIXME: "Not implemented" - public static SignatureHelper GetPropertySigHelper (Module mod, - CallingConventions callingConvention, - Type returnType, - Type [] requiredReturnTypeCustomModifiers, - Type [] optionalReturnTypeCustomModifiers, - Type [] parameterTypes, - Type [] [] requiredParameterTypeCustomModifiers, - Type [] [] optionalParameterTypeCustomModifiers) - { - throw new NotImplementedException (); - } - - // - // Grows the given array, and returns the index where the element - // was added - // - static int AppendArray (ref Type [] array, Type t) - { - if (array != null) { - Type[] new_a = new Type [array.Length + 1]; - System.Array.Copy (array, new_a, array.Length); - new_a [array.Length] = t; - array = new_a; - return array.Length-1; - } else { - array = new Type [1]; - array [0] = t; - return 0; - } - } - - // - // Appends the given type array @t into the @array passed at - // position @pos. If there is no array, it gets created - // - // This allows adding data to a null array at position 5 for - // example, creating 4 empty slots before the slot where @t - // is stored. - // - // - static void AppendArrayAt (ref Type [][] array, Type [] t, int pos) - { - int top = Math.Max (pos, array == null ? 0 : array.Length); - Type[][] new_a = new Type [top+1][]; - if (array != null) - System.Array.Copy (array, new_a, top); - new_a [pos] = t; - array = new_a; - } - - static void ValidateParameterModifiers (string name, Type [] parameter_modifiers) - { - foreach (Type modifier in parameter_modifiers){ - if (modifier == null) - throw new ArgumentNullException (name); - if (modifier.IsArray) - throw new ArgumentException ("Array type not permitted", name); - if (modifier.ContainsGenericParameters) - throw new ArgumentException ("Open Generic Type not permitted", name); - } - } - - static void ValidateCustomModifier (int n, Type [][] custom_modifiers, string name) - { - if (custom_modifiers == null) - return; - - if (custom_modifiers.Length != n) - throw new ArgumentException (String.Format ("Custom modifiers length `{0}' does not match the size of the arguments")); - - foreach (Type [] parameter_modifiers in custom_modifiers){ - if (parameter_modifiers == null) - continue; - - ValidateParameterModifiers (name, parameter_modifiers); - } - } - - static Exception MissingFeature () - { - throw new NotImplementedException ("Mono does not currently support setting modOpt/modReq through SignatureHelper"); - } - - // FIXME: "Currently we ignore requiredCustomModifiers and optionalCustomModifiers" - public void AddArguments (Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) - { - if (arguments == null) - throw new ArgumentNullException ("arguments"); - - // For now - if (requiredCustomModifiers != null || optionalCustomModifiers != null){ - throw MissingFeature(); - } - - ValidateCustomModifier (arguments.Length, requiredCustomModifiers, "requiredCustomModifiers"); - ValidateCustomModifier (arguments.Length, optionalCustomModifiers, "optionalCustomModifiers"); - - for (int i = 0; i < arguments.Length; i++){ - AddArgument (arguments [i], - requiredCustomModifiers != null ? requiredCustomModifiers [i] : null, - optionalCustomModifiers != null ? optionalCustomModifiers [i] : null); - } - } - - // FIXME: "pinned is ignored" - public void AddArgument (Type argument, bool pinned) - { - AddArgument (argument); - } - - public void AddArgument (Type argument, Type [] requiredCustomModifiers, Type [] optionalCustomModifiers) - { - if (argument == null) - throw new ArgumentNullException ("argument"); - - if (requiredCustomModifiers != null) - ValidateParameterModifiers ("requiredCustomModifiers", requiredCustomModifiers); - if (optionalCustomModifiers != null) - ValidateParameterModifiers ("optionalCustomModifiers", optionalCustomModifiers); - - int p = AppendArray (ref arguments, argument); - if (requiredCustomModifiers != null) - AppendArrayAt (ref modreqs, requiredCustomModifiers, p); - if (optionalCustomModifiers != null) - AppendArrayAt (ref modopts, optionalCustomModifiers, p); - } - - public void AddArgument (Type clsArgument) - { - if (clsArgument == null) - throw new ArgumentNullException ("clsArgument"); - - AppendArray (ref arguments, clsArgument); - } - - // FIXME: "Not implemented" - public void AddSentinel () - { - throw new NotImplementedException (); - } - - static bool CompareOK (Type [][] one, Type [][] two) - { - if (one == null){ - if (two == null) - return true; - return false; - } else if (two == null) - return false; - - if (one.Length != two.Length) - return false; - - for (int i = 0; i < one.Length; i++){ - Type [] tone = one [i]; - Type [] ttwo = two [i]; - - if (tone == null){ - if (ttwo == null) - continue; - } else if (ttwo == null) - return false; - - if (tone.Length != ttwo.Length) - return false; - - for (int j = 0; j < tone.Length; j++){ - Type uone = tone [j]; - Type utwo = ttwo [j]; - - if (uone == null){ - if (utwo == null) - continue; - return false; - } else if (utwo == null) - return false; - - if (!uone.Equals (utwo)) - return false; - } - } - return true; - } - - public override bool Equals (object obj) - { - SignatureHelper other = obj as SignatureHelper; - if (other == null) - return false; - - if (other.module != module || - other.returnType != returnType || - other.callConv != callConv || - other.unmanagedCallConv != unmanagedCallConv) - return false; - - if (arguments != null){ - if (other.arguments == null) - return false; - if (arguments.Length != other.arguments.Length) - return false; - - for (int i = 0; i < arguments.Length; i++) - if (!other.arguments [i].Equals (arguments [i])) - return false; - } else if (other.arguments != null) - return false; - - return CompareOK (other.modreqs, modreqs) && CompareOK (other.modopts, modopts); - } - - public override int GetHashCode () - { - // Lame, but easy, and will work, and chances are - // you will only need a few of these. - return 0; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern byte[] get_signature_local (); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern byte[] get_signature_field (); - - public byte[] GetSignature () - { - TypeBuilder.ResolveUserTypes (arguments); - - switch (type) { - case SignatureHelperType.HELPER_LOCAL: - return get_signature_local (); - case SignatureHelperType.HELPER_FIELD: - return get_signature_field (); - default: - throw new NotImplementedException (); - } - } - - public override string ToString() { - return "SignatureHelper"; - } - - internal static SignatureHelper GetMethodSigHelper (Module mod, CallingConventions callingConvention, CallingConvention unmanagedCallingConvention, Type returnType, - Type [] parameters) - { - if (mod != null && !(mod is ModuleBuilder)) - throw new ArgumentException ("ModuleBuilder is expected"); - - if (returnType == null) - returnType = typeof (void); - - if (returnType.IsUserType) - throw new NotSupportedException ("User defined subclasses of System.Type are not yet supported."); - if (parameters != null) { - for (int i = 0; i < parameters.Length; ++i) - if (parameters [i].IsUserType) - throw new NotSupportedException ("User defined subclasses of System.Type are not yet supported."); - - } - - SignatureHelper helper = - new SignatureHelper ((ModuleBuilder)mod, SignatureHelperType.HELPER_METHOD); - helper.returnType = returnType; - helper.callConv = callingConvention; - helper.unmanagedCallConv = unmanagedCallingConvention; - - if (parameters != null) { - helper.arguments = new Type [parameters.Length]; - for (int i = 0; i < parameters.Length; ++i) - helper.arguments [i] = parameters [i]; - } - - return helper; - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs deleted file mode 100644 index 7c7255daa7a..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs +++ /dev/null @@ -1,1892 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit.TypeBuilder.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// Marek Safar (marek.safar@gmail.com) -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System; -using System.Text; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Globalization; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics.SymbolStore; - -namespace System.Reflection.Emit -{ - [StructLayout (LayoutKind.Sequential)] - public sealed partial class TypeBuilder : TypeInfo - { -#pragma warning disable 169 - #region Sync with reflection.h - private string tname; // name in internal form - private string nspace; // namespace in internal form - private Type parent; - private Type nesting_type; - internal Type[] interfaces; - internal int num_methods; - internal MethodBuilder[] methods; - internal ConstructorBuilder[] ctors; - internal PropertyBuilder[] properties; - internal int num_fields; - internal FieldBuilder[] fields; - internal EventBuilder[] events; - private CustomAttributeBuilder[] cattrs; - internal TypeBuilder[] subtypes; - internal TypeAttributes attrs; - private int table_idx; - private ModuleBuilder pmodule; - private int class_size; - private PackingSize packing_size; - private IntPtr generic_container; - private GenericTypeParameterBuilder[] generic_params; - private object permissions; - private TypeInfo created; - private int state; - #endregion -#pragma warning restore 169 - - TypeName fullname; - bool createTypeCalled; - private Type underlying_type; - - public const int UnspecifiedTypeSize = 0; - - protected override TypeAttributes GetAttributeFlagsImpl () - { - return attrs; - } - - internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr, int table_idx) - { - this.parent = null; - this.attrs = attr; - this.class_size = UnspecifiedTypeSize; - this.table_idx = table_idx; - this.tname = table_idx == 1 ? "<Module>" : "type_" + table_idx.ToString (); - this.nspace = String.Empty; - this.fullname = TypeIdentifiers.WithoutEscape(this.tname); - pmodule = mb; - } - - internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type) - { - int sep_index; - this.parent = ResolveUserType (parent); - this.attrs = attr; - this.class_size = type_size; - this.packing_size = packing_size; - this.nesting_type = nesting_type; - - check_name ("fullname", name); - - if (parent == null && (attr & TypeAttributes.Interface) != 0 && (attr & TypeAttributes.Abstract) == 0) - throw new InvalidOperationException ("Interface must be declared abstract."); - - sep_index = name.LastIndexOf('.'); - if (sep_index != -1) { - this.tname = name.Substring (sep_index + 1); - this.nspace = name.Substring (0, sep_index); - } else { - this.tname = name; - this.nspace = String.Empty; - } - if (interfaces != null) { - this.interfaces = new Type[interfaces.Length]; - System.Array.Copy (interfaces, this.interfaces, interfaces.Length); - } - pmodule = mb; - - if (((attr & TypeAttributes.Interface) == 0) && (parent == null)) - this.parent = typeof (object); - - // skip .<Module> ? - table_idx = mb.get_next_table_index (this, 0x02, 1); - fullname = GetFullName (); - } - - public override Assembly Assembly { - get {return pmodule.Assembly;} - } - - public override string AssemblyQualifiedName { - get { - return fullname.DisplayName + ", " + Assembly.FullName; - } - } - - public override Type BaseType { - get { - return parent; - } - } - - public override Type DeclaringType { - get { return nesting_type; } - } - - [ComVisible (true)] - public override bool IsSubclassOf (Type c) - { - Type t; - if (c == null) - return false; - if (c == this) - return false; - t = parent; - while (t != null) { - if (c == t) - return true; - t = t.BaseType; - } - return false; - } - - public override Type UnderlyingSystemType { - get { - if (is_created) - return created.UnderlyingSystemType; - - if (IsEnum) { - if (underlying_type != null) - return underlying_type; - throw new InvalidOperationException ( - "Enumeration type is not defined."); - } - - return this; - } - } - - TypeName GetFullName () - { - TypeIdentifier ident = TypeIdentifiers.FromInternal (tname); - if (nesting_type != null) - return TypeNames.FromDisplay (nesting_type.FullName).NestedName (ident); - if ((nspace != null) && (nspace.Length > 0)) - return TypeIdentifiers.FromInternal (nspace, ident); - return ident; - } - - public override string FullName { - get { - return fullname.DisplayName; - } - } - - public override Guid GUID { - get { - check_created (); - return created.GUID; - } - } - - public override Module Module { - get {return pmodule;} - } - - public override string Name { - get {return tname;} - } - - public override string Namespace { - get {return nspace;} - } - - public PackingSize PackingSize { - get {return packing_size;} - } - - public int Size { - get { return class_size; } - } - - public override Type ReflectedType { - get { return nesting_type; } - } - - [ComVisible (true)] - public void AddInterfaceImplementation (Type interfaceType) - { - if (interfaceType == null) - throw new ArgumentNullException ("interfaceType"); - if (interfaceType.IsByRef) - throw new ArgumentException (nameof (interfaceType)); - check_not_created (); - - if (interfaces != null) { - // Check for duplicates - foreach (Type t in interfaces) - if (t == interfaceType) - return; - - Type[] ifnew = new Type [interfaces.Length + 1]; - interfaces.CopyTo (ifnew, 0); - ifnew [interfaces.Length] = interfaceType; - interfaces = ifnew; - } else { - interfaces = new Type [1]; - interfaces [0] = interfaceType; - } - } - - protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, - ParameterModifier[] modifiers) - { - check_created (); - - if (created == typeof (object)) { - /* - * This happens when building corlib. Calling created.GetConstructor - * would return constructors from the real mscorlib, instead of the - * newly built one. - */ - - if (ctors == null) - return null; - - ConstructorBuilder found = null; - int count = 0; - - foreach (ConstructorBuilder cb in ctors) { - if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention) - continue; - found = cb; - count++; - } - - if (count == 0) - return null; - if (types == null) { - if (count > 1) - throw new AmbiguousMatchException (); - return found; - } - MethodBase[] match = new MethodBase [count]; - if (count == 1) - match [0] = found; - else { - count = 0; - foreach (ConstructorInfo m in ctors) { - if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention) - continue; - match [count++] = m; - } - } - if (binder == null) - binder = DefaultBinder; - return (ConstructorInfo) binder.SelectMethod (bindingAttr, match, - types, modifiers); - } - - return created.GetConstructor (bindingAttr, binder, - callConvention, types, modifiers); - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - if (!is_created) - throw new NotSupportedException (); - /* - * MS throws NotSupported here, but we can't because some corlib - * classes make calls to IsDefined. - */ - return CustomAttribute.IsDefined (this, attributeType, inherit); - } - - public override object[] GetCustomAttributes(bool inherit) - { - check_created (); - - return created.GetCustomAttributes (inherit); - } - - public override object[] GetCustomAttributes(Type attributeType, bool inherit) - { - check_created (); - - return created.GetCustomAttributes (attributeType, inherit); - } - - public TypeBuilder DefineNestedType (string name) - { - return DefineNestedType (name, TypeAttributes.NestedPrivate, - typeof (object), null); - } - - public TypeBuilder DefineNestedType (string name, TypeAttributes attr) - { - return DefineNestedType (name, attr, typeof (object), null); - } - - public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent) - { - return DefineNestedType (name, attr, parent, null); - } - - private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces, - PackingSize packSize, int typeSize) - { - // Visibility must be NestedXXX - /* This breaks mcs - if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) || - ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic)) - throw new ArgumentException ("attr", "Bad type flags for nested type."); - */ - if (interfaces != null) { - foreach (Type iface in interfaces) { - if (iface == null) - throw new ArgumentNullException ("interfaces"); - if (iface.IsByRef) - throw new ArgumentException (nameof (interfaces)); - } - } - - TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packSize, typeSize, this); - res.fullname = res.GetFullName (); - pmodule.RegisterTypeName (res, res.fullname); - if (subtypes != null) { - TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1]; - System.Array.Copy (subtypes, new_types, subtypes.Length); - new_types [subtypes.Length] = res; - subtypes = new_types; - } else { - subtypes = new TypeBuilder [1]; - subtypes [0] = res; - } - return res; - } - - [ComVisible (true)] - public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) - { - return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize); - } - - public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typeSize) - { - return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typeSize); - } - - public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packSize) - { - return DefineNestedType (name, attr, parent, null, packSize, UnspecifiedTypeSize); - } - - public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packSize, - int typeSize) - { - return DefineNestedType (name, attr, parent, null, packSize, typeSize); - } - - [ComVisible (true)] - public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) - { - return DefineConstructor (attributes, callingConvention, parameterTypes, null, null); - } - - [ComVisible (true)] - public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) - { - check_not_created (); - if (IsInterface && (attributes & MethodAttributes.Static) == 0) - throw new InvalidOperationException (); - ConstructorBuilder cb = new ConstructorBuilder (this, attributes, - callingConvention, parameterTypes, requiredCustomModifiers, - optionalCustomModifiers); - if (ctors != null) { - ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1]; - System.Array.Copy (ctors, new_ctors, ctors.Length); - new_ctors [ctors.Length] = cb; - ctors = new_ctors; - } else { - ctors = new ConstructorBuilder [1]; - ctors [0] = cb; - } - return cb; - } - - [ComVisible (true)] - public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes) - { - Type parent_type, old_parent_type; - - if (IsInterface) - throw new InvalidOperationException (); - if ((attributes & (MethodAttributes.Static|MethodAttributes.Virtual)) > 0) - throw new ArgumentException (nameof (attributes)); - - if (parent != null) - parent_type = parent; - else - parent_type = typeof (object); - - old_parent_type = parent_type; - parent_type = parent_type.InternalResolve (); - /*This avoids corlib to have self references.*/ - if (parent_type == typeof (object) || parent_type == typeof (ValueType)) - parent_type = old_parent_type; - - ConstructorInfo parent_constructor = - parent_type.GetConstructor ( - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, - null, Type.EmptyTypes, null); - if (parent_constructor == null) { - throw new NotSupportedException ("Parent does" - + " not have a default constructor." - + " The default constructor must be" - + " explicitly defined."); - } - - ConstructorBuilder cb = DefineConstructor (attributes, - CallingConventions.Standard, Type.EmptyTypes); - ILGenerator ig = cb.GetILGenerator (); - ig.Emit (OpCodes.Ldarg_0); - ig.Emit (OpCodes.Call, parent_constructor); - ig.Emit (OpCodes.Ret); - cb.finished = true; - return cb; - } - - private void append_method (MethodBuilder mb) - { - if (methods != null) { - if (methods.Length == num_methods) { - MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2]; - System.Array.Copy (methods, new_methods, num_methods); - methods = new_methods; - } - } else { - methods = new MethodBuilder [1]; - } - methods [num_methods] = mb; - num_methods ++; - } - - public MethodBuilder DefineMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) - { - return DefineMethod (name, attributes, CallingConventions.Standard, - returnType, parameterTypes); - } - - public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) - { - return DefineMethod (name, attributes, callingConvention, returnType, - null, null, parameterTypes, null, null); - } - - public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) - { - check_name ("name", name); - check_not_created (); - if (IsInterface && ( - !((attributes & MethodAttributes.Abstract) != 0) || - !((attributes & MethodAttributes.Virtual) != 0)) && - !(((attributes & MethodAttributes.Static) != 0))) - throw new ArgumentException ("Interface method must be abstract and virtual."); - - if (returnType == null) - returnType = typeof (void); - MethodBuilder res = new MethodBuilder (this, name, attributes, - callingConvention, returnType, - returnTypeRequiredCustomModifiers, - returnTypeOptionalCustomModifiers, parameterTypes, - parameterTypeRequiredCustomModifiers, - parameterTypeOptionalCustomModifiers); - append_method (res); - return res; - } - - public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) - { - return DefinePInvokeMethod (name, dllName, entryName, attributes, - callingConvention, returnType, null, null, parameterTypes, - null, null, nativeCallConv, nativeCharSet); - } - - public MethodBuilder DefinePInvokeMethod ( - string name, - string dllName, - string entryName, MethodAttributes attributes, - CallingConventions callingConvention, - Type returnType, - Type[] returnTypeRequiredCustomModifiers, - Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, - Type[][] parameterTypeRequiredCustomModifiers, - Type[][] parameterTypeOptionalCustomModifiers, - CallingConvention nativeCallConv, - CharSet nativeCharSet) - { - check_name ("name", name); - check_name ("dllName", dllName); - check_name ("entryName", entryName); - if ((attributes & MethodAttributes.Abstract) != 0) - throw new ArgumentException ("PInvoke methods must be static and native and cannot be abstract."); - if (IsInterface) - throw new ArgumentException ("PInvoke methods cannot exist on interfaces."); - check_not_created (); - - MethodBuilder res - = new MethodBuilder ( - this, - name, - attributes, - callingConvention, - returnType, - returnTypeRequiredCustomModifiers, - returnTypeOptionalCustomModifiers, - parameterTypes, - parameterTypeRequiredCustomModifiers, - parameterTypeOptionalCustomModifiers, - dllName, - entryName, - nativeCallConv, - nativeCharSet); - append_method (res); - return res; - } - - public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { - return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, - nativeCallConv, nativeCharSet); - } - - public MethodBuilder DefineMethod (string name, MethodAttributes attributes) - { - return DefineMethod (name, attributes, CallingConventions.Standard); - } - - public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention) - { - return DefineMethod (name, attributes, callingConvention, null, null); - } - - public void DefineMethodOverride (MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) - { - if (methodInfoBody == null) - throw new ArgumentNullException ("methodInfoBody"); - if (methodInfoDeclaration == null) - throw new ArgumentNullException ("methodInfoDeclaration"); - check_not_created (); - if (methodInfoBody.DeclaringType != this) - throw new ArgumentException ("method body must belong to this type"); - - if (methodInfoBody is MethodBuilder) { - MethodBuilder mb = (MethodBuilder)methodInfoBody; - mb.set_override (methodInfoDeclaration); - } - } - - public FieldBuilder DefineField (string fieldName, Type type, FieldAttributes attributes) - { - return DefineField (fieldName, type, null, null, attributes); - } - - public FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes) - { - check_name ("fieldName", fieldName); - if (type == typeof (void)) - throw new ArgumentException ("Bad field type in defining field."); - check_not_created (); - - FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomModifiers, optionalCustomModifiers); - if (fields != null) { - if (fields.Length == num_fields) { - FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2]; - System.Array.Copy (fields, new_fields, num_fields); - fields = new_fields; - } - fields [num_fields] = res; - num_fields ++; - } else { - fields = new FieldBuilder [1]; - fields [0] = res; - num_fields ++; - } - - if (IsEnum) { - if (underlying_type == null && (attributes & FieldAttributes.Static) == 0) - underlying_type = type; - } - - return res; - } - - public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) - { - return DefineProperty (name, attributes, 0, returnType, null, null, parameterTypes, null, null); - } - - public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) - { - return DefineProperty (name, attributes, callingConvention, returnType , null, null, parameterTypes, null, null); - } - - public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) - { - return DefineProperty (name, attributes, 0, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); - } - - public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) - { - check_name ("name", name); - if (parameterTypes != null) - foreach (Type param in parameterTypes) - if (param == null) - throw new ArgumentNullException ("parameterTypes"); - check_not_created (); - - PropertyBuilder res = new PropertyBuilder (this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); - - if (properties != null) { - Array.Resize (ref properties, properties.Length + 1); - properties [properties.Length - 1] = res; - } else { - properties = new PropertyBuilder [1] { res }; - } - return res; - } - - [ComVisible (true)] - public ConstructorBuilder DefineTypeInitializer() - { - return DefineConstructor (MethodAttributes.Public | - MethodAttributes.Static | MethodAttributes.SpecialName | - MethodAttributes.RTSpecialName, CallingConventions.Standard, - null); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern TypeInfo create_runtime_class (); - - private bool is_nested_in (Type t) - { - while (t != null) { - if (t == this) - return true; - else - t = t.DeclaringType; - } - return false; - } - - // Return whenever this type has a ctor defined using DefineMethod () - private bool has_ctor_method () { - MethodAttributes ctor_attrs = MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; - - for (int i = 0; i < num_methods; ++i) { - MethodBuilder mb = (MethodBuilder)(methods[i]); - - if (mb.Name == ConstructorInfo.ConstructorName && (mb.Attributes & ctor_attrs) == ctor_attrs) - return true; - } - - return false; - } - - public Type CreateType () - { - return CreateTypeInfo (); - } - - public - TypeInfo CreateTypeInfo () - { - /* handle nesting_type */ - if (createTypeCalled) - return created; - - if (!IsInterface && (parent == null) && (this != typeof (object)) && (FullName != "<Module>")) { - SetParent (typeof (object)); - } - - // Fire TypeResolve events for fields whose type is an unfinished - // value type. - if (fields != null) { - foreach (FieldBuilder fb in fields) { - if (fb == null) - continue; - Type ft = fb.FieldType; - if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) { - TypeBuilder tb = (TypeBuilder)ft; - if (!tb.is_created) { - throw new NotImplementedException (); - } - } - } - } - - if (parent != null) { - if (parent.IsByRef) - throw new ArgumentException (); - if (IsInterface) - throw new TypeLoadException (); - } - - // - // On classes, define a default constructor if not provided - // - if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") && - (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method ()) - DefineDefaultConstructor (MethodAttributes.Public); - - createTypeCalled = true; - - if (parent != null) { - if (parent.IsSealed) - throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed."); - if (parent.IsGenericTypeDefinition) - throw new BadImageFormatException (); - } - - if (parent == typeof (Enum) && methods != null) - throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because it is an enum with methods."); - if (interfaces != null) { - foreach (var iface in interfaces) { - if (iface.IsNestedPrivate && iface.Assembly != Assembly) - throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because it is implements the inaccessible interface '" + iface.FullName + "'."); - if (iface.IsGenericTypeDefinition) - throw new BadImageFormatException (); - if (!iface.IsInterface) - throw new TypeLoadException (); - if (iface is TypeBuilder && !((TypeBuilder)iface).is_created) - throw new TypeLoadException (); - } - } - - if (fields != null) { - foreach (FieldBuilder fb in fields) { - if (fb == null) - continue; - if (fb.FieldType.IsByRef) - throw new COMException (); - } - } - - if (methods != null) { - bool is_concrete = !IsAbstract; - for (int i = 0; i < num_methods; ++i) { - MethodBuilder mb = (MethodBuilder)(methods[i]); - if (is_concrete && mb.IsAbstract) - throw new InvalidOperationException ("Type is concrete but has abstract method " + mb); - mb.check_override (); - mb.fixup (); - } - } - - if (ctors != null){ - foreach (ConstructorBuilder ctor in ctors) - ctor.fixup (); - } - - ResolveUserTypes (); - - created = create_runtime_class (); - if (created != null) - return created; - return this; - } - - void ResolveUserTypes () { - parent = ResolveUserType (parent); - ResolveUserTypes (interfaces); - if (fields != null) { - foreach (var fb in fields) { - if (fb != null) - fb.ResolveUserTypes (); - } - } - if (methods != null) { - foreach (var mb in methods) { - if (mb != null) - mb.ResolveUserTypes (); - } - } - if (ctors != null) { - foreach (var cb in ctors) { - if (cb != null) - cb.ResolveUserTypes (); - } - } - } - - static internal void ResolveUserTypes (Type[] types) { - if (types != null) - for (int i = 0; i < types.Length; ++i) - types [i] = ResolveUserType (types [i]); - } - - static internal Type ResolveUserType (Type t) { - if (t != null && ((t.GetType ().Assembly != typeof (int).Assembly) || (t is TypeDelegator))) { - t = t.UnderlyingSystemType; - if (t != null && ((t.GetType ().Assembly != typeof (int).Assembly) || (t is TypeDelegator))) - throw new NotSupportedException ("User defined subclasses of System.Type are not yet supported."); - return t; - } else { - return t; - } - } -/* - internal void GenerateDebugInfo (ISymbolWriter symbolWriter) - { - symbolWriter.OpenNamespace (this.Namespace); - - if (methods != null) { - for (int i = 0; i < num_methods; ++i) { - MethodBuilder metb = (MethodBuilder) methods[i]; - metb.GenerateDebugInfo (symbolWriter); - } - } - - if (ctors != null) { - foreach (ConstructorBuilder ctor in ctors) - ctor.GenerateDebugInfo (symbolWriter); - } - - symbolWriter.CloseNamespace (); - - if (subtypes != null) { - for (int i = 0; i < subtypes.Length; ++i) - subtypes [i].GenerateDebugInfo (symbolWriter); - } - } -*/ - [ComVisible (true)] - public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr) - { - if (is_created) - return created.GetConstructors (bindingAttr); - - throw new NotSupportedException (); - } - - internal ConstructorInfo[] GetConstructorsInternal (BindingFlags bindingAttr) - { - if (ctors == null) - return new ConstructorInfo [0]; - ArrayList l = new ArrayList (); - bool match; - MethodAttributes mattrs; - - foreach (ConstructorBuilder c in ctors) { - match = false; - mattrs = c.Attributes; - if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) { - if ((bindingAttr & BindingFlags.Public) != 0) - match = true; - } else { - if ((bindingAttr & BindingFlags.NonPublic) != 0) - match = true; - } - if (!match) - continue; - match = false; - if ((mattrs & MethodAttributes.Static) != 0) { - if ((bindingAttr & BindingFlags.Static) != 0) - match = true; - } else { - if ((bindingAttr & BindingFlags.Instance) != 0) - match = true; - } - if (!match) - continue; - l.Add (c); - } - ConstructorInfo[] result = new ConstructorInfo [l.Count]; - l.CopyTo (result); - return result; - } - - public override Type GetElementType () - { - throw new NotSupportedException (); - } - - public override EventInfo GetEvent (string name, BindingFlags bindingAttr) - { - check_created (); - return created.GetEvent (name, bindingAttr); - } - - /* Needed to keep signature compatibility with MS.NET */ - public override EventInfo[] GetEvents () - { - const BindingFlags DefaultBindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance; - return GetEvents (DefaultBindingFlags); - } - - public override EventInfo[] GetEvents (BindingFlags bindingAttr) - { - if (is_created) - return created.GetEvents (bindingAttr); - throw new NotSupportedException (); - } - - public override FieldInfo GetField (string name, BindingFlags bindingAttr) - { - check_created (); - return created.GetField (name, bindingAttr); - } - - public override FieldInfo[] GetFields (BindingFlags bindingAttr) - { - check_created (); - return created.GetFields (bindingAttr); - } - - public override Type GetInterface (string name, bool ignoreCase) - { - check_created (); - return created.GetInterface (name, ignoreCase); - } - - public override Type[] GetInterfaces () - { - if (is_created) - return created.GetInterfaces (); - - if (interfaces != null) { - Type[] ret = new Type [interfaces.Length]; - interfaces.CopyTo (ret, 0); - return ret; - } else { - return Type.EmptyTypes; - } - } - - public override MemberInfo[] GetMember (string name, MemberTypes type, - BindingFlags bindingAttr) - { - check_created (); - return created.GetMember (name, type, bindingAttr); - } - - public override MemberInfo[] GetMembers (BindingFlags bindingAttr) - { - check_created (); - return created.GetMembers (bindingAttr); - } - - private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type) - { - MethodInfo[] candidates; - bool match; - MethodAttributes mattrs; - - if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) { - MethodInfo [] parent_methods = parent.GetMethods (bindingAttr); - ArrayList parent_candidates = new ArrayList (parent_methods.Length); - - bool flatten = (bindingAttr & BindingFlags.FlattenHierarchy) != 0; - - for (int i = 0; i < parent_methods.Length; i++) { - MethodInfo m = parent_methods [i]; - - mattrs = m.Attributes; - - if (m.IsStatic && !flatten) - continue; - - switch (mattrs & MethodAttributes.MemberAccessMask) { - case MethodAttributes.Public: - match = (bindingAttr & BindingFlags.Public) != 0; - break; - case MethodAttributes.Assembly: - match = (bindingAttr & BindingFlags.NonPublic) != 0; - break; - case MethodAttributes.Private: - match = false; - break; - default: - match = (bindingAttr & BindingFlags.NonPublic) != 0; - break; - } - - if (match) - parent_candidates.Add (m); - } - - if (methods == null) { - candidates = new MethodInfo [parent_candidates.Count]; - parent_candidates.CopyTo (candidates); - } else { - candidates = new MethodInfo [methods.Length + parent_candidates.Count]; - parent_candidates.CopyTo (candidates, 0); - methods.CopyTo (candidates, parent_candidates.Count); - } - } - else - candidates = methods; - - if (candidates == null) - return new MethodInfo [0]; - - ArrayList l = new ArrayList (); - - foreach (MethodInfo c in candidates) { - if (c == null) - continue; - if (name != null) { - if (String.Compare (c.Name, name, ignoreCase) != 0) - continue; - } - match = false; - mattrs = c.Attributes; - if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) { - if ((bindingAttr & BindingFlags.Public) != 0) - match = true; - } else { - if ((bindingAttr & BindingFlags.NonPublic) != 0) - match = true; - } - if (!match) - continue; - match = false; - if ((mattrs & MethodAttributes.Static) != 0) { - if ((bindingAttr & BindingFlags.Static) != 0) - match = true; - } else { - if ((bindingAttr & BindingFlags.Instance) != 0) - match = true; - } - if (!match) - continue; - l.Add (c); - } - - MethodInfo[] result = new MethodInfo [l.Count]; - l.CopyTo (result); - return result; - } - - public override MethodInfo[] GetMethods (BindingFlags bindingAttr) - { - check_created (); - - return GetMethodsByName (null, bindingAttr, false, this); - } - - protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, - Binder binder, - CallingConventions callConvention, - Type[] types, ParameterModifier[] modifiers) - { - check_created (); - - if (types == null) - return created.GetMethod (name, bindingAttr); - - return created.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers); - } - - public override Type GetNestedType (string name, BindingFlags bindingAttr) - { - check_created (); - - if (subtypes == null) - return null; - - foreach (TypeBuilder t in subtypes) { - if (!t.is_created) - continue; - if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) { - if ((bindingAttr & BindingFlags.Public) == 0) - continue; - } else { - if ((bindingAttr & BindingFlags.NonPublic) == 0) - continue; - } - if (t.Name == name) - return t.created; - } - - return null; - } - - public override Type[] GetNestedTypes (BindingFlags bindingAttr) - { - if (!is_created) - throw new NotSupportedException (); - - bool match; - ArrayList result = new ArrayList (); - - if (subtypes == null) - return Type.EmptyTypes; - foreach (TypeBuilder t in subtypes) { - match = false; - if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) { - if ((bindingAttr & BindingFlags.Public) != 0) - match = true; - } else { - if ((bindingAttr & BindingFlags.NonPublic) != 0) - match = true; - } - if (!match) - continue; - result.Add (t); - } - Type[] r = new Type [result.Count]; - result.CopyTo (r); - return r; - } - - public override PropertyInfo[] GetProperties (BindingFlags bindingAttr) - { - check_created (); - return created.GetProperties (bindingAttr); - } - - protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) - { - throw not_supported (); - } - - protected override bool HasElementTypeImpl () - { - // a TypeBuilder can never represent an array, pointer - if (!is_created) - return false; - - return created.HasElementType; - } - - public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) - { - check_created (); - return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); - } - - protected override bool IsArrayImpl () - { - return false; /*A TypeBuilder never represents a non typedef type.*/ - } - - protected override bool IsByRefImpl () - { - return false; /*A TypeBuilder never represents a non typedef type.*/ - } - - protected override bool IsCOMObjectImpl () - { - return ((GetAttributeFlagsImpl () & TypeAttributes.Import) != 0); - } - - protected override bool IsPointerImpl () - { - return false; /*A TypeBuilder never represents a non typedef type.*/ - } - - protected override bool IsPrimitiveImpl () - { - // FIXME - return false; - } - - // FIXME: I doubt just removing this still works. - protected override bool IsValueTypeImpl () - { - Type parent_type = parent; - while (parent_type != null) { - if (parent_type == typeof (ValueType)) - return true; - parent_type = parent_type.BaseType; - } - return false; - } - - public override bool IsSZArray { - get { - return false; - } - } - - public override Type MakeArrayType () - { - return new ArrayType (this, 0); - } - - public override Type MakeArrayType (int rank) - { - if (rank < 1) - throw new IndexOutOfRangeException (); - return new ArrayType (this, rank); - } - - public override Type MakeByRefType () - { - return new ByRefType (this); - } - - public override Type MakeGenericType (params Type [] typeArguments) - { - //return base.MakeGenericType (typeArguments); - - if (!IsGenericTypeDefinition) - throw new InvalidOperationException ("not a generic type definition"); - if (typeArguments == null) - throw new ArgumentNullException ("typeArguments"); - - if (generic_params.Length != typeArguments.Length) - throw new ArgumentException (String.Format ("The type or method has {0} generic parameter(s) but {1} generic argument(s) where provided. A generic argument must be provided for each generic parameter.", generic_params.Length, typeArguments.Length), "typeArguments"); - - foreach (Type t in typeArguments) { - if (t == null) - throw new ArgumentNullException ("typeArguments"); - } - - Type[] copy = new Type [typeArguments.Length]; - typeArguments.CopyTo (copy, 0); - return pmodule.assemblyb.MakeGenericType (this, copy); - } - - public override Type MakePointerType () - { - return new PointerType (this); - } - - public override RuntimeTypeHandle TypeHandle { - get { - check_created (); - return created.TypeHandle; - } - } - - public void SetCustomAttribute (CustomAttributeBuilder customBuilder) - { - if (customBuilder == null) - throw new ArgumentNullException ("customBuilder"); - - string attrname = customBuilder.Ctor.ReflectedType.FullName; - if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") { - byte[] data = customBuilder.Data; - int layout_kind; /* the (stupid) ctor takes a short or an int ... */ - layout_kind = (int)data [2]; - layout_kind |= ((int)data [3]) << 8; - attrs &= ~TypeAttributes.LayoutMask; - switch ((LayoutKind)layout_kind) { - case LayoutKind.Auto: - attrs |= TypeAttributes.AutoLayout; - break; - case LayoutKind.Explicit: - attrs |= TypeAttributes.ExplicitLayout; - break; - case LayoutKind.Sequential: - attrs |= TypeAttributes.SequentialLayout; - break; - default: - // we should ignore it since it can be any value anyway... - throw new Exception ("Error in customattr"); - } - - var ctor_type = customBuilder.Ctor is ConstructorBuilder ? ((ConstructorBuilder)customBuilder.Ctor).parameters[0] : customBuilder.Ctor.GetParametersInternal()[0].ParameterType; - int pos = 6; - if (ctor_type.FullName == "System.Int16") - pos = 4; - int nnamed = (int)data [pos++]; - nnamed |= ((int)data [pos++]) << 8; - for (int i = 0; i < nnamed; ++i) { - //byte named_type = data [pos++]; - pos ++; - byte type = data [pos++]; - int len; - string named_name; - - if (type == 0x55) { - len = CustomAttributeBuilder.decode_len (data, pos, out pos); - //string named_typename = - CustomAttributeBuilder.string_from_bytes (data, pos, len); - pos += len; - // FIXME: Check that 'named_type' and 'named_typename' match, etc. - // See related code/FIXME in mono/mono/metadata/reflection.c - } - - len = CustomAttributeBuilder.decode_len (data, pos, out pos); - named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len); - pos += len; - /* all the fields are integers in StructLayout */ - int value = (int)data [pos++]; - value |= ((int)data [pos++]) << 8; - value |= ((int)data [pos++]) << 16; - value |= ((int)data [pos++]) << 24; - switch (named_name) { - case "CharSet": - switch ((CharSet)value) { - case CharSet.None: - case CharSet.Ansi: - attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass); - break; - case CharSet.Unicode: - attrs &= ~TypeAttributes.AutoClass; - attrs |= TypeAttributes.UnicodeClass; - break; - case CharSet.Auto: - attrs &= ~TypeAttributes.UnicodeClass; - attrs |= TypeAttributes.AutoClass; - break; - default: - break; // error out... - } - break; - case "Pack": - packing_size = (PackingSize)value; - break; - case "Size": - class_size = value; - break; - default: - break; // error out... - } - } - return; - } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") { - attrs |= TypeAttributes.SpecialName; - return; - } else if (attrname == "System.SerializableAttribute") { - attrs |= TypeAttributes.Serializable; - return; - } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") { - attrs |= TypeAttributes.Import; - return; - } else if (attrname == "System.Security.SuppressUnmanagedCodeSecurityAttribute") { - attrs |= TypeAttributes.HasSecurity; - } - - if (cattrs != null) { - CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; - cattrs.CopyTo (new_array, 0); - new_array [cattrs.Length] = customBuilder; - cattrs = new_array; - } else { - cattrs = new CustomAttributeBuilder [1]; - cattrs [0] = customBuilder; - } - } - - [ComVisible (true)] - public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute) - { - SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute)); - } - - public EventBuilder DefineEvent (string name, EventAttributes attributes, Type eventtype) - { - check_name ("name", name); - if (eventtype == null) - throw new ArgumentNullException ("type"); - check_not_created (); - if (eventtype.IsByRef) - throw new ArgumentException (nameof (eventtype)); - EventBuilder res = new EventBuilder (this, name, attributes, eventtype); - if (events != null) { - EventBuilder[] new_events = new EventBuilder [events.Length+1]; - System.Array.Copy (events, new_events, events.Length); - new_events [events.Length] = res; - events = new_events; - } else { - events = new EventBuilder [1]; - events [0] = res; - } - return res; - } - - public FieldBuilder DefineInitializedData (string name, byte[] data, FieldAttributes attributes) { - if (data == null) - throw new ArgumentNullException ("data"); - - FieldBuilder res = DefineUninitializedData (name, data.Length, attributes); - res.SetRVAData (data); - return res; - } - - public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes) - { - if (name == null) - throw new ArgumentNullException ("name"); - if (name.Length == 0) - throw new ArgumentException ("Empty name is not legal", "name"); - if ((size <= 0) || (size > 0x3f0000)) - throw new ArgumentException ("Data size must be > 0 and < 0x3f0000"); - check_not_created (); - - string typeName = "$ArrayType$" + size; - TypeIdentifier ident = TypeIdentifiers.WithoutEscape (typeName); - Type datablobtype = pmodule.GetRegisteredType (fullname.NestedName(ident)); - if (datablobtype == null) { - TypeBuilder tb = DefineNestedType (typeName, - TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed, - typeof (ValueType), null, PackingSize.Size1, size); - tb.CreateType (); - datablobtype = tb; - } - return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA); - } - - public TypeToken TypeToken { - get { - return new TypeToken (0x02000000 | table_idx); - } - } - - public void SetParent (Type parent) - { - check_not_created (); - - if (parent == null) { - if ((attrs & TypeAttributes.Interface) != 0) { - if ((attrs & TypeAttributes.Abstract) == 0) - throw new InvalidOperationException ("Interface must be declared abstract."); - this.parent = null; - } else { - this.parent = typeof (object); - } - } else { - if (parent.IsInterface) - throw new ArgumentException (nameof (parent)); - this.parent = parent; - } - this.parent = ResolveUserType (this.parent); - } - - internal int get_next_table_index (object obj, int table, int count) { - return pmodule.get_next_table_index (obj, table, count); - } - - [ComVisible (true)] - public override InterfaceMapping GetInterfaceMap (Type interfaceType) - { - if (created == null) - throw new NotSupportedException ("This method is not implemented for incomplete types."); - - return created.GetInterfaceMap (interfaceType); - } - - internal override Type InternalResolve () - { - check_created (); - return created; - } - - internal override Type RuntimeResolve () - { - check_created (); - return created; - } - - internal bool is_created { - get { - return createTypeCalled; - } - } - - private Exception not_supported () - { - return new NotSupportedException ("The invoked member is not supported in a dynamic module."); - } - - internal void check_not_created () - { - if (is_created) - throw new InvalidOperationException ("Unable to change after type has been created."); - } - - private void check_created () - { - if (!is_created) - throw not_supported (); - } - - private void check_name (string argName, string name) - { - if (name == null) - throw new ArgumentNullException (argName); - if (name.Length == 0) - throw new ArgumentException ("Empty name is not legal", argName); - if (name [0] == ((char)0)) - throw new ArgumentException ("Illegal name", argName); - } - - public override String ToString () - { - return FullName; - } - - // FIXME: - public override bool IsAssignableFrom (Type c) - { - return base.IsAssignableFrom (c); - } - - // FIXME: "arrays" - internal bool IsAssignableTo (Type c) - { - if (c == this) - return true; - - if (c.IsInterface) { - if (parent != null && is_created) { - if (c.IsAssignableFrom (parent)) - return true; - } - - if (interfaces == null) - return false; - foreach (Type t in interfaces) - if (c.IsAssignableFrom (t)) - return true; - if (!is_created) - return false; - } - - if (parent == null) - return c == typeof (object); - else - return c.IsAssignableFrom (parent); - } - - public bool IsCreated () - { - return is_created; - } - - public override Type[] GetGenericArguments () - { - if (generic_params == null) - return null; - Type[] args = new Type [generic_params.Length]; - generic_params.CopyTo (args, 0); - return args; - } - - public override Type GetGenericTypeDefinition () - { - if (generic_params == null) - throw new InvalidOperationException ("Type is not generic"); - return this; - } - - public override bool ContainsGenericParameters { - get { - return generic_params != null; - } - } - - public override bool IsGenericParameter { - get { - return false; - } - } - - public override GenericParameterAttributes GenericParameterAttributes { - get { return GenericParameterAttributes.None; } - } - - public override bool IsGenericTypeDefinition { - get { - return generic_params != null; - } - } - - public override bool IsGenericType { - get { return IsGenericTypeDefinition; } - } - - // FIXME: - public override int GenericParameterPosition { - get { - return 0; - } - } - - public override MethodBase DeclaringMethod { - get { - return null; - } - } - - public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names) - { - if (names == null) - throw new ArgumentNullException ("names"); - if (names.Length == 0) - throw new ArgumentException ("names"); - - generic_params = new GenericTypeParameterBuilder [names.Length]; - for (int i = 0; i < names.Length; i++) { - string item = names [i]; - if (item == null) - throw new ArgumentNullException ("names"); - generic_params [i] = new GenericTypeParameterBuilder (this, null, item, i); - } - - return generic_params; - } - - public static ConstructorInfo GetConstructor (Type type, ConstructorInfo constructor) - { - /*FIXME I would expect the same checks of GetMethod here*/ - if (type == null) - throw new ArgumentException ("Type is not generic", "type"); - - if (!type.IsGenericType) - throw new ArgumentException ("Type is not a generic type", "type"); - - if (type.IsGenericTypeDefinition) - throw new ArgumentException ("Type cannot be a generic type definition", "type"); - - if (constructor == null) - throw new NullReferenceException (); //MS raises this instead of an ArgumentNullException - - if (!constructor.DeclaringType.IsGenericTypeDefinition) - throw new ArgumentException ("constructor declaring type is not a generic type definition", "constructor"); - if (constructor.DeclaringType != type.GetGenericTypeDefinition ()) - throw new ArgumentException ("constructor declaring type is not the generic type definition of type", "constructor"); - - ConstructorInfo res = type.GetConstructor (constructor); - if (res == null) - throw new ArgumentException ("constructor not found"); - - return res; - } - - static bool IsValidGetMethodType (Type type) - { - if (type is TypeBuilder || type is TypeBuilderInstantiation) - return true; - /*GetMethod() must work with TypeBuilders after CreateType() was called.*/ - if (type.Module is ModuleBuilder) - return true; - if (type.IsGenericParameter) - return false; - - Type[] inst = type.GetGenericArguments (); - if (inst == null) - return false; - for (int i = 0; i < inst.Length; ++i) { - if (IsValidGetMethodType (inst [i])) - return true; - } - return false; - } - - public static MethodInfo GetMethod (Type type, MethodInfo method) - { - if (!IsValidGetMethodType (type)) - throw new ArgumentException ("type is not TypeBuilder but " + type.GetType (), "type"); - - if (type is TypeBuilder && type.ContainsGenericParameters) - type = type.MakeGenericType (type.GetGenericArguments ()); - - if (!type.IsGenericType) - throw new ArgumentException ("type is not a generic type", "type"); - - if (!method.DeclaringType.IsGenericTypeDefinition) - throw new ArgumentException ("method declaring type is not a generic type definition", "method"); - if (method.DeclaringType != type.GetGenericTypeDefinition ()) - throw new ArgumentException ("method declaring type is not the generic type definition of type", "method"); - if (method == null) - throw new NullReferenceException (); //MS raises this instead of an ArgumentNullException - - MethodInfo res = type.GetMethod (method); - if (res == null) - throw new ArgumentException (String.Format ("method {0} not found in type {1}", method.Name, type)); - - return res; - } - - public static FieldInfo GetField (Type type, FieldInfo field) - { - if (!type.IsGenericType) - throw new ArgumentException ("Type is not a generic type", "type"); - - if (type.IsGenericTypeDefinition) - throw new ArgumentException ("Type cannot be a generic type definition", "type"); - - if (field is FieldOnTypeBuilderInst) - throw new ArgumentException ("The specified field must be declared on a generic type definition.", "field"); - - if (field.DeclaringType != type.GetGenericTypeDefinition ()) - throw new ArgumentException ("field declaring type is not the generic type definition of type", "method"); - - FieldInfo res = type.GetField (field); - if (res == null) - throw new System.Exception ("field not found"); - else - return res; - } - - internal override bool IsUserType { - get { - return false; - } - } - - internal override bool IsTypeBuilder () => true; - - public override bool IsConstructedGenericType { - get { return false; } - } - - public override bool IsAssignableFrom (TypeInfo typeInfo) - { - return base.IsAssignableFrom (typeInfo); - } - - internal static bool SetConstantValue (Type destType, Object value, ref Object destValue) - { - // Mono: This is based on the CoreCLR - // TypeBuilder.SetConstantValue except it writes to an - // out argument instead of doing an icall, and it uses - // TypeCode instead of CorElementType (like - // MonoTypeEnum) which we don't have in our corlib and - // our member fields are different. - - // This is a helper function that is used by ParameterBuilder, PropertyBuilder, - // and FieldBuilder to validate a default value and save it in the meta-data. - - if (value != null) { - Type type = value.GetType (); - - // We should allow setting a constant value on a ByRef parameter - if (destType.IsByRef) - destType = destType.GetElementType (); - - // Convert nullable types to their underlying type. - // This is necessary for nullable enum types to pass the IsEnum check that's coming next. - destType = Nullable.GetUnderlyingType (destType) ?? destType; - - if (destType.IsEnum) - { - // | UnderlyingSystemType | Enum.GetUnderlyingType() | IsEnum - // ----------------------------------|---------------------------|---------------------------|--------- - // runtime Enum Type | self | underlying type of enum | TRUE - // EnumBuilder | underlying type of enum | underlying type of enum* | TRUE - // TypeBuilder of enum types** | underlying type of enum | Exception | TRUE - // TypeBuilder of enum types (baked) | runtime enum type | Exception | TRUE - - // *: the behavior of Enum.GetUnderlyingType(EnumBuilder) might change in the future - // so let's not depend on it. - // **: created with System.Enum as the parent type. - - // The above behaviors might not be the most consistent but we have to live with them. - - Type underlyingType; - EnumBuilder enumBldr; - TypeBuilder typeBldr; - if ((enumBldr = destType as EnumBuilder) != null) { - underlyingType = enumBldr.GetEnumUnderlyingType (); - - // The constant value supplied should match either the baked enum type or its underlying type - // we don't need to compare it with the EnumBuilder itself because you can never have an object of that type - if (!((enumBldr.GetTypeBuilder ().is_created && type == enumBldr.GetTypeBuilder ().created) || - type == underlyingType)) - throw_argument_ConstantDoesntMatch (); - } else if ((typeBldr = destType as TypeBuilder) != null) { - underlyingType = typeBldr.underlying_type; - - // The constant value supplied should match either the baked enum type or its underlying type - // typeBldr.m_enumUnderlyingType is null if the user hasn't created a "value__" field on the enum - if (underlyingType == null || (type != typeBldr.UnderlyingSystemType && type != underlyingType)) - throw_argument_ConstantDoesntMatch (); - } else { - // must be a runtime Enum Type - - // Debug.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder."); - - underlyingType = Enum.GetUnderlyingType (destType); - - // The constant value supplied should match either the enum itself or its underlying type - if (type != destType && type != underlyingType) - throw_argument_ConstantDoesntMatch (); - } - - type = underlyingType; - } else { - // Note that it is non CLS compliant if destType != type. But RefEmit never guarantees CLS-Compliance. - if (!destType.IsAssignableFrom (type)) - throw_argument_ConstantDoesntMatch (); - } - - TypeCode corType = Type.GetTypeCode (type); - - switch (corType) - { - case TypeCode.Byte: - case TypeCode.SByte: - case TypeCode.Boolean: - case TypeCode.Int16: - case TypeCode.UInt16: - case TypeCode.Char: - case TypeCode.Int32: - case TypeCode.UInt32: - case TypeCode.Single: - case TypeCode.Int64: - case TypeCode.UInt64: - case TypeCode.Double: - destValue = value; - return true; - case TypeCode.String: - destValue = value; - return true; - case TypeCode.DateTime: - //date is a I8 representation - long ticks = ((DateTime)value).Ticks; - destValue = ticks; - return true; - default: - throw new ArgumentException(type.ToString() + " is not a supported constant type."); - } - } else { - // A null default value in metadata is permissible even for non-nullable value types. - // (See ECMA-335 II.15.4.1.4 "The .param directive" and II.22.9 "Constant" for details.) - // This is how the Roslyn compilers generally encode `default(TValueType)` default values. - - destValue = null; - return true; - } - } - - private static void throw_argument_ConstantDoesntMatch () - { - throw new ArgumentException("Constant does not match the defined type."); - } - - public override bool IsTypeDefinition => true; - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs deleted file mode 100644 index 00b5432b33a..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs +++ /dev/null @@ -1,512 +0,0 @@ -#nullable disable - -// -// System.Reflection.Emit.TypeBuilderInstantiation -// -// Sean MacIsaac (macisaac@ximian.com) -// Paolo Molaro (lupus@ximian.com) -// Patrik Torstensson (patrik.torstensson@labs2.com) -// -// (C) 2001 Ximian, Inc. -// - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#if MONO_FEATURE_SRE -using System.Reflection; -using System.Reflection.Emit; -using System.Collections; -using System.Runtime.CompilerServices; -using System.Globalization; -using System.Runtime.Serialization; -using System.Text; -using System.Runtime.InteropServices; - -namespace System.Reflection.Emit -{ - /* - * TypeBuilderInstantiation represents an instantiation of a generic TypeBuilder. - */ - [StructLayout (LayoutKind.Sequential)] - sealed class TypeBuilderInstantiation : - TypeInfo - { - #region Keep in sync with object-internals.h MonoReflectionGenericClass -#pragma warning disable 649 - internal Type generic_type; - Type[] type_arguments; -#pragma warning restore 649 - #endregion - - Hashtable fields, ctors, methods; - - internal TypeBuilderInstantiation () - { - // this should not be used - throw new InvalidOperationException (); - } - - internal TypeBuilderInstantiation (Type tb, Type[] args) - { - this.generic_type = tb; - this.type_arguments = args; - } - - internal override Type InternalResolve () - { - Type gtd = generic_type.InternalResolve (); - Type[] args = new Type [type_arguments.Length]; - for (int i = 0; i < type_arguments.Length; ++i) - args [i] = type_arguments [i].InternalResolve (); - return gtd.MakeGenericType (args); - } - - // Called from the runtime to return the corresponding finished Type object - internal override Type RuntimeResolve () - { - if (generic_type is TypeBuilder && !(generic_type as TypeBuilder).IsCreated ()) - throw new NotImplementedException (); - for (int i = 0; i < type_arguments.Length; ++i) { - var t = type_arguments [i]; - if (t is TypeBuilder && !(t as TypeBuilder).IsCreated ()) - throw new NotImplementedException (); - } - return InternalResolve (); - } - - internal bool IsCreated { - get { - TypeBuilder tb = generic_type as TypeBuilder; - return tb != null ? tb.is_created : true; - } - } - - private const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | - BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; - - Type GetParentType () - { - return InflateType (generic_type.BaseType); - } - - internal Type InflateType (Type type) - { - return InflateType (type, type_arguments, null); - } - - internal Type InflateType (Type type, Type[] method_args) - { - return InflateType (type, type_arguments, method_args); - } - - internal static Type InflateType (Type type, Type[] type_args, Type[] method_args) - { - if (type == null) - return null; - if (!type.IsGenericParameter && !type.ContainsGenericParameters) - return type; - if (type.IsGenericParameter) { - if (type.DeclaringMethod == null) - return type_args == null ? type : type_args [type.GenericParameterPosition]; - return method_args == null ? type : method_args [type.GenericParameterPosition]; - } - if (type.IsPointer) - return InflateType (type.GetElementType (), type_args, method_args).MakePointerType (); - if (type.IsByRef) - return InflateType (type.GetElementType (), type_args, method_args).MakeByRefType (); - if (type.IsArray) { - if (type.GetArrayRank () > 1) - return InflateType (type.GetElementType (), type_args, method_args).MakeArrayType (type.GetArrayRank ()); - - if (type.ToString ().EndsWith ("[*]", StringComparison.Ordinal)) /*FIXME, the reflection API doesn't offer a way around this*/ - return InflateType (type.GetElementType (), type_args, method_args).MakeArrayType (1); - return InflateType (type.GetElementType (), type_args, method_args).MakeArrayType (); - } - - Type[] args = type.GetGenericArguments (); - for (int i = 0; i < args.Length; ++i) - args [i] = InflateType (args [i], type_args, method_args); - - Type gtd = type.IsGenericTypeDefinition ? type : type.GetGenericTypeDefinition (); - return gtd.MakeGenericType (args); - } - - public override Type BaseType { - get { return generic_type.BaseType; } - } - - public override Type[] GetInterfaces () - { - throw new NotSupportedException (); - } - - protected override bool IsValueTypeImpl () - { - return generic_type.IsValueType; - } - - internal override MethodInfo GetMethod (MethodInfo fromNoninstanciated) - { - if (methods == null) - methods = new Hashtable (); - if (!methods.ContainsKey (fromNoninstanciated)) - methods [fromNoninstanciated] = new MethodOnTypeBuilderInst (this, fromNoninstanciated); - return (MethodInfo)methods [fromNoninstanciated]; - } - - internal override ConstructorInfo GetConstructor (ConstructorInfo fromNoninstanciated) - { - if (ctors == null) - ctors = new Hashtable (); - if (!ctors.ContainsKey (fromNoninstanciated)) - ctors [fromNoninstanciated] = new ConstructorOnTypeBuilderInst (this, fromNoninstanciated); - return (ConstructorInfo)ctors [fromNoninstanciated]; - } - - internal override FieldInfo GetField (FieldInfo fromNoninstanciated) - { - if (fields == null) - fields = new Hashtable (); - if (!fields.ContainsKey (fromNoninstanciated)) - fields [fromNoninstanciated] = new FieldOnTypeBuilderInst (this, fromNoninstanciated); - return (FieldInfo)fields [fromNoninstanciated]; - } - - public override MethodInfo[] GetMethods (BindingFlags bf) - { - throw new NotSupportedException (); - } - - public override ConstructorInfo[] GetConstructors (BindingFlags bf) - { - throw new NotSupportedException (); - } - - public override FieldInfo[] GetFields (BindingFlags bf) - { - throw new NotSupportedException (); - } - - public override PropertyInfo[] GetProperties (BindingFlags bf) - { - throw new NotSupportedException (); - } - - public override EventInfo[] GetEvents (BindingFlags bf) - { - throw new NotSupportedException (); - } - - public override Type[] GetNestedTypes (BindingFlags bf) - { - throw new NotSupportedException (); - } - - public override bool IsAssignableFrom (Type c) - { - throw new NotSupportedException (); - } - - public override Type UnderlyingSystemType { - get { return this; } - } - - public override Assembly Assembly { - get { return generic_type.Assembly; } - } - - public override Module Module { - get { return generic_type.Module; } - } - - public override string Name { - get { return generic_type.Name; } - } - - public override string Namespace { - get { return generic_type.Namespace; } - } - - public override string FullName { - get { return format_name (true, false); } - } - - public override string AssemblyQualifiedName { - get { return format_name (true, true); } - } - - public override Guid GUID { - get { throw new NotSupportedException (); } - } - - string format_name (bool full_name, bool assembly_qualified) - { - StringBuilder sb = new StringBuilder (generic_type.FullName); - - sb.Append ("["); - for (int i = 0; i < type_arguments.Length; ++i) { - if (i > 0) - sb.Append (","); - - string name; - if (full_name) { - string assemblyName = type_arguments [i].Assembly.FullName; - name = type_arguments [i].FullName; - if (name != null && assemblyName != null) - name = name + ", " + assemblyName; - } else { - name = type_arguments [i].ToString (); - } - if (name == null) { - return null; - } - if (full_name) - sb.Append ("["); - sb.Append (name); - if (full_name) - sb.Append ("]"); - } - sb.Append ("]"); - if (assembly_qualified) { - sb.Append (", "); - sb.Append (generic_type.Assembly.FullName); - } - return sb.ToString (); - } - - public override string ToString () - { - return format_name (false, false); - } - - public override Type GetGenericTypeDefinition () - { - return generic_type; - } - - public override Type[] GetGenericArguments () - { - Type[] ret = new Type [type_arguments.Length]; - type_arguments.CopyTo (ret, 0); - return ret; - } - - public override bool ContainsGenericParameters { - get { - foreach (Type t in type_arguments) { - if (t.ContainsGenericParameters) - return true; - } - return false; - } - } - - public override bool IsGenericTypeDefinition { - get { return false; } - } - - public override bool IsGenericType { - get { return true; } - } - - public override Type DeclaringType { - get { return generic_type.DeclaringType; } - } - - public override RuntimeTypeHandle TypeHandle { - get { - throw new NotSupportedException (); - } - } - - public override Type MakeArrayType () - { - return new ArrayType (this, 0); - } - - public override Type MakeArrayType (int rank) - { - if (rank < 1) - throw new IndexOutOfRangeException (); - return new ArrayType (this, rank); - } - - public override Type MakeByRefType () - { - return new ByRefType (this); - } - - public override Type MakePointerType () - { - return new PointerType (this); - } - - public override Type GetElementType () - { - throw new NotSupportedException (); - } - - protected override bool HasElementTypeImpl () - { - return false; - } - - protected override bool IsCOMObjectImpl () - { - return false; - } - - protected override bool IsPrimitiveImpl () - { - return false; - } - - protected override bool IsArrayImpl () - { - return false; - } - - protected override bool IsByRefImpl () - { - return false; - } - - protected override bool IsPointerImpl () - { - return false; - } - - protected override TypeAttributes GetAttributeFlagsImpl () - { - return generic_type.Attributes; - } - - //stuff that throws - public override Type GetInterface (string name, bool ignoreCase) - { - throw new NotSupportedException (); - } - - public override EventInfo GetEvent (string name, BindingFlags bindingAttr) - { - throw new NotSupportedException (); - } - - public override FieldInfo GetField( string name, BindingFlags bindingAttr) - { - throw new NotSupportedException (); - } - - public override MemberInfo[] GetMembers (BindingFlags bindingAttr) - { - throw new NotSupportedException (); - } - - public override Type GetNestedType (string name, BindingFlags bindingAttr) - { - throw new NotSupportedException (); - } - - public override object InvokeMember (string name, BindingFlags invokeAttr, - Binder binder, object target, object[] args, - ParameterModifier[] modifiers, - CultureInfo culture, string[] namedParameters) - { - throw new NotSupportedException (); - } - - protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, - ParameterModifier[] modifiers) - { - throw new NotSupportedException (); - } - - protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, - Type returnType, Type[] types, ParameterModifier[] modifiers) - { - throw new NotSupportedException (); - } - - protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, - Binder binder, - CallingConventions callConvention, - Type[] types, - ParameterModifier[] modifiers) - { - throw new NotSupportedException (); - } - - //MemberInfo - public override bool IsDefined (Type attributeType, bool inherit) - { - throw new NotSupportedException (); - } - - public override object [] GetCustomAttributes (bool inherit) - { - if (IsCreated) - return generic_type.GetCustomAttributes (inherit); - throw new NotSupportedException (); - } - - public override object [] GetCustomAttributes (Type attributeType, bool inherit) - { - if (IsCreated) - return generic_type.GetCustomAttributes (attributeType, inherit); - throw new NotSupportedException (); - } - - internal override bool IsUserType { - get { - foreach (var t in type_arguments) { - if (t.IsUserType) - return true; - } - return false; - } - } - - internal static Type MakeGenericType (Type type, Type[] typeArguments) - { - return new TypeBuilderInstantiation (type, typeArguments); - } - - public override bool IsTypeDefinition => false; - - public override bool IsConstructedGenericType => true; - } -} -#else -namespace System.Reflection.Emit -{ - abstract class TypeBuilderInstantiation : TypeInfo - { - internal static Type MakeGenericType (Type type, Type[] typeArguments) - { - throw new NotSupportedException ("User types are not supported under full aot"); - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/UnmanagedMarshal.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Emit/UnmanagedMarshal.cs deleted file mode 100644 index bbe9c3894ed..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Emit/UnmanagedMarshal.cs +++ /dev/null @@ -1,138 +0,0 @@ -#nullable disable - -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// -// System.Reflection.Emit/UnmanagedMarshal.cs -// -// Author: -// Paolo Molaro (lupus@ximian.com) -// -// (C) 2001-2002 Ximian, Inc. http://www.ximian.com -// - -#if MONO_FEATURE_SRE -using System.Reflection.Emit; -using System.Runtime.InteropServices; -using System; - -namespace System.Reflection.Emit { - - [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")] - [ComVisible (true)] - [Serializable] - [StructLayout (LayoutKind.Sequential)] - public sealed class UnmanagedMarshal { -#pragma warning disable 169, 414 - private int count; - private UnmanagedType t; - private UnmanagedType tbase; - string guid; - string mcookie; - string marshaltype; - internal Type marshaltyperef; - private int param_num; - private bool has_size; -#pragma warning restore 169, 414 - - private UnmanagedMarshal (UnmanagedType maint, int cnt) { - count = cnt; - t = maint; - tbase = maint; - } - private UnmanagedMarshal (UnmanagedType maint, UnmanagedType elemt) { - count = 0; - t = maint; - tbase = elemt; - } - - public UnmanagedType BaseType { - get { - if (t == UnmanagedType.LPArray) - throw new ArgumentException (); - -#if FEATURE_COMINTEROP - if (t == UnmanagedType.SafeArray) - throw new ArgumentException (); -#endif - return tbase; - } - } - - public int ElementCount { - get {return count;} - } - - public UnmanagedType GetUnmanagedType { - get {return t;} - } - - public Guid IIDGuid { - get {return new Guid (guid);} - } - - public static UnmanagedMarshal DefineByValArray( int elemCount) { - return new UnmanagedMarshal (UnmanagedType.ByValArray, elemCount); - } - - public static UnmanagedMarshal DefineByValTStr( int elemCount) { - return new UnmanagedMarshal (UnmanagedType.ByValTStr, elemCount); - } - - public static UnmanagedMarshal DefineLPArray( UnmanagedType elemType) { - return new UnmanagedMarshal (UnmanagedType.LPArray, elemType); - } -#if FEATURE_COMINTEROP - public static UnmanagedMarshal DefineSafeArray( UnmanagedType elemType) { - return new UnmanagedMarshal (UnmanagedType.SafeArray, elemType); - } -#endif - public static UnmanagedMarshal DefineUnmanagedMarshal( UnmanagedType unmanagedType) { - return new UnmanagedMarshal (unmanagedType, unmanagedType); - } -#if FEATURE_COMINTEROP - internal static UnmanagedMarshal DefineCustom (Type typeref, string cookie, string mtype, Guid id) { - UnmanagedMarshal res = new UnmanagedMarshal (UnmanagedType.CustomMarshaler, UnmanagedType.CustomMarshaler); - res.mcookie = cookie; - res.marshaltype = mtype; - res.marshaltyperef = typeref; - if (id == Guid.Empty) - res.guid = String.Empty; - else - res.guid = id.ToString (); - return res; - } -#endif - // sizeConst and sizeParamIndex can be -1 meaning they are not specified - internal static UnmanagedMarshal DefineLPArrayInternal (UnmanagedType elemType, int sizeConst, int sizeParamIndex) { - UnmanagedMarshal res = new UnmanagedMarshal (UnmanagedType.LPArray, elemType); - res.count = sizeConst; - res.param_num = sizeParamIndex; - res.has_size = true; - - return res; - } - } -} -#endif diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/FieldInfo.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/FieldInfo.Mono.cs deleted file mode 100644 index ae68d8a40da..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/FieldInfo.Mono.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection -{ - partial class FieldInfo - { - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern FieldInfo internal_from_handle_type (IntPtr field_handle, IntPtr type_handle); - - public static FieldInfo GetFieldFromHandle (RuntimeFieldHandle handle) - { - if (handle.IsNullHandle ()) - throw new ArgumentException (SR.Argument_InvalidHandle); - return internal_from_handle_type (handle.Value, IntPtr.Zero); - } - - public static FieldInfo GetFieldFromHandle (RuntimeFieldHandle handle, RuntimeTypeHandle declaringType) - { - if (handle.IsNullHandle ()) - throw new ArgumentException (SR.Argument_InvalidHandle); - FieldInfo fi = internal_from_handle_type (handle.Value, declaringType.Value); - if (fi == null) - throw new ArgumentException ("The field handle and the type handle are incompatible."); - return fi; - } - - internal virtual int GetFieldOffset () - { - throw NotImplemented.ByDesign; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern MarshalAsAttribute get_marshal_info (); - - internal object[] GetPseudoCustomAttributes () - { - int count = 0; - - if (IsNotSerialized) - count ++; - - if (DeclaringType.IsExplicitLayout) - count ++; - - MarshalAsAttribute marshalAs = get_marshal_info (); - if (marshalAs != null) - count ++; - - if (count == 0) - return null; - object[] attrs = new object [count]; - count = 0; - - if (IsNotSerialized) - attrs [count ++] = new NonSerializedAttribute (); - if (DeclaringType.IsExplicitLayout) - attrs [count ++] = new FieldOffsetAttribute (GetFieldOffset ()); - if (marshalAs != null) - attrs [count ++] = marshalAs; - - return attrs; - } - - internal CustomAttributeData[] GetPseudoCustomAttributesData () - { - int count = 0; - - if (IsNotSerialized) - count++; - - if (DeclaringType.IsExplicitLayout) - count++; - - MarshalAsAttribute marshalAs = get_marshal_info (); - if (marshalAs != null) - count++; - - if (count == 0) - return null; - CustomAttributeData[] attrsData = new CustomAttributeData [count]; - count = 0; - - if (IsNotSerialized) - attrsData [count++] = new CustomAttributeData ((typeof (NonSerializedAttribute)).GetConstructor (Type.EmptyTypes)); - if (DeclaringType.IsExplicitLayout) { - var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument (typeof (int), GetFieldOffset ()) }; - attrsData [count++] = new CustomAttributeData ( - (typeof (FieldOffsetAttribute)).GetConstructor (new[] { typeof (int) }), - ctorArgs, - Array.Empty<CustomAttributeNamedArgument> ()); - } - - if (marshalAs != null) { - var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument (typeof (UnmanagedType), marshalAs.Value) }; - attrsData [count++] = new CustomAttributeData ( - (typeof (MarshalAsAttribute)).GetConstructor (new[] { typeof (UnmanagedType) }), - ctorArgs, - Array.Empty<CustomAttributeNamedArgument> ());//FIXME Get named params - } - - return attrsData; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs deleted file mode 100644 index c385d9ec5e8..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Reflection -{ - public abstract partial class MemberInfo - { - internal bool HasSameMetadataDefinitionAsCore<TOther>(MemberInfo other) where TOther : MemberInfo - { - if (other == null) - throw new ArgumentNullException(nameof(other)); - - // Ensure that "other" is a runtime-implemented MemberInfo. Do this check before calling any methods on it! - if (!(other is TOther)) - return false; - - if (MetadataToken != other.MetadataToken) - return false; - - if (!(Module.Equals(other.Module))) - return false; - - return true; - } - } -} - diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs b/netcore/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs deleted file mode 100644 index 3d759589a7d..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Reflection.Metadata -{ - public static class AssemblyExtensions - { - [CLSCompliant(false)] - public static unsafe bool TryGetRawMetadata (this Assembly assembly, out byte* blob, out int length) => throw new NotImplementedException (); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/MethodBase.Mono.cs b/netcore/System.Private.CoreLib/src/System/Reflection/MethodBase.Mono.cs deleted file mode 100644 index b219e9f919f..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/MethodBase.Mono.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; -using System.Reflection.Emit; - -namespace System.Reflection -{ - partial class MethodBase - { - public static MethodBase GetMethodFromHandle (RuntimeMethodHandle handle) - { - if (handle.IsNullHandle ()) - throw new ArgumentException (SR.Argument_InvalidHandle); - - MethodBase m = RuntimeMethodInfo.GetMethodFromHandleInternalType (handle.Value, IntPtr.Zero); - if (m == null) - throw new ArgumentException (SR.Argument_InvalidHandle); - - Type declaringType = m.DeclaringType; - if (declaringType != null && declaringType.IsGenericType) - throw new ArgumentException (String.Format (SR.Argument_MethodDeclaringTypeGeneric, - m, declaringType.GetGenericTypeDefinition ())); - - return m; - } - - public static MethodBase GetMethodFromHandle (RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) - { - if (handle.IsNullHandle ()) - throw new ArgumentException (SR.Argument_InvalidHandle); - MethodBase m = RuntimeMethodInfo.GetMethodFromHandleInternalType (handle.Value, declaringType.Value); - if (m == null) - throw new ArgumentException (SR.Argument_InvalidHandle); - return m; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static MethodBase GetCurrentMethod (); - - internal virtual ParameterInfo[] GetParametersNoCopy () - { - return GetParametersInternal (); - } - - internal virtual ParameterInfo[] GetParametersInternal () - { - throw new NotImplementedException (); - } - - internal virtual int GetParametersCount () - { - throw new NotImplementedException (); - } - - internal virtual Type GetParameterType (int pos) - { - throw new NotImplementedException (); - } - - internal virtual Type[] GetParameterTypes () - { - ParameterInfo[] paramInfo = GetParametersNoCopy (); - - Type[] parameterTypes = new Type [paramInfo.Length]; - for (int i = 0; i < paramInfo.Length; i++) - parameterTypes [i] = paramInfo [i].ParameterType; - - return parameterTypes; - } - - internal virtual int get_next_table_index (object obj, int table, int count) - { - throw new NotImplementedException (); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs b/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs deleted file mode 100644 index 9a264739e36..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs +++ /dev/null @@ -1,451 +0,0 @@ -// -// Copyright (C) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#nullable disable -using System.IO; -using System.Globalization; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Loader; -using System.Threading; - -namespace System.Reflection -{ - [StructLayout (LayoutKind.Sequential)] - sealed class RuntimeAssembly : Assembly - { - private sealed class ResolveEventHolder - { - public event ModuleResolveEventHandler ModuleResolve; - } - - private sealed class UnmanagedMemoryStreamForModule : UnmanagedMemoryStream - { - Module module; - - public unsafe UnmanagedMemoryStreamForModule (byte* pointer, long length, Module module) - : base (pointer, length) - { - this.module = module; - } - } - - // - // KEEP IN SYNC WITH mcs/class/corlib/System.Reflection/RuntimeAssembly.cs - // - #region VM dependency - IntPtr _mono_assembly; - object _evidence; // Unused, kept for layout compatibility - #endregion - - ResolveEventHolder resolve_event_holder; - - public override extern MethodInfo? EntryPoint { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - get; - } - - public override bool ReflectionOnly => false; - - public override string? CodeBase { - get { - return get_code_base (this, false); - } - } - - public override string? FullName { - get { - return get_fullname (this); - } - } - - // - // We can't store the event directly in this class, since the - // compiler would silently insert the fields before _mono_assembly - // - public override event ModuleResolveEventHandler ModuleResolve { - add { - resolve_event_holder.ModuleResolve += value; - } - remove { - resolve_event_holder.ModuleResolve -= value; - } - } - - public override Module? ManifestModule => GetManifestModuleInternal (); - - public override bool GlobalAssemblyCache => false; - - public override long HostContext => 0; - - public override string ImageRuntimeVersion => InternalImageRuntimeVersion (this); - - public override string Location { - get { - return get_location (); - } - } - - // TODO: - public override bool IsCollectible => false; - - internal static AssemblyName CreateAssemblyName (string assemblyString, out RuntimeAssembly assemblyFromResolveEvent) - { - if (assemblyString == null) - throw new ArgumentNullException (nameof (assemblyString)); - - if ((assemblyString.Length == 0) || - (assemblyString[0] == '\0')) - throw new ArgumentException (SR.Format_StringZeroLength); - - assemblyFromResolveEvent = null; - try { - return new AssemblyName (assemblyString); - } catch (Exception) { - assemblyFromResolveEvent = (RuntimeAssembly)AssemblyLoadContext.DoAssemblyResolve (assemblyString); - if (assemblyFromResolveEvent == null) - throw new FileLoadException (assemblyString); - return null; - } - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public override extern String[] GetManifestResourceNames (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public override extern Type[] GetExportedTypes (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern Type[] GetTopLevelForwardedTypes (); - - public override Type[] GetForwardedTypes () { - Type[] topLevelTypes = GetTopLevelForwardedTypes (); - List<Type> forwardedTypes = new List<Type> (topLevelTypes); - List<Exception> exceptions = new List<Exception> (); - - foreach (Type t in topLevelTypes) - AddPublicNestedTypes (t, forwardedTypes, exceptions); - - if (exceptions.Count > 0) { - forwardedTypes.AddRange (new Type [exceptions.Count]); // add one null Type for each exception - exceptions.InsertRange (0, new Exception [forwardedTypes.Count]); // align the Exceptions with the null Types - throw new ReflectionTypeLoadException (forwardedTypes.ToArray (), exceptions.ToArray ()); - } - - return forwardedTypes.ToArray (); - } - - private static void AddPublicNestedTypes (Type type, List<Type> types, List<Exception> exceptions) - { - Type[] nestedTypes; - - try { - nestedTypes = type.GetNestedTypes (BindingFlags.Public); - } - catch (FileLoadException e) { exceptions.Add (e); return; } - catch (FileNotFoundException e) { exceptions.Add (e); return; } - catch (TypeLoadException e) { exceptions.Add (e); return; } - catch (IOException e) { exceptions.Add (e); return; } - catch (UnauthorizedAccessException e) { exceptions.Add (e); return; } - - foreach (Type nestedType in nestedTypes) { - types.Add(nestedType); - AddPublicNestedTypes(nestedType, types, exceptions); - } - } - - public override ManifestResourceInfo GetManifestResourceInfo (string resourceName) - { - if (resourceName == null) - throw new ArgumentNullException ("resourceName"); - if (resourceName.Length == 0) - throw new ArgumentException ("String cannot have zero length."); - ManifestResourceInfo result = new ManifestResourceInfo (null, null, 0); - bool found = GetManifestResourceInfoInternal (resourceName, result); - if (found) - return result; - else - return null; - } - - public override Stream GetManifestResourceStream (string name) - { - if (name == null) - throw new ArgumentNullException (nameof (name)); - - if (name.Length == 0) - throw new ArgumentException ("String cannot have zero length.", - "name"); - - unsafe { - byte* data = (byte*) GetManifestResourceInternal (name, out int length, out Module resourceModule); - if (data == null) - return null; - - // It cannot use SafeBuffer mode because not all methods are supported in this - // mode (e.g. UnmanagedMemoryStream.get_PositionPointer) - return new UnmanagedMemoryStreamForModule (data, length, resourceModule); - } - } - - public override Stream GetManifestResourceStream (Type type, string name) - { - if (type == null && name == null) - throw new ArgumentNullException (nameof (type)); - - string nameSpace = type?.Namespace; - - string resourceName = nameSpace != null && name != null ? - nameSpace + Type.Delimiter + name : - nameSpace + name; - - return GetManifestResourceStream (resourceName); - } - - public override AssemblyName GetName (bool copiedName) - { - return AssemblyName.Create (_mono_assembly, CodeBase); - } - - public override Type GetType (string name, bool throwOnError, bool ignoreCase) - { - if (name == null) - throw new ArgumentNullException (nameof (name)); - - if (name.Length == 0) - throw new ArgumentException ("Name cannot be empty"); - - return InternalGetType (null, name, throwOnError, ignoreCase); - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - return CustomAttribute.IsDefined (this, attributeType, inherit); - } - - public override IList<CustomAttributeData> GetCustomAttributesData () - { - return CustomAttributeData.GetCustomAttributes (this); - } - - public override object[] GetCustomAttributes (bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, inherit); - } - - public override object[] GetCustomAttributes (Type attributeType, bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - } - - public override Module GetModule (string name) - { - if (name == null) - throw new ArgumentNullException ("name"); - if (name.Length == 0) - throw new ArgumentException ("Name can't be empty"); - - Module[] modules = GetModules (true); - foreach (Module module in modules) { - if (module.ScopeName == name) - return module; - } - - return null; - } - - public override Module[] GetModules (bool getResourceModules) - { - Module[] modules = GetModulesInternal (); - - if (!getResourceModules) { - var result = new List<Module> (modules.Length); - foreach (Module m in modules) - if (!m.IsResource ()) - result.Add (m); - return result.ToArray (); - } - else - return modules; - } - - public override Module[] GetLoadedModules (bool getResourceModules) - { - return GetModules (getResourceModules); - } - - public override AssemblyName[] GetReferencedAssemblies () - { - using (var nativeNames = new Mono.SafeGPtrArrayHandle (InternalGetReferencedAssemblies (this))) { - var numAssemblies = nativeNames.Length; - try { - AssemblyName [] result = new AssemblyName[numAssemblies]; - const bool addVersion = true; - const bool addPublicKey = false; - const bool defaultToken = true; - for (int i = 0; i < numAssemblies; i++) { - AssemblyName name = new AssemblyName (); - unsafe { - Mono.MonoAssemblyName *nativeName = (Mono.MonoAssemblyName*) nativeNames[i]; - name.FillName (nativeName, null, addVersion, addPublicKey, defaultToken); - result[i] = name; - } - } - return result; - } finally { - for (int i = 0; i < numAssemblies; i++) { - unsafe { - Mono.MonoAssemblyName* nativeName = (Mono.MonoAssemblyName*) nativeNames[i]; - Mono.RuntimeMarshal.FreeAssemblyName (ref *nativeName, true); - } - } - } - } - } - - public override Assembly GetSatelliteAssembly (CultureInfo culture) - { - return GetSatelliteAssembly (culture, null); - } - - public override Assembly GetSatelliteAssembly (CultureInfo culture, Version version) - { - if (culture == null) - throw new ArgumentNullException (nameof (culture)); - - return InternalGetSatelliteAssembly (culture, version, true); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - internal Assembly InternalGetSatelliteAssembly (CultureInfo culture, Version version, bool throwOnFileNotFound) - { - var aname = GetName (); - - var an = new AssemblyName (); - if (version == null) - an.Version = aname.Version; - else - an.Version = version; - - an.CultureInfo = culture; - an.Name = aname.Name + ".resources"; - - Assembly res = null; - try { - StackCrawlMark unused = default; - res = Assembly.Load (an, ref unused, null); - } catch { - } - - if (res == this) - res = null; - if (res == null && throwOnFileNotFound) - throw new FileNotFoundException (String.Format (culture, SR.IO_FileNotFound_FileName, an.Name)); - return res; - } - - public override FileStream GetFile (string name) - { - if (name == null) - throw new ArgumentNullException (nameof (name), SR.ArgumentNull_FileName); - if (name.Length == 0) - throw new ArgumentException (SR.Argument_EmptyFileName); - - string location = Location; - if (location != null && Path.GetFileName (location) == name) - return new FileStream (location, FileMode.Open, FileAccess.Read); - string filename = (string)GetFilesInternal (name, true); - if (filename != null) - return new FileStream (filename, FileMode.Open, FileAccess.Read); - else - return null; - } - - public override FileStream[] GetFiles (bool getResourceModules) - { - string[] names = (string[]) GetFilesInternal (null, getResourceModules); - if (names == null) - return Array.Empty<FileStream> (); - - string location = Location; - - FileStream[] res; - if (location != String.Empty) { - res = new FileStream [names.Length + 1]; - res [0] = new FileStream (location, FileMode.Open, FileAccess.Read); - for (int i = 0; i < names.Length; ++i) - res [i + 1] = new FileStream (names [i], FileMode.Open, FileAccess.Read); - } else { - res = new FileStream [names.Length]; - for (int i = 0; i < names.Length; ++i) - res [i] = new FileStream (names [i], FileMode.Open, FileAccess.Read); - } - return res; - } - - internal static RuntimeAssembly InternalLoadAssemblyName (AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext) - { - // TODO: Use assemblyLoadContext - return (RuntimeAssembly) InternalLoad (assemblyRef.FullName, ref stackMark, IntPtr.Zero); - } - - // FIXME: Merge some of these - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern string get_location (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static string get_code_base (Assembly a, bool escaped); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static string get_fullname (Assembly a); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static string InternalImageRuntimeVersion (Assembly a); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern bool GetManifestResourceInfoInternal (string name, ManifestResourceInfo info); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern IntPtr /* byte* */ GetManifestResourceInternal (string name, out int size, out Module module); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern Module GetManifestModuleInternal (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern Module[] GetModulesInternal (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern IntPtr InternalGetReferencedAssemblies (Assembly module); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - private extern object GetFilesInternal (String name, bool getResourceModules); - - internal string? GetSimpleName () - { - // TODO: Make this cheaper and faster - return GetName ().Name; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs b/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs deleted file mode 100644 index d2e178f702b..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs +++ /dev/null @@ -1,220 +0,0 @@ -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004, 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#nullable disable -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection -{ - internal struct MonoEventInfo - { - public Type declaring_type; - public Type reflected_type; - public String name; - public MethodInfo add_method; - public MethodInfo remove_method; - public MethodInfo raise_method; - public EventAttributes attrs; - public MethodInfo[] other_methods; - } - - [StructLayout (LayoutKind.Sequential)] - internal sealed class RuntimeEventInfo : EventInfo - { -#pragma warning disable 169 - IntPtr klass; - IntPtr handle; -#pragma warning restore 169 - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern void get_event_info (RuntimeEventInfo ev, out MonoEventInfo info); - - internal static MonoEventInfo GetEventInfo (RuntimeEventInfo ev) - { - MonoEventInfo mei; - get_event_info (ev, out mei); - return mei; - } - - public override Module Module { - get { - return GetRuntimeModule (); - } - } - - internal BindingFlags BindingFlags { - get { - return GetBindingFlags (); - } - } - - internal RuntimeType GetDeclaringTypeInternal () - { - return (RuntimeType) DeclaringType; - } - - RuntimeType ReflectedTypeInternal { - get { - return (RuntimeType) ReflectedType; - } - } - - internal RuntimeModule GetRuntimeModule () - { - return GetDeclaringTypeInternal ().GetRuntimeModule (); - } - - internal BindingFlags GetBindingFlags () - { - MonoEventInfo info = GetEventInfo (this); - - MethodInfo method = info.add_method; - if (method == null) - method = info.remove_method; - if (method == null) - method = info.raise_method; - - return RuntimeType.FilterPreCalculate (method != null && method.IsPublic, GetDeclaringTypeInternal () != ReflectedType , method != null && method.IsStatic); - } - - public override EventAttributes Attributes { - get { - return GetEventInfo (this).attrs; - } - } - - public override MethodInfo GetAddMethod (bool nonPublic) - { - MonoEventInfo info = GetEventInfo (this); - if (nonPublic || (info.add_method != null && info.add_method.IsPublic)) - return info.add_method; - return null; - } - - public override MethodInfo GetRaiseMethod (bool nonPublic) - { - MonoEventInfo info = GetEventInfo (this); - if (nonPublic || (info.raise_method != null && info.raise_method.IsPublic)) - return info.raise_method; - return null; - } - - public override MethodInfo GetRemoveMethod (bool nonPublic) - { - MonoEventInfo info = GetEventInfo (this); - if (nonPublic || (info.remove_method != null && info.remove_method.IsPublic)) - return info.remove_method; - return null; - } - - public override MethodInfo[] GetOtherMethods (bool nonPublic) - { - MonoEventInfo info = GetEventInfo (this); - if (nonPublic) - return info.other_methods; - int num_public = 0; - foreach (MethodInfo m in info.other_methods) { - if (m.IsPublic) - num_public++; - } - if (num_public == info.other_methods.Length) - return info.other_methods; - MethodInfo[] res = new MethodInfo [num_public]; - num_public = 0; - foreach (MethodInfo m in info.other_methods) { - if (m.IsPublic) - res [num_public++] = m; - } - return res; - } - - public override Type DeclaringType { - get { - return GetEventInfo (this).declaring_type; - } - } - - public override Type ReflectedType { - get { - return GetEventInfo (this).reflected_type; - } - } - - public override string Name { - get { - return GetEventInfo (this).name; - } - } - - public override string ToString () - { - return EventHandlerType + " " + Name; - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - return CustomAttribute.IsDefined (this, attributeType, inherit); - } - - public override object[] GetCustomAttributes( bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, inherit); - } - - public override object[] GetCustomAttributes( Type attributeType, bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - } - - public override IList<CustomAttributeData> GetCustomAttributesData () { - return CustomAttributeData.GetCustomAttributes (this); - } - - public override int MetadataToken { - get { - return get_metadata_token (this); - } - } - - public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeEventInfo> (other); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern int get_metadata_token (RuntimeEventInfo monoEvent); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern EventInfo internal_from_handle_type (IntPtr event_handle, IntPtr type_handle); - - internal static EventInfo GetEventFromHandle (Mono.RuntimeEventHandle handle, RuntimeTypeHandle reflectedType) - { - if (handle.Value == IntPtr.Zero) - throw new ArgumentException ("The handle is invalid."); - EventInfo ei = internal_from_handle_type (handle.Value, reflectedType.Value); - if (ei == null) - throw new ArgumentException ("The event handle and the type handle are incompatible."); - return ei; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs b/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs deleted file mode 100644 index 75f6ac2a4a1..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -namespace System.Reflection -{ - [StructLayout (LayoutKind.Sequential)] - internal sealed class RuntimeExceptionHandlingClause : ExceptionHandlingClause - { - #region Keep in sync with MonoReflectionExceptionHandlingClause in object-internals.h - internal Type catch_type; - internal int filter_offset; - internal ExceptionHandlingClauseOptions flags; - internal int try_offset; - internal int try_length; - internal int handler_offset; - internal int handler_length; - #endregion - - public override ExceptionHandlingClauseOptions Flags => flags; - public override int TryOffset => try_offset; - public override int TryLength => try_length; - public override int HandlerOffset => handler_offset; - public override int HandlerLength => handler_length; - public override int FilterOffset => filter_offset; - public override Type? CatchType => catch_type; - } - -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs b/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs deleted file mode 100644 index 56a82717a6d..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs +++ /dev/null @@ -1,289 +0,0 @@ -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#nullable disable -using System.Collections.Generic; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Diagnostics; - -namespace System.Reflection -{ - abstract class RtFieldInfo : FieldInfo - { - internal abstract object UnsafeGetValue (object obj); - internal abstract void UnsafeSetValue (Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture); - internal abstract void CheckConsistency(Object target); - } - - [StructLayout (LayoutKind.Sequential)] - class RuntimeFieldInfo : RtFieldInfo - { -#pragma warning disable 649 - internal IntPtr klass; - internal RuntimeFieldHandle fhandle; - string name; - Type type; - FieldAttributes attrs; -#pragma warning restore 649 - - internal BindingFlags BindingFlags { - get { - return 0; - } - } - - public override Module Module { - get { - return GetRuntimeModule (); - } - } - - internal RuntimeType GetDeclaringTypeInternal () - { - return (RuntimeType) DeclaringType; - } - - RuntimeType ReflectedTypeInternal { - get { - return (RuntimeType) ReflectedType; - } - } - - internal RuntimeModule GetRuntimeModule () - { - return GetDeclaringTypeInternal ().GetRuntimeModule (); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal override extern object UnsafeGetValue (object obj); - - internal override void CheckConsistency(Object target) - { - // only test instance fields - if ((Attributes & FieldAttributes.Static) != FieldAttributes.Static) - { - if (!DeclaringType.IsInstanceOfType(target)) - { - if (target == null) - { - throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatFldReqTarg")); - } - else - { - throw new ArgumentException( - String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_FieldDeclTarget"), - Name, DeclaringType, target.GetType())); - } - } - } - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - internal override void UnsafeSetValue (Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) - { - bool domainInitialized = false; - RuntimeFieldHandle.SetValue (this, obj, value, null, Attributes, null, ref domainInitialized); - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override void SetValueDirect(TypedReference obj, Object value) - { - if (obj.IsNull) - throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); - - unsafe - { - // Passing TypedReference by reference is easier to make correct in native code - RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType); - } - } - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override Object GetValueDirect(TypedReference obj) - { - if (obj.IsNull) - throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); - - unsafe - { - // Passing TypedReference by reference is easier to make correct in native code - return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType); - } - } - - public override FieldAttributes Attributes { - get { - return attrs; - } - } - public override RuntimeFieldHandle FieldHandle { - get { - return fhandle; - } - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern Type ResolveType (); - - public override Type FieldType { - get { - if (type == null) - type = ResolveType (); - return type; - } - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern Type GetParentType (bool declaring); - - public override Type ReflectedType { - get { - return GetParentType (false); - } - } - public override Type DeclaringType { - get { - Type parentType = GetParentType (true); - return parentType.Name != "<Module>" ? parentType : null; - } - } - public override string Name { - get { - return name; - } - } - - public override bool IsDefined (Type attributeType, bool inherit) { - return CustomAttribute.IsDefined (this, attributeType, inherit); - } - - public override object[] GetCustomAttributes( bool inherit) { - return CustomAttribute.GetCustomAttributes (this, inherit); - } - public override object[] GetCustomAttributes( Type attributeType, bool inherit) { - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal override extern int GetFieldOffset (); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern object GetValueInternal (object obj); - - public override object GetValue (object obj) - { - if (!IsStatic) { - if (obj == null) - throw new TargetException ("Non-static field requires a target"); - if (!DeclaringType.IsAssignableFrom (obj.GetType ())) - throw new ArgumentException (string.Format ( - "Field {0} defined on type {1} is not a field on the target object which is of type {2}.", - Name, DeclaringType, obj.GetType ()), - "obj"); - } - - if (!IsLiteral) - CheckGeneric (); - return GetValueInternal (obj); - } - - public override string ToString () { - return String.Format ("{0} {1}", FieldType, name); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void SetValueInternal (FieldInfo fi, object obj, object value); - - public override void SetValue (object obj, object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture) - { - if (!IsStatic) { - if (obj == null) - throw new TargetException ("Non-static field requires a target"); - if (!DeclaringType.IsAssignableFrom (obj.GetType ())) - throw new ArgumentException (string.Format ( - "Field {0} defined on type {1} is not a field on the target object which is of type {2}.", - Name, DeclaringType, obj.GetType ()), - "obj"); - } - if (IsLiteral) - throw new FieldAccessException ("Cannot set a constant field"); - if (binder == null) - binder = Type.DefaultBinder; - CheckGeneric (); - if (val != null) { - RuntimeType fieldType = (RuntimeType) FieldType; - val = fieldType.CheckValue (val, binder, culture, invokeAttr); - } - SetValueInternal (this, obj, val); - } - - internal RuntimeFieldInfo Clone (string newName) - { - RuntimeFieldInfo field = new RuntimeFieldInfo (); - field.name = newName; - field.type = type; - field.attrs = attrs; - field.klass = klass; - field.fhandle = fhandle; - return field; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public override extern object GetRawConstantValue (); - - public override IList<CustomAttributeData> GetCustomAttributesData () { - return CustomAttributeData.GetCustomAttributes (this); - } - - void CheckGeneric () { - Type declaringType = DeclaringType; - if (declaringType != null && declaringType.ContainsGenericParameters) - throw new InvalidOperationException ("Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true."); - } - - public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeFieldInfo> (other); - - public override int MetadataToken { - get { - return get_metadata_token (this); - } - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern int get_metadata_token (RuntimeFieldInfo monoField); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern Type[] GetTypeModifiers (bool optional); - - public override Type[] GetOptionalCustomModifiers () => GetCustomModifiers (true); - - public override Type[] GetRequiredCustomModifiers () => GetCustomModifiers (false); - - private Type[] GetCustomModifiers (bool optional) => GetTypeModifiers (optional) ?? Type.EmptyTypes; - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeLocalVariableInfo.cs b/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeLocalVariableInfo.cs deleted file mode 100644 index 6681ef929ee..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeLocalVariableInfo.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection { - [StructLayout (LayoutKind.Sequential)] - internal sealed class RuntimeLocalVariableInfo : LocalVariableInfo { - #region Keep in sync with MonoReflectionLocalVariableInfo in object-internals.h - internal Type type; - internal bool is_pinned; - internal ushort position; - #endregion - - public override bool IsPinned => is_pinned; - - public override int LocalIndex => position; - - public override Type LocalType => type; - } - -} - diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeMethodBody.cs b/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeMethodBody.cs deleted file mode 100644 index 7ded1e13589..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeMethodBody.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Reflection { - - internal sealed class RuntimeMethodBody : MethodBody - { - ExceptionHandlingClause[] clauses; - LocalVariableInfo[] locals; - byte[] il; - bool init_locals; - int sig_token; - int max_stack; - - // Called by the runtime - internal RuntimeMethodBody (ExceptionHandlingClause[] clauses, LocalVariableInfo[] locals, - byte[] il, bool init_locals, int sig_token, int max_stack) - { - this.clauses = clauses; - this.locals = locals; - this.il = il; - this.init_locals = init_locals; - this.sig_token = sig_token; - this.max_stack = max_stack; - } - - public override int LocalSignatureMetadataToken => sig_token; - public override IList<LocalVariableInfo> LocalVariables => Array.AsReadOnly (locals); - public override int MaxStackSize => max_stack; - public override bool InitLocals => init_locals; - public override byte[] GetILAsByteArray() => il; - public override IList<ExceptionHandlingClause> ExceptionHandlingClauses => Array.AsReadOnly (clauses); - } - -} - - diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs b/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs deleted file mode 100644 index 763b4a52d11..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs +++ /dev/null @@ -1,913 +0,0 @@ -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) -// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#nullable disable -using System.Collections.Generic; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Reflection.Emit; -using System.Text; -using System.Diagnostics; -using InteropServicesCallingConvention = System.Runtime.InteropServices.CallingConvention; - -namespace System.Reflection -{ - - [Flags] - internal enum PInvokeAttributes - { - NoMangle = 0x0001, - - CharSetMask = 0x0006, - CharSetNotSpec = 0x0000, - CharSetAnsi = 0x0002, - CharSetUnicode = 0x0004, - CharSetAuto = 0x0006, - - BestFitUseAssem = 0x0000, - BestFitEnabled = 0x0010, - BestFitDisabled = 0x0020, - BestFitMask = 0x0030, - - ThrowOnUnmappableCharUseAssem = 0x0000, - ThrowOnUnmappableCharEnabled = 0x1000, - ThrowOnUnmappableCharDisabled = 0x2000, - ThrowOnUnmappableCharMask = 0x3000, - - SupportsLastError = 0x0040, - - CallConvMask = 0x0700, - CallConvWinapi = 0x0100, - CallConvCdecl = 0x0200, - CallConvStdcall = 0x0300, - CallConvThiscall = 0x0400, - CallConvFastcall = 0x0500, - - MaxValue = 0xFFFF, - } - - internal struct MonoMethodInfo - { -#pragma warning disable 649 - private Type parent; - private Type ret; - internal MethodAttributes attrs; - internal MethodImplAttributes iattrs; - private CallingConventions callconv; -#pragma warning restore 649 - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern void get_method_info (IntPtr handle, out MonoMethodInfo info); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern int get_method_attributes (IntPtr handle); - - internal static MonoMethodInfo GetMethodInfo (IntPtr handle) - { - MonoMethodInfo info; - MonoMethodInfo.get_method_info (handle, out info); - return info; - } - - internal static Type GetDeclaringType (IntPtr handle) - { - return GetMethodInfo (handle).parent; - } - - internal static Type GetReturnType (IntPtr handle) - { - return GetMethodInfo (handle).ret; - } - - internal static MethodAttributes GetAttributes (IntPtr handle) - { - return (MethodAttributes)get_method_attributes (handle); - } - - internal static CallingConventions GetCallingConvention (IntPtr handle) - { - return GetMethodInfo (handle).callconv; - } - - internal static MethodImplAttributes GetMethodImplementationFlags (IntPtr handle) - { - return GetMethodInfo (handle).iattrs; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern ParameterInfo[] get_parameter_info (IntPtr handle, MemberInfo member); - - static internal ParameterInfo[] GetParametersInfo (IntPtr handle, MemberInfo member) - { - return get_parameter_info (handle, member); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern MarshalAsAttribute get_retval_marshal (IntPtr handle); - - static internal ParameterInfo GetReturnParameterInfo (RuntimeMethodInfo method) - { - return RuntimeParameterInfo.New (GetReturnType (method.mhandle), method, get_retval_marshal (method.mhandle)); - } - } - - [StructLayout (LayoutKind.Sequential)] - class RuntimeMethodInfo : MethodInfo - { -#pragma warning disable 649 - internal IntPtr mhandle; - string name; - Type reftype; -#pragma warning restore 649 - - internal BindingFlags BindingFlags { - get { - return 0; - } - } - - public override Module Module { - get { - return GetRuntimeModule (); - } - } - - RuntimeType ReflectedTypeInternal { - get { - return (RuntimeType) ReflectedType; - } - } - - string FormatNameAndSig () - { - // Serialization uses ToString to resolve MethodInfo overloads. - StringBuilder sbName = new StringBuilder(Name); - - if (IsGenericMethod) - sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, TypeNameFormatFlags.FormatBasic)); - - sbName.Append("("); - RuntimeParameterInfo.FormatParameters (sbName, GetParametersNoCopy (), CallingConvention); - sbName.Append(")"); - - return sbName.ToString(); - } - - public override Delegate CreateDelegate (Type delegateType) - { - return Delegate.CreateDelegate (delegateType, this); - } - - public override Delegate CreateDelegate (Type delegateType, object target) - { - return Delegate.CreateDelegate (delegateType, target, this); - } - - public override String ToString() - { - return ReturnType.FormatTypeName() + " " + FormatNameAndSig(); - } - - internal RuntimeModule GetRuntimeModule () - { - return ((RuntimeType)DeclaringType).GetRuntimeModule(); - } - - internal static MethodBase GetMethodFromHandleNoGenericCheck (RuntimeMethodHandle handle) - { - return GetMethodFromHandleInternalType_native (handle.Value, IntPtr.Zero, false); - } - - internal static MethodBase GetMethodFromHandleNoGenericCheck (RuntimeMethodHandle handle, RuntimeTypeHandle reflectedType) - { - return GetMethodFromHandleInternalType_native (handle.Value, reflectedType.Value, false); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - [PreserveDependency(".ctor(System.Reflection.ExceptionHandlingClause[],System.Reflection.LocalVariableInfo[],System.Byte[],System.Boolean,System.Int32,System.Int32)", "System.Reflection.RuntimeMethodBody")] - internal extern static MethodBody GetMethodBodyInternal (IntPtr handle); - - internal static MethodBody GetMethodBody (IntPtr handle) - { - return GetMethodBodyInternal (handle); - } - - internal static MethodBase GetMethodFromHandleInternalType (IntPtr method_handle, IntPtr type_handle) { - return GetMethodFromHandleInternalType_native (method_handle, type_handle, true); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static MethodBase GetMethodFromHandleInternalType_native (IntPtr method_handle, IntPtr type_handle, bool genericCheck); - - internal RuntimeMethodInfo () { - } - - internal RuntimeMethodInfo (RuntimeMethodHandle mhandle) { - this.mhandle = mhandle.Value; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern string get_name (MethodBase method); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern RuntimeMethodInfo get_base_method (RuntimeMethodInfo method, bool definition); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern int get_metadata_token (RuntimeMethodInfo method); - - public override MethodInfo GetBaseDefinition () - { - return get_base_method (this, true); - } - - // TODO: Remove, needed only for MonoCustomAttribute - internal MethodInfo GetBaseMethod () - { - return get_base_method (this, false); - } - - public override ParameterInfo ReturnParameter { - get { - return MonoMethodInfo.GetReturnParameterInfo (this); - } - } - - public override Type ReturnType { - get { - return MonoMethodInfo.GetReturnType (mhandle); - } - } - public override ICustomAttributeProvider ReturnTypeCustomAttributes { - get { - return MonoMethodInfo.GetReturnParameterInfo (this); - } - } - - public override int MetadataToken { - get { - return get_metadata_token (this); - } - } - - public override MethodImplAttributes GetMethodImplementationFlags () - { - return MonoMethodInfo.GetMethodImplementationFlags (mhandle); - } - - public override ParameterInfo[] GetParameters () - { - var src = MonoMethodInfo.GetParametersInfo (mhandle, this); - if (src.Length == 0) - return src; - - // Have to clone because GetParametersInfo icall returns cached value - var dest = new ParameterInfo [src.Length]; - Array.FastCopy (src, 0, dest, 0, src.Length); - return dest; - } - - internal override ParameterInfo[] GetParametersInternal () - { - return MonoMethodInfo.GetParametersInfo (mhandle, this); - } - - internal override int GetParametersCount () - { - return MonoMethodInfo.GetParametersInfo (mhandle, this).Length; - } - - /* - * InternalInvoke() receives the parameters correctly converted by the - * binder to match the types of the method signature. - * The exc argument is used to capture exceptions thrown by the icall. - * Exceptions thrown by the called method propagate normally. - */ - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc); - - [DebuggerHidden] - [DebuggerStepThrough] - public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - if (!IsStatic) { - if (!DeclaringType.IsInstanceOfType (obj)) { - if (obj == null) - throw new TargetException ("Non-static method requires a target."); - else - throw new TargetException ("Object does not match target type."); - } - } - - if (binder == null) - binder = Type.DefaultBinder; - - /*Avoid allocating an array every time*/ - ParameterInfo[] pinfo = GetParametersInternal (); - ConvertValues (binder, parameters, pinfo, culture, invokeAttr); - - if (ContainsGenericParameters) - throw new InvalidOperationException ("Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."); - - Exception exc; - object o = null; - - if ((invokeAttr & BindingFlags.DoNotWrapExceptions) == 0) { - try { - o = InternalInvoke (obj, parameters, out exc); - } catch (Mono.NullByRefReturnException) { - throw new NullReferenceException (); - } catch (OverflowException) { - throw; - } catch (Exception e) { - throw new TargetInvocationException (e); - } - } - else - { - try { - o = InternalInvoke (obj, parameters, out exc); - } catch (Mono.NullByRefReturnException) { - throw new NullReferenceException (); - } - } - - if (exc != null) - throw exc; - return o; - } - - internal static void ConvertValues (Binder binder, object[] args, ParameterInfo[] pinfo, CultureInfo culture, BindingFlags invokeAttr) - { - if (args == null) { - if (pinfo.Length == 0) - return; - - throw new TargetParameterCountException (); - } - - if (pinfo.Length != args.Length) - throw new TargetParameterCountException (); - - for (int i = 0; i < args.Length; ++i) { - var arg = args [i]; - var pi = pinfo [i]; - if (arg == Type.Missing) { - if (pi.DefaultValue == System.DBNull.Value) - throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),"parameters"); - - args [i] = pi.DefaultValue; - continue; - } - - var rt = (RuntimeType) pi.ParameterType; - args [i] = rt.CheckValue (arg, binder, culture, invokeAttr); - } - } - - public override RuntimeMethodHandle MethodHandle { - get { - return new RuntimeMethodHandle (mhandle); - } - } - - public override MethodAttributes Attributes { - get { - return MonoMethodInfo.GetAttributes (mhandle); - } - } - - public override CallingConventions CallingConvention { - get { - return MonoMethodInfo.GetCallingConvention (mhandle); - } - } - - public override Type ReflectedType { - get { - return reftype; - } - } - public override Type DeclaringType { - get { - return MonoMethodInfo.GetDeclaringType (mhandle); - } - } - public override string Name { - get { - if (name != null) - return name; - return get_name (this); - } - } - - public override bool IsDefined (Type attributeType, bool inherit) { - return CustomAttribute.IsDefined (this, attributeType, inherit); - } - - public override object[] GetCustomAttributes( bool inherit) { - return CustomAttribute.GetCustomAttributes (this, inherit); - } - public override object[] GetCustomAttributes( Type attributeType, bool inherit) { - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern void GetPInvoke (out PInvokeAttributes flags, out string entryPoint, out string dllName); - - internal object[] GetPseudoCustomAttributes () - { - int count = 0; - - /* MS.NET doesn't report MethodImplAttribute */ - - MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle); - if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0) - count ++; - if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) - count ++; - - if (count == 0) - return null; - object[] attrs = new object [count]; - count = 0; - - if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0) - attrs [count ++] = new PreserveSigAttribute (); - if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) { - attrs [count ++] = GetDllImportAttribute (); - } - - return attrs; - } - - Attribute GetDllImportAttribute () - { - string entryPoint, dllName = null; - int token = MetadataToken; - PInvokeAttributes flags = 0; - - GetPInvoke (out flags, out entryPoint, out dllName); - - CharSet charSet = CharSet.None; - - switch (flags & PInvokeAttributes.CharSetMask) { - case PInvokeAttributes.CharSetNotSpec: charSet = CharSet.None; break; - case PInvokeAttributes.CharSetAnsi: charSet = CharSet.Ansi; break; - case PInvokeAttributes.CharSetUnicode: charSet = CharSet.Unicode; break; - case PInvokeAttributes.CharSetAuto: charSet = CharSet.Auto; break; - - // Invalid: default to CharSet.None - default: break; - } - - CallingConvention callingConvention = InteropServicesCallingConvention.Cdecl; - - switch (flags & PInvokeAttributes.CallConvMask) { - case PInvokeAttributes.CallConvWinapi: callingConvention = InteropServicesCallingConvention.Winapi; break; - case PInvokeAttributes.CallConvCdecl: callingConvention = InteropServicesCallingConvention.Cdecl; break; - case PInvokeAttributes.CallConvStdcall: callingConvention = InteropServicesCallingConvention.StdCall; break; - case PInvokeAttributes.CallConvThiscall: callingConvention = InteropServicesCallingConvention.ThisCall; break; - case PInvokeAttributes.CallConvFastcall: callingConvention = InteropServicesCallingConvention.FastCall; break; - - // Invalid: default to CallingConvention.Cdecl - default: break; - } - - bool exactSpelling = (flags & PInvokeAttributes.NoMangle) != 0; - bool setLastError = (flags & PInvokeAttributes.SupportsLastError) != 0; - bool bestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled; - bool throwOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled; - bool preserveSig = (GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0; - - return new DllImportAttribute (dllName) { EntryPoint = entryPoint, CharSet = charSet, SetLastError = setLastError, - ExactSpelling = exactSpelling, PreserveSig = preserveSig, BestFitMapping = bestFitMapping, - ThrowOnUnmappableChar = throwOnUnmappableChar, CallingConvention = callingConvention }; - } - - internal CustomAttributeData[] GetPseudoCustomAttributesData () - { - int count = 0; - - /* MS.NET doesn't report MethodImplAttribute */ - - MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle); - if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0) - count++; - if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) - count++; - - if (count == 0) - return null; - CustomAttributeData[] attrsData = new CustomAttributeData [count]; - count = 0; - - if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0) - attrsData [count++] = new CustomAttributeData ((typeof (PreserveSigAttribute)).GetConstructor (Type.EmptyTypes)); - if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) - attrsData [count++] = GetDllImportAttributeData (); - - return attrsData; - } - - private CustomAttributeData GetDllImportAttributeData () - { - if ((Attributes & MethodAttributes.PinvokeImpl) == 0) - return null; - - string entryPoint, dllName = null; - PInvokeAttributes flags = 0; - - GetPInvoke (out flags, out entryPoint, out dllName); - - CharSet charSet; - - switch (flags & PInvokeAttributes.CharSetMask) { - case PInvokeAttributes.CharSetNotSpec: - charSet = CharSet.None; - break; - case PInvokeAttributes.CharSetAnsi: - charSet = CharSet.Ansi; - break; - case PInvokeAttributes.CharSetUnicode: - charSet = CharSet.Unicode; - break; - case PInvokeAttributes.CharSetAuto: - charSet = CharSet.Auto; - break; - // Invalid: default to CharSet.None - default: - charSet = CharSet.None; - break; - } - - InteropServicesCallingConvention callingConvention; - - switch (flags & PInvokeAttributes.CallConvMask) { - case PInvokeAttributes.CallConvWinapi: - callingConvention = InteropServicesCallingConvention.Winapi; - break; - case PInvokeAttributes.CallConvCdecl: - callingConvention = InteropServicesCallingConvention.Cdecl; - break; - case PInvokeAttributes.CallConvStdcall: - callingConvention = InteropServicesCallingConvention.StdCall; - break; - case PInvokeAttributes.CallConvThiscall: - callingConvention = InteropServicesCallingConvention.ThisCall; - break; - case PInvokeAttributes.CallConvFastcall: - callingConvention = InteropServicesCallingConvention.FastCall; - break; - // Invalid: default to CallingConvention.Cdecl - default: - callingConvention = InteropServicesCallingConvention.Cdecl; - break; - } - - bool exactSpelling = (flags & PInvokeAttributes.NoMangle) != 0; - bool setLastError = (flags & PInvokeAttributes.SupportsLastError) != 0; - bool bestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled; - bool throwOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled; - bool preserveSig = (GetMethodImplementationFlags () & MethodImplAttributes.PreserveSig) != 0; - - var ctorArgs = new CustomAttributeTypedArgument [] { - new CustomAttributeTypedArgument (typeof (string), dllName), - }; - - var attrType = typeof (DllImportAttribute); - - var namedArgs = new CustomAttributeNamedArgument [] { - new CustomAttributeNamedArgument (attrType.GetField ("EntryPoint"), entryPoint), - new CustomAttributeNamedArgument (attrType.GetField ("CharSet"), charSet), - new CustomAttributeNamedArgument (attrType.GetField ("ExactSpelling"), exactSpelling), - new CustomAttributeNamedArgument (attrType.GetField ("SetLastError"), setLastError), - new CustomAttributeNamedArgument (attrType.GetField ("PreserveSig"), preserveSig), - new CustomAttributeNamedArgument (attrType.GetField ("CallingConvention"), callingConvention), - new CustomAttributeNamedArgument (attrType.GetField ("BestFitMapping"), bestFitMapping), - new CustomAttributeNamedArgument (attrType.GetField ("ThrowOnUnmappableChar"), throwOnUnmappableChar) - }; - - return new CustomAttributeData ( - attrType.GetConstructor (new[] { typeof (string) }), - ctorArgs, - namedArgs); - } - - public override MethodInfo MakeGenericMethod (Type [] methodInstantiation) - { - if (methodInstantiation == null) - throw new ArgumentNullException ("methodInstantiation"); - - if (!IsGenericMethodDefinition) - throw new InvalidOperationException ("not a generic method definition"); - - /*FIXME add GetGenericArgumentsLength() internal vcall to speed this up*/ - if (GetGenericArguments ().Length != methodInstantiation.Length) - throw new ArgumentException ("Incorrect length"); - - bool hasUserType = false; - foreach (Type type in methodInstantiation) { - if (type == null) - throw new ArgumentNullException (); - if (!(type is RuntimeType)) - hasUserType = true; - } - - if (hasUserType) { - if (RuntimeFeature.IsDynamicCodeSupported) - return new MethodOnTypeBuilderInst (this, methodInstantiation); - - throw new NotSupportedException ("User types are not supported under full aot"); - } - - MethodInfo ret = MakeGenericMethod_impl (methodInstantiation); - if (ret == null) - throw new ArgumentException (String.Format ("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments ().Length, methodInstantiation.Length)); - return ret; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern MethodInfo MakeGenericMethod_impl (Type [] types); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public override extern Type [] GetGenericArguments (); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern MethodInfo GetGenericMethodDefinition_impl (); - - public override MethodInfo GetGenericMethodDefinition () - { - MethodInfo res = GetGenericMethodDefinition_impl (); - if (res == null) - throw new InvalidOperationException (); - - return res; - } - - public override extern bool IsGenericMethodDefinition { - [MethodImplAttribute(MethodImplOptions.InternalCall)] - get; - } - - public override extern bool IsGenericMethod { - [MethodImplAttribute(MethodImplOptions.InternalCall)] - get; - } - - public override bool ContainsGenericParameters { - get { - if (IsGenericMethod) { - foreach (Type arg in GetGenericArguments ()) - if (arg.ContainsGenericParameters) - return true; - } - return DeclaringType.ContainsGenericParameters; - } - } - - public override MethodBody GetMethodBody () { - return GetMethodBody (mhandle); - } - - public override IList<CustomAttributeData> GetCustomAttributesData () { - return CustomAttributeData.GetCustomAttributes (this); - } - - public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeMethodInfo> (other); - } - - [StructLayout (LayoutKind.Sequential)] - class RuntimeConstructorInfo : ConstructorInfo - { -#pragma warning disable 649 - internal IntPtr mhandle; - string name; - Type reftype; -#pragma warning restore 649 - - public override Module Module { - get { - return GetRuntimeModule (); - } - } - - internal RuntimeModule GetRuntimeModule () - { - return RuntimeTypeHandle.GetModule((RuntimeType)DeclaringType); - } - - internal BindingFlags BindingFlags { - get { - return 0; - } - } - - RuntimeType ReflectedTypeInternal { - get { - return (RuntimeType) ReflectedType; - } - } - - public override MethodImplAttributes GetMethodImplementationFlags () - { - return MonoMethodInfo.GetMethodImplementationFlags (mhandle); - } - - public override ParameterInfo[] GetParameters () - { - return MonoMethodInfo.GetParametersInfo (mhandle, this); - } - - internal override ParameterInfo[] GetParametersInternal () - { - return MonoMethodInfo.GetParametersInfo (mhandle, this); - } - - internal override int GetParametersCount () - { - var pi = MonoMethodInfo.GetParametersInfo (mhandle, this); - return pi == null ? 0 : pi.Length; - } - - /* - * InternalInvoke() receives the parameters correctly converted by the binder - * to match the types of the method signature. - */ - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc); - - [DebuggerHidden] - [DebuggerStepThrough] - public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) - { - if (obj == null) { - if (!IsStatic) - throw new TargetException ("Instance constructor requires a target"); - } else if (!DeclaringType.IsInstanceOfType (obj)) { - throw new TargetException ("Constructor does not match target type"); - } - - return DoInvoke (obj, invokeAttr, binder, parameters, culture); - } - - object DoInvoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) - { - if (binder == null) - binder = Type.DefaultBinder; - - ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this); - - RuntimeMethodInfo.ConvertValues (binder, parameters, pinfo, culture, invokeAttr); - - if (obj == null && DeclaringType.ContainsGenericParameters) - throw new MemberAccessException ("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true."); - - if ((invokeAttr & BindingFlags.CreateInstance) != 0 && DeclaringType.IsAbstract) { - throw new MemberAccessException (String.Format ("Cannot create an instance of {0} because it is an abstract class", DeclaringType)); - } - - return InternalInvoke (obj, parameters, (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0); - } - - public object InternalInvoke (object obj, object[] parameters, bool wrapExceptions) - { - Exception exc; - object o = null; - - if (wrapExceptions) { - try { - o = InternalInvoke (obj, parameters, out exc); - } catch (MethodAccessException) { - throw; - } catch (OverflowException) { - throw; - } catch (Exception e) { - throw new TargetInvocationException (e); - } - } else { - o = InternalInvoke (obj, parameters, out exc); - } - - if (exc != null) - throw exc; - - return obj == null ? o : null; - } - - [DebuggerHidden] - [DebuggerStepThrough] - public override Object Invoke (BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) - { - return DoInvoke (null, invokeAttr, binder, parameters, culture); - } - - public override RuntimeMethodHandle MethodHandle { - get { - return new RuntimeMethodHandle (mhandle); - } - } - - public override MethodAttributes Attributes { - get { - return MonoMethodInfo.GetAttributes (mhandle); - } - } - - public override CallingConventions CallingConvention { - get { - return MonoMethodInfo.GetCallingConvention (mhandle); - } - } - - public override bool ContainsGenericParameters { - get { - return DeclaringType.ContainsGenericParameters; - } - } - - public override Type ReflectedType { - get { - return reftype; - } - } - public override Type DeclaringType { - get { - return MonoMethodInfo.GetDeclaringType (mhandle); - } - } - public override string Name { - get { - if (name != null) - return name; - return RuntimeMethodInfo.get_name (this); - } - } - - public override bool IsDefined (Type attributeType, bool inherit) { - return CustomAttribute.IsDefined (this, attributeType, inherit); - } - - public override object[] GetCustomAttributes( bool inherit) { - return CustomAttribute.GetCustomAttributes (this, inherit); - } - - public override object[] GetCustomAttributes( Type attributeType, bool inherit) { - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - } - - public override MethodBody GetMethodBody () { - return RuntimeMethodInfo.GetMethodBody (mhandle); - } - - public override string ToString () - { - StringBuilder sbName = new StringBuilder(Name); - sbName.Append ("Void "); - - sbName.Append("("); - RuntimeParameterInfo.FormatParameters (sbName, GetParametersNoCopy (), CallingConvention); - sbName.Append(")"); - - return sbName.ToString(); - } - - public override IList<CustomAttributeData> GetCustomAttributesData () - { - return CustomAttributeData.GetCustomAttributes (this); - } - - public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeConstructorInfo> (other); - - public override int MetadataToken { - get { - return get_metadata_token (this); - } - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern int get_metadata_token (RuntimeConstructorInfo method); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs b/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs deleted file mode 100644 index 60e6708eaf7..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs +++ /dev/null @@ -1,391 +0,0 @@ -// -// Copyright (C) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#nullable disable -using System.Collections; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - -namespace System.Reflection { - - [StructLayout (LayoutKind.Sequential)] - class RuntimeModule : Module - { -#pragma warning disable 649 - #region Sync with object-internals.h - #region Sync with ModuleBuilder - internal IntPtr _impl; /* a pointer to a MonoImage */ - internal Assembly assembly; - internal string fqname; - internal string name; - internal string scopename; - internal bool is_resource; - internal int token; - #endregion - #endregion -#pragma warning restore 649 - - public - override - Assembly Assembly { - get { return assembly; } - } - - public - override - // Note: we do not ask for PathDiscovery because no path is returned here. - // However MS Fx requires it (see FDBK23572 for details). - string Name { - get { return name; } - } - - public - override - string ScopeName { - get { return scopename; } - } - - public - override - int MDStreamVersion { - get { - if (_impl == IntPtr.Zero) - throw new NotSupportedException (); - return GetMDStreamVersion (_impl); - } - } - - public - override - Guid ModuleVersionId { - get { - return GetModuleVersionId (); - } - } - - public override - string FullyQualifiedName { - get { - return fqname; - } - } - - public - override - bool IsResource() - { - return is_resource; - } - - public override - Type[] FindTypes(TypeFilter filter, object filterCriteria) - { - var filtered = new List<Type> (); - Type[] types = GetTypes (); - foreach (Type t in types) - if (filter (t, filterCriteria)) - filtered.Add (t); - return filtered.ToArray (); - } - - public override - object[] GetCustomAttributes(bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, inherit); - } - - public override - object[] GetCustomAttributes(Type attributeType, bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - } - - public override - FieldInfo GetField (string name, BindingFlags bindingAttr) - { - if (name == null) - throw new ArgumentNullException("name"); - - if (IsResource ()) - return null; - - Type globalType = GetGlobalType (_impl); - return (globalType != null) ? globalType.GetField (name, bindingAttr) : null; - } - - public override - FieldInfo[] GetFields (BindingFlags bindingFlags) - { - if (IsResource ()) - return new FieldInfo [0]; - - Type globalType = GetGlobalType (_impl); - return (globalType != null) ? globalType.GetFields (bindingFlags) : new FieldInfo [0]; - } - - public override - int MetadataToken { - get { - return get_MetadataToken (this); - } - } - - protected - override - MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) - { - if (IsResource ()) - return null; - - Type globalType = GetGlobalType (_impl); - if (globalType == null) - return null; - if (types == null) - return globalType.GetMethod (name); - return globalType.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers); - } - - public - override - MethodInfo[] GetMethods (BindingFlags bindingFlags) { - if (IsResource ()) - return new MethodInfo [0]; - - Type globalType = GetGlobalType (_impl); - return (globalType != null) ? globalType.GetMethods (bindingFlags) : new MethodInfo [0]; - } - - public override - void GetPEKind (out PortableExecutableKinds peKind, out ImageFileMachine machine) { - RuntimeModule.GetPEKind (_impl, out peKind, out machine); - } - - public override - Type GetType(string className, bool throwOnError, bool ignoreCase) - { - if (className == null) - throw new ArgumentNullException ("className"); - if (className == String.Empty) - throw new ArgumentException ("Type name can't be empty"); - return assembly.InternalGetType (this, className, throwOnError, ignoreCase); - } - - public override - bool IsDefined (Type attributeType, bool inherit) - { - return CustomAttribute.IsDefined (this, attributeType, inherit); - } - - public - override - FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - return ResolveField (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments); - } - - internal static FieldInfo ResolveField (Module module, IntPtr monoModule, int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - ResolveTokenError error; - - IntPtr handle = ResolveFieldToken (monoModule, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error); - if (handle == IntPtr.Zero) - throw resolve_token_exception (module.Name, metadataToken, error, "Field"); - else - return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle)); - } - - public - override - MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - return ResolveMember (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments); - } - - internal static MemberInfo ResolveMember (Module module, IntPtr monoModule, int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - ResolveTokenError error; - - MemberInfo m = ResolveMemberToken (monoModule, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error); - if (m == null) - throw resolve_token_exception (module.Name, metadataToken, error, "MemberInfo"); - else - return m; - } - - public - override - MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - return ResolveMethod (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments); - } - - internal static MethodBase ResolveMethod (Module module, IntPtr monoModule, int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - ResolveTokenError error; - - IntPtr handle = ResolveMethodToken (monoModule, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error); - if (handle == IntPtr.Zero) - throw resolve_token_exception (module.Name, metadataToken, error, "MethodBase"); - else - return RuntimeMethodInfo.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle)); - } - - public - override - string ResolveString (int metadataToken) { - return ResolveString (this, _impl, metadataToken); - } - - internal static string ResolveString (Module module, IntPtr monoModule, int metadataToken) { - ResolveTokenError error; - - string s = ResolveStringToken (monoModule, metadataToken, out error); - if (s == null) - throw resolve_token_exception (module.Name, metadataToken, error, "string"); - else - return s; - } - - public - override - Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - return ResolveType (this, _impl, metadataToken, genericTypeArguments, genericMethodArguments); - } - - internal static Type ResolveType (Module module, IntPtr monoModule, int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) { - ResolveTokenError error; - - IntPtr handle = ResolveTypeToken (monoModule, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error); - if (handle == IntPtr.Zero) - throw resolve_token_exception (module.Name, metadataToken, error, "Type"); - else - return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle)); - } - - public - override - byte[] ResolveSignature (int metadataToken) { - return ResolveSignature (this, _impl, metadataToken); - } - - internal static byte[] ResolveSignature (Module module, IntPtr monoModule, int metadataToken) { - ResolveTokenError error; - - byte[] res = ResolveSignature (monoModule, metadataToken, out error); - if (res == null) - throw resolve_token_exception (module.Name, metadataToken, error, "signature"); - else - return res; - } - - public override - Type[] GetTypes() - { - return InternalGetTypes (_impl); - } - - public override IList<CustomAttributeData> GetCustomAttributesData () { - return CustomAttributeData.GetCustomAttributes (this); - } - - internal RuntimeAssembly GetRuntimeAssembly () - { - return (RuntimeAssembly)assembly; - } - - internal IntPtr MonoModule { - get { - return _impl; - } - } - - internal Guid GetModuleVersionId () - { - var guid = new byte [16]; - GetGuidInternal (_impl, guid); - return new Guid (guid); - } - - internal static Exception resolve_token_exception (string name, int metadataToken, ResolveTokenError error, string tokenType) { - if (error == ResolveTokenError.OutOfRange) - return new ArgumentOutOfRangeException ("metadataToken", String.Format ("Token 0x{0:x} is not valid in the scope of module {1}", metadataToken, name)); - else - return new ArgumentException (String.Format ("Token 0x{0:x} is not a valid {1} token in the scope of module {2}", metadataToken, tokenType, name), "metadataToken"); - } - - internal static IntPtr[] ptrs_from_types (Type[] types) { - if (types == null) - return null; - else { - IntPtr[] res = new IntPtr [types.Length]; - for (int i = 0; i < types.Length; ++i) { - if (types [i] == null) - throw new ArgumentException (); - res [i] = types [i].TypeHandle.Value; - } - return res; - } - } - - // This calls ves_icall_reflection_get_token, so needs a Module argument - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern int get_MetadataToken (Module module); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern int GetMDStreamVersion (IntPtr module); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern Type[] InternalGetTypes (IntPtr module); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern IntPtr GetHINSTANCE (IntPtr module); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - private static extern void GetGuidInternal (IntPtr module, byte[] guid); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern Type GetGlobalType (IntPtr module); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern IntPtr ResolveTypeToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern IntPtr ResolveMethodToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern IntPtr ResolveFieldToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern string ResolveStringToken (IntPtr module, int token, out ResolveTokenError error); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern MemberInfo ResolveMemberToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern byte[] ResolveSignature (IntPtr module, int metadataToken, out ResolveTokenError error); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern void GetPEKind (IntPtr module, out PortableExecutableKinds peKind, out ImageFileMachine machine); - } - - internal enum ResolveTokenError { - OutOfRange, - BadTable, - Other - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs b/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs deleted file mode 100644 index 2d6f842a786..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs +++ /dev/null @@ -1,294 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#nullable disable -using System.Reflection.Emit; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections.Generic; -using System.Text; - -namespace System.Reflection -{ - class RuntimeParameterInfo : ParameterInfo - { - internal MarshalAsAttribute marshalAs; - - // Called by the runtime - internal RuntimeParameterInfo (string name, Type type, int position, int attrs, object defaultValue, MemberInfo member, MarshalAsAttribute marshalAs) { - NameImpl = name; - ClassImpl = type; - PositionImpl = position; - AttrsImpl = (ParameterAttributes)attrs; - DefaultValueImpl = defaultValue; - MemberImpl = member; - this.marshalAs = marshalAs; - } - - internal static void FormatParameters (StringBuilder sb, ParameterInfo[] p, CallingConventions callingConvention) - { - for (int i = 0; i < p.Length; ++i) { - if (i > 0) - sb.Append (", "); - - Type t = p[i].ParameterType; - - string typeName = t.FormatTypeName (); - - // Legacy: Why use "ByRef" for by ref parameters? What language is this? - // VB uses "ByRef" but it should precede (not follow) the parameter name. - // Why don't we just use "&"? - if (t.IsByRef) { - sb.Append (typeName.TrimEnd (new char[] { '&' })); - sb.Append (" ByRef"); - } else { - sb.Append (typeName); - } - } - - if ((callingConvention & CallingConventions.VarArgs) != 0) { - if (p.Length > 0) - sb.Append (", "); - sb.Append ("..."); - } - } - - internal RuntimeParameterInfo (ParameterBuilder pb, Type type, MemberInfo member, int position) { - this.ClassImpl = type; - this.MemberImpl = member; - if (pb != null) { - this.NameImpl = pb.Name; - this.PositionImpl = pb.Position - 1; // ParameterInfo.Position is zero-based - this.AttrsImpl = (ParameterAttributes) pb.Attributes; - } else { - this.NameImpl = null; - this.PositionImpl = position - 1; - this.AttrsImpl = ParameterAttributes.None; - } - } - - internal static ParameterInfo New (ParameterBuilder pb, Type type, MemberInfo member, int position) - { - return new RuntimeParameterInfo (pb, type, member, position); - } - - /*FIXME this constructor looks very broken in the position parameter*/ - internal RuntimeParameterInfo (ParameterInfo pinfo, Type type, MemberInfo member, int position) { - this.ClassImpl = type; - this.MemberImpl = member; - if (pinfo != null) { - this.NameImpl = pinfo.Name; - this.PositionImpl = pinfo.Position - 1; // ParameterInfo.Position is zero-based - this.AttrsImpl = (ParameterAttributes) pinfo.Attributes; - } else { - this.NameImpl = null; - this.PositionImpl = position - 1; - this.AttrsImpl = ParameterAttributes.None; - } - } - - internal RuntimeParameterInfo (ParameterInfo pinfo, MemberInfo member) { - this.ClassImpl = pinfo.ParameterType; - this.MemberImpl = member; - this.NameImpl = pinfo.Name; - this.PositionImpl = pinfo.Position; - this.AttrsImpl = pinfo.Attributes; - this.DefaultValueImpl = GetDefaultValueImpl (pinfo); - } - - /* to build a ParameterInfo for the return type of a method */ - internal RuntimeParameterInfo (Type type, MemberInfo member, MarshalAsAttribute marshalAs) { - this.ClassImpl = type; - this.MemberImpl = member; - this.NameImpl = null; - this.PositionImpl = -1; // since parameter positions are zero-based, return type pos is -1 - this.AttrsImpl = ParameterAttributes.Retval; - this.marshalAs = marshalAs; - } - - public override - object DefaultValue { - get { - if (ClassImpl == typeof (Decimal) || ClassImpl == typeof (Decimal?)) { - /* default values for decimals are encoded using a custom attribute */ - DecimalConstantAttribute[] attrs = (DecimalConstantAttribute[])GetCustomAttributes (typeof (DecimalConstantAttribute), false); - if (attrs.Length > 0) - return attrs [0].Value; - } else if (ClassImpl == typeof (DateTime) || ClassImpl == typeof (DateTime?)) { - /* default values for DateTime are encoded using a custom attribute */ - DateTimeConstantAttribute[] attrs = (DateTimeConstantAttribute[])GetCustomAttributes (typeof (DateTimeConstantAttribute), false); - if (attrs.Length > 0) - return attrs [0].Value; - } - return DefaultValueImpl; - } - } - - public override - object RawDefaultValue { - get { - if (DefaultValue != null && DefaultValue.GetType ().IsEnum) - return ((Enum)DefaultValue).GetValue (); - /*FIXME right now DefaultValue doesn't throw for reflection-only assemblies. Change this once the former is fixed.*/ - return DefaultValue; - } - } - - public - override - int MetadataToken { - get { - if (MemberImpl is PropertyInfo) { - PropertyInfo prop = (PropertyInfo)MemberImpl; - MethodInfo mi = prop.GetGetMethod (true); - if (mi == null) - mi = prop.GetSetMethod (true); - - return mi.GetParametersInternal () [PositionImpl].MetadataToken; - } else if (MemberImpl is MethodBase) { - return GetMetadataToken (); - } - throw new ArgumentException ("Can't produce MetadataToken for member of type " + MemberImpl.GetType ()); - } - } - - - public - override - object[] GetCustomAttributes (bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, inherit); - } - - public - override - object[] GetCustomAttributes (Type attributeType, bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, attributeType, inherit); - } - - internal object GetDefaultValueImpl (ParameterInfo pinfo) - { - FieldInfo field = typeof (ParameterInfo).GetField ("DefaultValueImpl", BindingFlags.Instance | BindingFlags.NonPublic); - return field.GetValue (pinfo); - } - - public - override - bool IsDefined( Type attributeType, bool inherit) { - return CustomAttribute.IsDefined (this, attributeType, inherit); - } - - public override IList<CustomAttributeData> GetCustomAttributesData () { - return CustomAttributeData.GetCustomAttributes (this); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern int GetMetadataToken (); - - public override Type[] GetOptionalCustomModifiers () => GetCustomModifiers (true); - - internal object[] GetPseudoCustomAttributes () - { - int count = 0; - - if (IsIn) - count ++; - if (IsOut) - count ++; - if (IsOptional) - count ++; - if (marshalAs != null) - count ++; - - if (count == 0) - return null; - object[] attrs = new object [count]; - count = 0; - - if (IsIn) - attrs [count ++] = new InAttribute (); - if (IsOut) - attrs [count ++] = new OutAttribute (); - if (IsOptional) - attrs [count ++] = new OptionalAttribute (); - - if (marshalAs != null) { - attrs [count ++] = (MarshalAsAttribute)marshalAs.CloneInternal (); - } - - return attrs; - } - - internal CustomAttributeData[] GetPseudoCustomAttributesData () - { - int count = 0; - - if (IsIn) - count++; - if (IsOut) - count++; - if (IsOptional) - count++; - if (marshalAs != null) - count++; - - if (count == 0) - return null; - CustomAttributeData[] attrsData = new CustomAttributeData [count]; - count = 0; - - if (IsIn) - attrsData [count++] = new CustomAttributeData ((typeof (InAttribute)).GetConstructor (Type.EmptyTypes)); - if (IsOut) - attrsData [count++] = new CustomAttributeData ((typeof (OutAttribute)).GetConstructor (Type.EmptyTypes)); - if (IsOptional) - attrsData [count++] = new CustomAttributeData ((typeof (OptionalAttribute)).GetConstructor (Type.EmptyTypes)); - if (marshalAs != null) { - var ctorArgs = new CustomAttributeTypedArgument[] { new CustomAttributeTypedArgument (typeof (UnmanagedType), marshalAs.Value) }; - attrsData [count++] = new CustomAttributeData ( - (typeof (MarshalAsAttribute)).GetConstructor (new[] { typeof (UnmanagedType) }), - ctorArgs, - Array.Empty<CustomAttributeNamedArgument> ());//FIXME Get named params - } - - return attrsData; - } - - public override Type[] GetRequiredCustomModifiers () => GetCustomModifiers (false); - - public override bool HasDefaultValue { - get { - object defaultValue = DefaultValue; - if (defaultValue == null) - return true; - - if (defaultValue.GetType () == typeof(DBNull) || defaultValue.GetType () == typeof(Missing)) - return false; - - return true; - } - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern Type[] GetTypeModifiers (Type type, MemberInfo member, int position, bool optional); - - internal static ParameterInfo New (ParameterInfo pinfo, Type type, MemberInfo member, int position) - { - return new RuntimeParameterInfo (pinfo, type, member, position); - } - - internal static ParameterInfo New (ParameterInfo pinfo, MemberInfo member) - { - return new RuntimeParameterInfo (pinfo, member); - } - - internal static ParameterInfo New (Type type, MemberInfo member, MarshalAsAttribute marshalAs) - { - return new RuntimeParameterInfo (type, member, marshalAs); - } - - private Type[] GetCustomModifiers (bool optional) => GetTypeModifiers (ParameterType, Member, Position, optional) ?? Type.EmptyTypes; - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs b/netcore/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs deleted file mode 100644 index d2c8abb949e..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs +++ /dev/null @@ -1,459 +0,0 @@ -// -// (C) 2001 Ximian, Inc. http://www.ximian.com -// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) -// Copyright 2013 Xamarin, Inc (http://www.xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#nullable disable -using System.Collections.Generic; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using Mono; - -namespace System.Reflection -{ - internal struct MonoPropertyInfo { - public Type parent; - public Type declaring_type; - public String name; - public MethodInfo get_method; - public MethodInfo set_method; - public PropertyAttributes attrs; - } - - [Flags] - internal enum PInfo { - Attributes = 1, - GetMethod = 1 << 1, - SetMethod = 1 << 2, - ReflectedType = 1 << 3, - DeclaringType = 1 << 4, - Name = 1 << 5 - - } - - internal delegate object GetterAdapter (object _this); - internal delegate R Getter<T,R> (T _this); - - [StructLayout (LayoutKind.Sequential)] - internal class RuntimePropertyInfo : PropertyInfo - { -#pragma warning disable 649 - internal IntPtr klass; - internal IntPtr prop; - MonoPropertyInfo info; - PInfo cached; - GetterAdapter cached_getter; -#pragma warning restore 649 - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern void get_property_info (RuntimePropertyInfo prop, ref MonoPropertyInfo info, - PInfo req_info); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern Type[] GetTypeModifiers (RuntimePropertyInfo prop, bool optional); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern object get_default_value (RuntimePropertyInfo prop); - - - internal BindingFlags BindingFlags { - get { - CachePropertyInfo (PInfo.GetMethod | PInfo.SetMethod); - bool isPublic = info.set_method?.IsPublic == true || info.get_method?.IsPublic == true; - bool isStatic = info.set_method?.IsStatic == true || info.get_method?.IsStatic == true; - bool isInherited = DeclaringType != ReflectedType; - return FilterPreCalculate (isPublic, isInherited, isStatic); - } - } - - // Copied from https://github.com/dotnet/coreclr/blob/7a24a538cd265993e5864179f51781398c28ecdf/src/System.Private.CoreLib/src/System/RtType.cs#L2022 - static BindingFlags FilterPreCalculate (bool isPublic, bool isInherited, bool isStatic) - { - BindingFlags bindingFlags = isPublic ? BindingFlags.Public : BindingFlags.NonPublic; - if (isInherited) { - // We arrange things so the DeclaredOnly flag means "include inherited members" - bindingFlags |= BindingFlags.DeclaredOnly; - if (isStatic) - bindingFlags |= BindingFlags.Static | BindingFlags.FlattenHierarchy; - else - bindingFlags |= BindingFlags.Instance; - } - else { - if (isStatic) - bindingFlags |= BindingFlags.Static; - else - bindingFlags |= BindingFlags.Instance; - } - return bindingFlags; - } - - public override Module Module { - get { - return GetRuntimeModule (); - } - } - - internal RuntimeType GetDeclaringTypeInternal () - { - return (RuntimeType) DeclaringType; - } - - RuntimeType ReflectedTypeInternal { - get { - return (RuntimeType) ReflectedType; - } - } - - internal RuntimeModule GetRuntimeModule () - { - return GetDeclaringTypeInternal ().GetRuntimeModule (); - } - - #region Object Overrides - public override String ToString() - { - return FormatNameAndSig(); - } - - private string FormatNameAndSig() - { - StringBuilder sbName = new StringBuilder(PropertyType.FormatTypeName()); - - sbName.Append(" "); - sbName.Append(Name); - - var pi = GetIndexParameters (); - if (pi.Length > 0) { - sbName.Append (" ["); - RuntimeParameterInfo.FormatParameters (sbName, pi, 0); - sbName.Append ("]"); - } - - return sbName.ToString(); - } - #endregion - - void CachePropertyInfo (PInfo flags) - { - if ((cached & flags) != flags) { - get_property_info (this, ref info, flags); - cached |= flags; - } - } - - public override PropertyAttributes Attributes { - get { - CachePropertyInfo (PInfo.Attributes); - return info.attrs; - } - } - - public override bool CanRead { - get { - CachePropertyInfo (PInfo.GetMethod); - return (info.get_method != null); - } - } - - public override bool CanWrite { - get { - CachePropertyInfo (PInfo.SetMethod); - return (info.set_method != null); - } - } - - public override Type PropertyType { - get { - CachePropertyInfo (PInfo.GetMethod | PInfo.SetMethod); - - if (info.get_method != null) { - return info.get_method.ReturnType; - } else { - ParameterInfo[] parameters = info.set_method.GetParametersInternal (); - if (parameters.Length == 0) - throw new ArgumentException (SR.SetterHasNoParams, "indexer"); - - return parameters [parameters.Length - 1].ParameterType; - } - } - } - - public override Type ReflectedType { - get { - CachePropertyInfo (PInfo.ReflectedType); - return info.parent; - } - } - - public override Type DeclaringType { - get { - CachePropertyInfo (PInfo.DeclaringType); - return info.declaring_type; - } - } - - public override string Name { - get { - CachePropertyInfo (PInfo.Name); - return info.name; - } - } - - public override MethodInfo[] GetAccessors (bool nonPublic) - { - int nget = 0; - int nset = 0; - - CachePropertyInfo (PInfo.GetMethod | PInfo.SetMethod); - - if (info.set_method != null && (nonPublic || info.set_method.IsPublic)) - nset = 1; - if (info.get_method != null && (nonPublic || info.get_method.IsPublic)) - nget = 1; - - MethodInfo[] res = new MethodInfo [nget + nset]; - int n = 0; - if (nset != 0) - res [n++] = info.set_method; - if (nget != 0) - res [n++] = info.get_method; - return res; - } - - public override MethodInfo GetGetMethod (bool nonPublic) - { - CachePropertyInfo (PInfo.GetMethod); - if (info.get_method != null && (nonPublic || info.get_method.IsPublic)) - return info.get_method; - else - return null; - } - - public override ParameterInfo[] GetIndexParameters () - { - CachePropertyInfo (PInfo.GetMethod | PInfo.SetMethod); - ParameterInfo[] src; - int length; - if (info.get_method != null) { - src = info.get_method.GetParametersInternal (); - length = src.Length; - } else if (info.set_method != null) { - src = info.set_method.GetParametersInternal (); - length = src.Length - 1; - } else - return Array.Empty<ParameterInfo> (); - - var dest = new ParameterInfo [length]; - for (int i = 0; i < length; ++i) { - dest [i] = RuntimeParameterInfo.New (src [i], this); - } - return dest; - } - - public override MethodInfo GetSetMethod (bool nonPublic) - { - CachePropertyInfo (PInfo.SetMethod); - if (info.set_method != null && (nonPublic || info.set_method.IsPublic)) - return info.set_method; - else - return null; - } - - - /*TODO verify for attribute based default values, just like ParameterInfo*/ - public override object GetConstantValue () - { - return get_default_value (this); - } - - public override object GetRawConstantValue() { - return get_default_value (this); - } - - // According to MSDN the inherit parameter is ignored here and - // the behavior always defaults to inherit = false - // - public override bool IsDefined (Type attributeType, bool inherit) - { - return CustomAttribute.IsDefined (this, attributeType, false); - } - - public override object[] GetCustomAttributes (bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, false); - } - - public override object[] GetCustomAttributes (Type attributeType, bool inherit) - { - return CustomAttribute.GetCustomAttributes (this, attributeType, false); - } - - - delegate object GetterAdapter (object _this); - delegate R Getter<T,R> (T _this); - delegate R StaticGetter<R> (); - -#pragma warning disable 169 - // Used via reflection - static object GetterAdapterFrame<T,R> (Getter<T,R> getter, object obj) - { - return getter ((T)obj); - } - - static object StaticGetterAdapterFrame<R> (StaticGetter<R> getter, object obj) - { - return getter (); - } -#pragma warning restore 169 - - /* - * The idea behing this optimization is to use a pair of delegates to simulate the same effect of doing a reflection call. - * The first delegate cast the this argument to the right type and the second does points to the target method. - */ - static GetterAdapter CreateGetterDelegate (MethodInfo method) - { - Type[] typeVector; - Type getterType; - object getterDelegate; - MethodInfo adapterFrame; - Type getterDelegateType; - string frameName; - - if (method.IsStatic) { - typeVector = new Type[] { method.ReturnType }; - getterDelegateType = typeof (StaticGetter<>); - frameName = "StaticGetterAdapterFrame"; - } else { - typeVector = new Type[] { method.DeclaringType, method.ReturnType }; - getterDelegateType = typeof (Getter<,>); - frameName = "GetterAdapterFrame"; - } - - getterType = getterDelegateType.MakeGenericType (typeVector); - getterDelegate = Delegate.CreateDelegate (getterType, method); - adapterFrame = typeof (RuntimePropertyInfo).GetMethod (frameName, BindingFlags.Static | BindingFlags.NonPublic); - adapterFrame = adapterFrame.MakeGenericMethod (typeVector); - return (GetterAdapter)Delegate.CreateDelegate (typeof (GetterAdapter), getterDelegate, adapterFrame, true); - } - - public override object GetValue (object obj, object[] index) - { - if ((index == null || index.Length == 0) && RuntimeFeature.IsDynamicCodeSupported) { - /*FIXME we should check if the number of arguments matches the expected one, otherwise the error message will be pretty criptic.*/ - if (cached_getter == null) { - MethodInfo method = GetGetMethod (true); - if (method == null) - throw new ArgumentException ($"Get Method not found for '{Name}'"); - if (!DeclaringType.IsValueType && !PropertyType.IsByRef && !method.ContainsGenericParameters) { //FIXME find a way to build an invoke delegate for value types. - cached_getter = CreateGetterDelegate (method); - // The try-catch preserves the .Invoke () behaviour - try { - return cached_getter (obj); - } catch (Exception ex) { - throw new TargetInvocationException (ex); - } - } - } else { - try { - return cached_getter (obj); - } catch (Exception ex) { - throw new TargetInvocationException (ex); - } - } - } - - return GetValue (obj, BindingFlags.Default, null, index, null); - } - - public override object GetValue (object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) - { - object ret = null; - - MethodInfo method = GetGetMethod (true); - if (method == null) - throw new ArgumentException ($"Get Method not found for '{Name}'"); - - if (index == null || index.Length == 0) - ret = method.Invoke (obj, invokeAttr, binder, null, culture); - else - ret = method.Invoke (obj, invokeAttr, binder, index, culture); - - return ret; - } - - public override void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) - { - MethodInfo method = GetSetMethod (true); - if (method == null) - throw new ArgumentException ("Set Method not found for '" + Name + "'"); - - object [] parms; - if (index == null || index.Length == 0) - parms = new object [] {value}; - else { - int ilen = index.Length; - parms = new object [ilen+ 1]; - index.CopyTo (parms, 0); - parms [ilen] = value; - } - - method.Invoke (obj, invokeAttr, binder, parms, culture); - } - - public override Type[] GetOptionalCustomModifiers () => GetCustomModifiers (true); - - public override Type[] GetRequiredCustomModifiers () => GetCustomModifiers (false); - - private Type[] GetCustomModifiers (bool optional) => GetTypeModifiers (this, optional) ?? Type.EmptyTypes; - - public override IList<CustomAttributeData> GetCustomAttributesData () { - return CustomAttributeData.GetCustomAttributes (this); - } - - public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimePropertyInfo> (other); - - public override int MetadataToken { - get { - return get_metadata_token (this); - } - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern int get_metadata_token (RuntimePropertyInfo monoProperty); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern PropertyInfo internal_from_handle_type (IntPtr event_handle, IntPtr type_handle); - - internal static PropertyInfo GetPropertyFromHandle (RuntimePropertyHandle handle, RuntimeTypeHandle reflectedType) - { - if (handle.Value == IntPtr.Zero) - throw new ArgumentException ("The handle is invalid."); - PropertyInfo pi = internal_from_handle_type (handle.Value, reflectedType.Value); - if (pi == null) - throw new ArgumentException ("The property handle and the type handle are incompatible."); - return pi; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.Mono.cs b/netcore/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.Mono.cs deleted file mode 100644 index c62ffdb3720..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.Mono.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Globalization; -using System.Reflection; - -namespace System.Resources -{ - partial class ManifestBasedResourceGroveler - { - static Assembly InternalGetSatelliteAssembly (Assembly mainAssembly, CultureInfo culture, Version version) - { - return ((RuntimeAssembly)mainAssembly).InternalGetSatelliteAssembly (culture, version, throwOnFileNotFound: false); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs b/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs deleted file mode 100644 index c70be1bb984..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - struct Ephemeron - { - public object key; - public object value; - } - - // - // Instead of dependent handles, mono uses arrays of Ephemeron objects. - // - struct DependentHandle - { - Ephemeron[] data; - - public DependentHandle (object primary, object secondary) - { - data = new Ephemeron [1]; - data [0].key = primary; - data [0].value = secondary; - GC.register_ephemeron_array (data); - } - - public bool IsAllocated => data != null; - - // Getting the secondary object is more expensive than getting the first so - // we provide a separate primary-only accessor for those times we only want the - // primary. - public object GetPrimary () - { - if (!IsAllocated) - throw new NotSupportedException (); - if (data [0].key == GC.EPHEMERON_TOMBSTONE) - return null; - return data [0].key; - } - - public object GetPrimaryAndSecondary (out object secondary) - { - if (!IsAllocated) - throw new NotSupportedException (); - if (data [0].key == GC.EPHEMERON_TOMBSTONE) { - secondary = null; - return null; - } - secondary = data [0].value; - return data [0].key; - } - - public void SetPrimary (object primary) - { - if (!IsAllocated) - throw new NotSupportedException (); - data [0].key = primary; - } - - public void SetSecondary (object secondary) - { - if (!IsAllocated) - throw new NotSupportedException (); - data [0].value = secondary; - } - - public void Free () - { - data = null; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/JitHelpers.cs b/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/JitHelpers.cs deleted file mode 100644 index 8c23159dd41..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/JitHelpers.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - static class JitHelpers - { - [Intrinsic] - public static bool EnumEquals<T> (T x, T y) where T : struct, Enum => throw new NotImplementedException (); - - [Intrinsic] - public static int EnumCompareTo<T> (T x, T y) where T : struct, Enum => throw new NotImplementedException (); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/PreserveDependencyAttribute.cs b/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/PreserveDependencyAttribute.cs deleted file mode 100644 index e68473a63ed..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/PreserveDependencyAttribute.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// PreserveDependencyAttribute.cs -// -// Authors: -// Marek Safar <marek.safar@gmail.com> -// -// Copyright (C) 2018 Microsoft Corporation -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -namespace System.Runtime.CompilerServices { - [AttributeUsage (AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Field, AllowMultiple = true)] - /*public*/ sealed class PreserveDependencyAttribute : Attribute { - public PreserveDependencyAttribute (string memberSignature) - { - } - - public PreserveDependencyAttribute (string memberSignature, string typeName) - { - } - - public PreserveDependencyAttribute (string memberSignature, string typeName, string assembly) - { - } - - public string Condition { get; set; } - } -}
\ No newline at end of file diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeFeature.Mono.cs b/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeFeature.Mono.cs deleted file mode 100644 index 00b5c981419..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeFeature.Mono.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - partial class RuntimeFeature - { - public static bool IsDynamicCodeSupported { - [Intrinsic] // the JIT/AOT compiler will change this flag to false for FullAOT scenarios, otherwise true - get => IsDynamicCodeSupported; - } - - public static bool IsDynamicCodeCompiled { - [Intrinsic] // the JIT/AOT compiler will change this flag to false for FullAOT scenarios, otherwise true - get => IsDynamicCodeCompiled; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs b/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs deleted file mode 100644 index 43efbaa9de6..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs +++ /dev/null @@ -1,141 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.CompilerServices -{ - partial class RuntimeHelpers - { - public static void InitializeArray (Array array, RuntimeFieldHandle fldHandle) - { - if (array == null || fldHandle.Value == IntPtr.Zero) - throw new ArgumentNullException (); - - InitializeArray (array, fldHandle.Value); - } - - public static int OffsetToStringData { - [Intrinsic] - get => OffsetToStringData; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern int InternalGetHashCode (object o); - - public static int GetHashCode (object o) - { - return InternalGetHashCode (o); - } - - public static new bool Equals (object? o1, object? o2) - { - if (o1 == o2) - return true; - - if (o1 == null || o2 == null) - return false; - - if (o1 is ValueType) - return ValueType.DefaultEquals (o1, o2); - - return false; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public static extern object GetObjectValue (object obj); - - public static void RunClassConstructor (RuntimeTypeHandle type) - { - if (type.Value == IntPtr.Zero) - throw new ArgumentException ("Handle is not initialized.", "type"); - - RunClassConstructor (type.Value); - } - - public static void EnsureSufficientExecutionStack () - { - if (SufficientExecutionStack ()) - return; - - throw new InsufficientExecutionStackException (); - } - - public static bool TryEnsureSufficientExecutionStack () - { - return SufficientExecutionStack (); - } - - public static void PrepareDelegate (Delegate d) - { - } - - public static void PrepareMethod (RuntimeMethodHandle method) - { - if (method.IsNullHandle ()) - throw new ArgumentException (SR.Argument_InvalidHandle); - unsafe { - PrepareMethod (method.Value, null, 0); - } - } - - public static void PrepareMethod (RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation) - { - if (method.IsNullHandle ()) - throw new ArgumentException (SR.Argument_InvalidHandle); - unsafe { - IntPtr[] instantiations = RuntimeTypeHandle.CopyRuntimeTypeHandles (instantiation, out int length); - fixed (IntPtr* pinst = instantiations) { - PrepareMethod (method.Value, pinst, length); - GC.KeepAlive (instantiation); - } - } - } - - public static void RunModuleConstructor (ModuleHandle module) - { - if (module == ModuleHandle.EmptyHandle) - throw new ArgumentException ("Handle is not initialized.", "module"); - - RunModuleConstructor (module.Value); - } - - [Intrinsic] - public static bool IsReferenceOrContainsReferences<T> () => IsReferenceOrContainsReferences<T> (); - - [Intrinsic] - internal static bool IsBitwiseEquatable<T> () => IsBitwiseEquatable<T> (); - - [Intrinsic] - internal static bool ObjectHasComponentSize (object obj) => ObjectHasComponentSize (obj); - - [Intrinsic] - internal static bool ObjectHasReferences (object obj) - { - // TODO: Missing intrinsic in interpreter - return RuntimeTypeHandle.HasReferences (obj.GetType () as RuntimeType); - } - - static object GetUninitializedObjectInternal (Type type) - { - return GetUninitializedObjectInternal (new RuntimeTypeHandle ((RuntimeType)type).Value); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern unsafe void PrepareMethod (IntPtr method, IntPtr* instantiations, int ninst); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern object GetUninitializedObjectInternal (IntPtr type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern void InitializeArray (Array array, IntPtr fldHandle); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern void RunClassConstructor (IntPtr type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern void RunModuleConstructor (IntPtr module); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern bool SufficientExecutionStack (); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/GCSettings.Mono.cs b/netcore/System.Private.CoreLib/src/System/Runtime/GCSettings.Mono.cs deleted file mode 100644 index c7374f93975..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/GCSettings.Mono.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime -{ - partial class GCSettings - { - public static bool IsServerGC => false; - - static GCLatencyMode GetGCLatencyMode() => GCLatencyMode.Batch; - - static SetLatencyModeStatus SetGCLatencyMode(GCLatencyMode newLatencyMode) - { - if (newLatencyMode != GCLatencyMode.Batch) - throw new PlatformNotSupportedException (); - - return SetLatencyModeStatus.Succeeded; - } - - static GCLargeObjectHeapCompactionMode GetLOHCompactionMode() => GCLargeObjectHeapCompactionMode.Default; - - static void SetLOHCompactionMode (GCLargeObjectHeapCompactionMode newLOHCompactionMode) - { - if (newLOHCompactionMode != GCLargeObjectHeapCompactionMode.Default) - throw new PlatformNotSupportedException (); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.Mono.cs b/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.Mono.cs deleted file mode 100644 index 9dc17ee4aaa..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.Mono.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.InteropServices -{ - partial class CriticalHandle - { - void ReleaseHandleFailed () - { - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.Mono.cs b/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.Mono.cs deleted file mode 100644 index 08038b4c648..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.Mono.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices -{ - partial struct GCHandle - { - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern IntPtr InternalAlloc (object value, GCHandleType type); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern void InternalFree (IntPtr handle); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern object InternalGet (IntPtr handle); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern void InternalSet (IntPtr handle, object value); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Mono.cs b/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Mono.cs deleted file mode 100644 index 40bf279960a..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Mono.cs +++ /dev/null @@ -1,448 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices -{ - partial class Marshal - { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static IntPtr AllocCoTaskMem (int cb); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static IntPtr AllocHGlobal (IntPtr cb); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static void FreeBSTR (IntPtr ptr); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static void FreeCoTaskMem (IntPtr ptr); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static void FreeHGlobal (IntPtr hglobal); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public static extern int GetLastWin32Error (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static void DestroyStructure (IntPtr ptr, Type structuretype); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static IntPtr OffsetOf (Type t, string fieldName); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static string PtrToStringBSTR (IntPtr ptr); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern unsafe static IntPtr BufferToBSTR (char* ptr, int slen); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static bool IsPinnableType (Type type); - - internal static bool IsPinnable (object obj) - { - if (obj == null || obj is string) - return true; - return IsPinnableType (obj.GetType ()); - //Type type = obj.GetType (); - //return !type.IsValueType || RuntimeTypeHandle.HasReferences (type as RuntimeType); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern void SetLastWin32Error (int error); - - static Exception GetExceptionForHRInternal (int errorCode, IntPtr errorInfo) - { - switch (errorCode) { - case HResults.S_OK: - case HResults.S_FALSE: - return null; - case HResults.COR_E_AMBIGUOUSMATCH: - return new System.Reflection.AmbiguousMatchException (); - case HResults.COR_E_APPLICATION: - return new System.ApplicationException (); - case HResults.COR_E_ARGUMENT: - return new System.ArgumentException (); - case HResults.COR_E_ARGUMENTOUTOFRANGE: - return new System.ArgumentOutOfRangeException (); - case HResults.COR_E_ARITHMETIC: - return new System.ArithmeticException (); - case HResults.COR_E_ARRAYTYPEMISMATCH: - return new System.ArrayTypeMismatchException (); - case HResults.COR_E_BADEXEFORMAT: - return new System.BadImageFormatException (); - case HResults.COR_E_BADIMAGEFORMAT: - return new System.BadImageFormatException (); - //case HResults.COR_E_CODECONTRACTFAILED: - //return new System.Diagnostics.Contracts.ContractException (); - //case HResults.COR_E_COMEMULATE: - case HResults.COR_E_CUSTOMATTRIBUTEFORMAT: - return new System.Reflection.CustomAttributeFormatException (); - case HResults.COR_E_DATAMISALIGNED: - return new System.DataMisalignedException (); - case HResults.COR_E_DIRECTORYNOTFOUND: - return new System.IO.DirectoryNotFoundException (); - case HResults.COR_E_DIVIDEBYZERO: - return new System.DivideByZeroException (); - case HResults.COR_E_DLLNOTFOUND: - return new System.DllNotFoundException (); - case HResults.COR_E_DUPLICATEWAITOBJECT: - return new System.DuplicateWaitObjectException (); - case HResults.COR_E_ENDOFSTREAM: - return new System.IO.EndOfStreamException (); - case HResults.COR_E_ENTRYPOINTNOTFOUND: - return new System.EntryPointNotFoundException (); - case HResults.COR_E_EXCEPTION: - return new System.Exception (); - case HResults.COR_E_EXECUTIONENGINE: - return new System.ExecutionEngineException (); - case HResults.COR_E_FIELDACCESS: - return new System.FieldAccessException (); - case HResults.COR_E_FILELOAD: - return new System.IO.FileLoadException (); - case HResults.COR_E_FILENOTFOUND: - return new System.IO.FileNotFoundException (); - case HResults.COR_E_FORMAT: - return new System.FormatException (); - case HResults.COR_E_INDEXOUTOFRANGE: - return new System.IndexOutOfRangeException (); - case HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: - return new System.InsufficientExecutionStackException (); - case HResults.COR_E_INVALIDCAST: - return new System.InvalidCastException (); - case HResults.COR_E_INVALIDFILTERCRITERIA: - return new System.Reflection.InvalidFilterCriteriaException (); - case HResults.COR_E_INVALIDOLEVARIANTTYPE: - return new System.Runtime.InteropServices.InvalidOleVariantTypeException (); - case HResults.COR_E_INVALIDOPERATION: - return new System.InvalidOperationException (); - case HResults.COR_E_INVALIDPROGRAM: - return new System.InvalidProgramException (); - case HResults.COR_E_IO: - return new System.IO.IOException (); - case HResults.COR_E_MARSHALDIRECTIVE: - return new System.Runtime.InteropServices.MarshalDirectiveException (); - case HResults.COR_E_MEMBERACCESS: - return new System.MemberAccessException (); - case HResults.COR_E_METHODACCESS: - return new System.MethodAccessException (); - case HResults.COR_E_MISSINGFIELD: - return new System.MissingFieldException (); - case HResults.COR_E_MISSINGMANIFESTRESOURCE: - return new System.Resources.MissingManifestResourceException (); - case HResults.COR_E_MISSINGMEMBER: - return new System.MissingMemberException (); - case HResults.COR_E_MISSINGMETHOD: - return new System.MissingMethodException (); - case HResults.COR_E_MULTICASTNOTSUPPORTED: - return new System.MulticastNotSupportedException (); - case HResults.COR_E_NOTFINITENUMBER: - return new System.NotFiniteNumberException (); - case HResults.COR_E_NOTSUPPORTED: - return new System.NotSupportedException (); - case HResults.COR_E_NULLREFERENCE: - return new System.NullReferenceException (); - case HResults.COR_E_OBJECTDISPOSED: - return new System.ObjectDisposedException (""); - case HResults.COR_E_OPERATIONCANCELED: - return new System.OperationCanceledException (); - case HResults.COR_E_OUTOFMEMORY: - return new System.OutOfMemoryException (); - case HResults.COR_E_OVERFLOW: - return new System.OverflowException (); - case HResults.COR_E_PATHTOOLONG: - return new System.IO.PathTooLongException (); - case HResults.COR_E_PLATFORMNOTSUPPORTED: - return new System.PlatformNotSupportedException (); - case HResults.COR_E_RANK: - return new System.RankException (); - case HResults.COR_E_REFLECTIONTYPELOAD: - return new System.MissingMethodException (); - case HResults.COR_E_RUNTIMEWRAPPED: - return new System.MissingMethodException (); - case HResults.COR_E_SECURITY: - return new System.Security.SecurityException (); - case HResults.COR_E_SERIALIZATION: - return new System.Runtime.Serialization.SerializationException (); - case HResults.COR_E_STACKOVERFLOW: - return new System.StackOverflowException (); - case HResults.COR_E_SYNCHRONIZATIONLOCK: - return new System.Threading.SynchronizationLockException (); - case HResults.COR_E_SYSTEM: - return new System.SystemException (); - case HResults.COR_E_TARGET: - return new System.Reflection.TargetException (); - case HResults.COR_E_TARGETINVOCATION: - return new System.MissingMethodException (); - case HResults.COR_E_TARGETPARAMCOUNT: - return new System.Reflection.TargetParameterCountException (); - case HResults.COR_E_THREADABORTED: - return new System.Threading.ThreadAbortException (); - case HResults.COR_E_THREADINTERRUPTED: - return new System.Threading.ThreadInterruptedException (); - case HResults.COR_E_THREADSTART: - return new System.Threading.ThreadStartException (); - case HResults.COR_E_THREADSTATE: - return new System.Threading.ThreadStateException (); - case HResults.COR_E_TYPEACCESS: - return new System.TypeAccessException (); - case HResults.COR_E_TYPEINITIALIZATION: - return new System.TypeInitializationException (""); - case HResults.COR_E_TYPELOAD: - return new System.TypeLoadException (); - case HResults.COR_E_TYPEUNLOADED: - return new System.TypeUnloadedException (); - case HResults.COR_E_UNAUTHORIZEDACCESS: - return new System.UnauthorizedAccessException (); - //case HResults.COR_E_UNSUPPORTEDFORMAT: - case HResults.COR_E_VERIFICATION: - return new System.Security.VerificationException (); - //case HResults.E_INVALIDARG: - case HResults.E_NOTIMPL: - return new System.NotImplementedException (); - //case HResults.E_POINTER: - case HResults.RO_E_CLOSED: - return new System.ObjectDisposedException (""); - case HResults.COR_E_ABANDONEDMUTEX: - case HResults.COR_E_AMBIGUOUSIMPLEMENTATION: - case HResults.COR_E_CANNOTUNLOADAPPDOMAIN: - case HResults.COR_E_CONTEXTMARSHAL: - case HResults.COR_E_HOSTPROTECTION: - case HResults.COR_E_INSUFFICIENTMEMORY: - case HResults.COR_E_INVALIDCOMOBJECT: - case HResults.COR_E_KEYNOTFOUND: - case HResults.COR_E_MISSINGSATELLITEASSEMBLY: - case HResults.COR_E_SAFEARRAYRANKMISMATCH: - case HResults.COR_E_SAFEARRAYTYPEMISMATCH: - case HResults.COR_E_SAFEHANDLEMISSINGATTRIBUTE: - case HResults.COR_E_SEMAPHOREFULL: - case HResults.COR_E_THREADSTOP: - case HResults.COR_E_TIMEOUT: - case HResults.COR_E_WAITHANDLECANNOTBEOPENED: - case HResults.DISP_E_OVERFLOW: - case HResults.E_BOUNDS: - case HResults.E_CHANGED_STATE: - case HResults.E_FAIL: - case HResults.E_HANDLE: - case HResults.ERROR_MRM_MAP_NOT_FOUND: - case HResults.TYPE_E_TYPEMISMATCH: - case HResults.CO_E_NOTINITIALIZED: - case HResults.RPC_E_CHANGED_MODE: - return new COMException ("", errorCode); - - case HResults.STG_E_PATHNOTFOUND: - case HResults.CTL_E_PATHNOTFOUND: { - return new System.IO.DirectoryNotFoundException { - HResult = errorCode - }; - } - case HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION: - case HResults.FUSION_E_SIGNATURE_CHECK_FAILED: - case HResults.FUSION_E_LOADFROM_BLOCKED: - case HResults.FUSION_E_CACHEFILE_FAILED: - case HResults.FUSION_E_ASM_MODULE_MISSING: - case HResults.FUSION_E_INVALID_NAME: - case HResults.FUSION_E_PRIVATE_ASM_DISALLOWED: - case HResults.FUSION_E_HOST_GAC_ASM_MISMATCH: - case HResults.COR_E_MODULE_HASH_CHECK_FAILED: - case HResults.FUSION_E_REF_DEF_MISMATCH: - case HResults.SECURITY_E_INCOMPATIBLE_SHARE: - case HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE: - case HResults.SECURITY_E_UNVERIFIABLE: - case HResults.COR_E_FIXUPSINEXE: - case HResults.ERROR_TOO_MANY_OPEN_FILES: - case HResults.ERROR_SHARING_VIOLATION: - case HResults.ERROR_LOCK_VIOLATION: - case HResults.ERROR_OPEN_FAILED: - case HResults.ERROR_DISK_CORRUPT: - case HResults.ERROR_UNRECOGNIZED_VOLUME: - case HResults.ERROR_DLL_INIT_FAILED: - case HResults.FUSION_E_CODE_DOWNLOAD_DISABLED: - case HResults.CORSEC_E_MISSING_STRONGNAME: - case HResults.MSEE_E_ASSEMBLYLOADINPROGRESS: - case HResults.ERROR_FILE_INVALID: { - return new System.IO.FileLoadException { - HResult = errorCode - }; - } - case HResults.CTL_E_FILENOTFOUND: { - return new System.IO.FileNotFoundException { - HResult = errorCode - }; - } - default: - return new COMException ("", errorCode); - } - } - - static void PrelinkCore (MethodInfo m) - { - if (!(m is RuntimeMethodInfo)) - { - throw new ArgumentException (SR.Argument_MustBeRuntimeMethodInfo, nameof(m)); - } - - PrelinkInternal (m); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static void PtrToStructureInternal (IntPtr ptr, object structure, bool allowValueClasses); - - static void PtrToStructureHelper (IntPtr ptr, object structure, bool allowValueClasses) - { - if (structure == null) - throw new ArgumentNullException (nameof (structure)); - PtrToStructureInternal (ptr, structure, allowValueClasses); - } - - static object PtrToStructureHelper (IntPtr ptr, Type structureType) - { - var obj = Activator.CreateInstance (structureType); - PtrToStructureHelper (ptr, obj, true); - return obj; - } - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t); - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void PrelinkInternal (MethodInfo m); - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern int SizeOfHelper (Type t, bool throwIfNotMarshalable); - - public static IntPtr GetExceptionPointers () - { - throw new PlatformNotSupportedException (); - } - - internal unsafe static IntPtr AllocBSTR (int length) - { - var res = BufferToBSTR ((char*)IntPtr.Zero, length); - if (res == IntPtr.Zero) - throw new OutOfMemoryException (); - return res; - } - - public unsafe static IntPtr StringToBSTR (string s) - { - if (s == null) - return IntPtr.Zero; - fixed (char* fixed_s = s) - return BufferToBSTR (fixed_s, s.Length); - } - - #region PlatformNotSupported - - public static int GetExceptionCode() - { - // Obsolete - throw new PlatformNotSupportedException (); - } - - public static byte ReadByte(Object ptr, int ofs) - { - // Obsolete - throw new PlatformNotSupportedException (); - } - - public static short ReadInt16(Object ptr, int ofs) - { - // Obsolete - throw new PlatformNotSupportedException (); - } - - public static int ReadInt32(Object ptr, int ofs) - { - // Obsolete - throw new PlatformNotSupportedException (); - } - - public static long ReadInt64(Object ptr, int ofs) - { - // Obsolete - throw new PlatformNotSupportedException (); - } - - public static void WriteByte(Object ptr, int ofs, byte val) - { - // Obsolete - throw new PlatformNotSupportedException (); - } - - public static void WriteInt16(Object ptr, int ofs, short val) - { - // Obsolete - throw new PlatformNotSupportedException (); - } - - public static void WriteInt32(Object ptr, int ofs, int val) - { - // Obsolete - throw new PlatformNotSupportedException (); - } - - public static void WriteInt64(Object ptr, int ofs, long val) - { - // Obsolete - throw new PlatformNotSupportedException (); - } - - #endregion - } -} - -namespace System -{ - internal static partial class HResults - { - // DirectoryNotFoundException - public const int STG_E_PATHNOTFOUND = unchecked((int)0x80030003); - public const int CTL_E_PATHNOTFOUND = unchecked((int)0x800A004C); - - // FileNotFoundException - public const int CTL_E_FILENOTFOUND = unchecked((int)0x800A0035); - - public const int FUSION_E_INVALID_PRIVATE_ASM_LOCATION = unchecked((int)0x80131041); - public const int FUSION_E_SIGNATURE_CHECK_FAILED = unchecked((int)0x80131045); - public const int FUSION_E_LOADFROM_BLOCKED = unchecked((int)0x80131051); - public const int FUSION_E_CACHEFILE_FAILED = unchecked((int)0x80131052); - public const int FUSION_E_ASM_MODULE_MISSING = unchecked((int)0x80131042); - public const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); - public const int FUSION_E_PRIVATE_ASM_DISALLOWED = unchecked((int)0x80131044); - public const int FUSION_E_HOST_GAC_ASM_MISMATCH = unchecked((int)0x80131050); - public const int COR_E_MODULE_HASH_CHECK_FAILED = unchecked((int)0x80131039); - public const int FUSION_E_REF_DEF_MISMATCH = unchecked((int)0x80131040); - public const int SECURITY_E_INCOMPATIBLE_SHARE = unchecked((int)0x80131401); - public const int SECURITY_E_INCOMPATIBLE_EVIDENCE = unchecked((int)0x80131403); - public const int SECURITY_E_UNVERIFIABLE = unchecked((int)0x80131402); - public const int COR_E_FIXUPSINEXE = unchecked((int)0x80131019); - public const int ERROR_TOO_MANY_OPEN_FILES = unchecked((int)0x80070004); - public const int ERROR_SHARING_VIOLATION = unchecked((int)0x80070020); - public const int ERROR_LOCK_VIOLATION = unchecked((int)0x80070021); - public const int ERROR_OPEN_FAILED = unchecked((int)0x8007006E); - public const int ERROR_DISK_CORRUPT = unchecked((int)0x80070571); - public const int ERROR_UNRECOGNIZED_VOLUME = unchecked((int)0x800703ED); - public const int ERROR_DLL_INIT_FAILED = unchecked((int)0x8007045A); - public const int FUSION_E_CODE_DOWNLOAD_DISABLED = unchecked((int)0x80131048); - public const int CORSEC_E_MISSING_STRONGNAME = unchecked((int)0x8013141b); - public const int MSEE_E_ASSEMBLYLOADINPROGRESS = unchecked((int)0x80131016); - public const int ERROR_FILE_INVALID = unchecked((int)0x800703EE); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/MarshalAsAttribute.Mono.cs b/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/MarshalAsAttribute.Mono.cs deleted file mode 100644 index 89353dbdd21..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/MarshalAsAttribute.Mono.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.InteropServices -{ - [StructLayout (LayoutKind.Sequential)] - partial class MarshalAsAttribute - { - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.Mono.cs b/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.Mono.cs deleted file mode 100644 index 32605afc5e1..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.Mono.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.IO; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices -{ - partial class NativeLibrary - { - static IntPtr LoadLibraryByName (string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool throwOnError) - { - return LoadByName (libraryName, - (RuntimeAssembly)assembly, - searchPath.HasValue, - (uint)searchPath.GetValueOrDefault(), - throwOnError); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static IntPtr LoadFromPath (string libraryName, bool throwOnError); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static IntPtr LoadByName (string libraryName, RuntimeAssembly callingAssembly, bool hasDllImportSearchPathFlag, uint dllImportSearchPathFlag, bool throwOnError); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void FreeLib (IntPtr handle); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static IntPtr GetSymbol (IntPtr handle, string symbolName, bool throwOnError); - - private static void MonoLoadLibraryCallbackStub (string libraryName, Assembly assembly, bool hasDllImportSearchPathFlags, uint dllImportSearchPathFlags, ref IntPtr dll) - { - dll = LoadLibraryCallbackStub (libraryName, assembly, hasDllImportSearchPathFlags, dllImportSearchPathFlags); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeHandle.Mono.cs b/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeHandle.Mono.cs deleted file mode 100644 index c9910f92714..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeHandle.Mono.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices -{ - // Mono runtime relies on exact layout - [StructLayout (LayoutKind.Sequential)] - public abstract partial class SafeHandle - { - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs b/netcore/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs deleted file mode 100644 index bed62bbae92..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.Loader -{ - public sealed class AssemblyDependencyResolver - { - public AssemblyDependencyResolver (string componentAssemblyPath) - { - } - - public string ResolveAssemblyToPath (System.Reflection.AssemblyName assemblyName) - { - throw new NotImplementedException (); - } - - public string ResolveUnmanagedDllToPath (string unmanagedDllName) - { - throw new NotImplementedException (); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.Mono.cs b/netcore/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.Mono.cs deleted file mode 100644 index eea013780c8..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.Mono.cs +++ /dev/null @@ -1,159 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.IO; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading; - -namespace System.Runtime.Loader -{ - partial class AssemblyLoadContext - { - internal IntPtr NativeALC { - get { - return _nativeAssemblyLoadContext; - } - } - - static IntPtr InitializeAssemblyLoadContext (IntPtr thisHandlePtr, bool representsTPALoadContext, bool isCollectible) - { - return InternalInitializeNativeALC (thisHandlePtr, representsTPALoadContext, isCollectible); - } - - static void PrepareForAssemblyLoadContextRelease (IntPtr nativeAssemblyLoadContext, IntPtr assemblyLoadContextStrong) - { - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - Assembly InternalLoadFromPath (string assemblyPath, string nativeImagePath) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - - assemblyPath = assemblyPath.Replace ('\\', Path.DirectorySeparatorChar); - // TODO: Handle nativeImagePath - return InternalLoadFile (NativeALC, assemblyPath, ref stackMark); - } - - internal Assembly InternalLoad (byte[] arrAssembly, byte[] arrSymbols) - { - unsafe { - int symbolsLength = arrSymbols?.Length ?? 0; - fixed (byte* ptrAssembly = arrAssembly, ptrSymbols = arrSymbols) - { - return InternalLoadFromStream (NativeALC, new IntPtr (ptrAssembly), arrAssembly.Length, - new IntPtr (ptrSymbols), symbolsLength); - } - } - } - - internal static Assembly[] GetLoadedAssemblies () - { - return InternalGetLoadedAssemblies (); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static IntPtr GetLoadContextForAssembly (RuntimeAssembly rtAsm); - - // Returns the load context in which the specified assembly has been loaded - public static AssemblyLoadContext? GetLoadContext (Assembly assembly) - { - if (assembly == null) - throw new ArgumentNullException (nameof (assembly)); - - AssemblyLoadContext? loadContextForAssembly = null; - - RuntimeAssembly? rtAsm = assembly as RuntimeAssembly; - - // We only support looking up load context for runtime assemblies. - if (rtAsm != null) { - RuntimeAssembly runtimeAssembly = rtAsm; - IntPtr ptrAssemblyLoadContext = GetLoadContextForAssembly (runtimeAssembly); - loadContextForAssembly = GetAssemblyLoadContext (ptrAssemblyLoadContext); - } - - return loadContextForAssembly; - } - - public void SetProfileOptimizationRoot (string directoryPath) - { - } - - public void StartProfileOptimization (string profile) - { - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static Assembly InternalLoadFile (IntPtr nativeAssemblyLoadContext, string assemblyFile, ref StackCrawlMark stackMark); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static IntPtr InternalInitializeNativeALC (IntPtr thisHandlePtr, bool representsTPALoadContext, bool isCollectible); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static Assembly InternalLoadFromStream (IntPtr nativeAssemblyLoadContext, IntPtr assm, int assmLength, IntPtr symbols, int symbolsLength); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static Assembly[] InternalGetLoadedAssemblies (); - - internal static Assembly DoAssemblyResolve (string name) - { - return AssemblyResolve (null, new ResolveEventArgs (name)); - } - - // Invoked by Mono to resolve using the load method. - static Assembly? MonoResolveUsingLoad (IntPtr gchALC, string assemblyName) - { - return Resolve (gchALC, new AssemblyName (assemblyName)); - } - - // Invoked by Mono to resolve using the Resolving event after - // trying the Load override and default load context without - // success. - static Assembly? MonoResolveUsingResolvingEvent (IntPtr gchALC, string assemblyName) - { - return ResolveUsingResolvingEvent (gchALC, new AssemblyName (assemblyName)); - } - - // Invoked by Mono to resolve requests to load satellite assemblies. - static Assembly? MonoResolveUsingResolveSatelliteAssembly (IntPtr gchALC, string assemblyName) - { - return ResolveSatelliteAssembly (gchALC, new AssemblyName (assemblyName)); - } - - private static AssemblyLoadContext GetAssemblyLoadContext (IntPtr gchManagedAssemblyLoadContext) - { - AssemblyLoadContext context; - // This check exists because the function can be called early in startup, before the default ALC is initialized - if (gchManagedAssemblyLoadContext == IntPtr.Zero) - context = AssemblyLoadContext.Default; - else - context = (AssemblyLoadContext)(GCHandle.FromIntPtr (gchManagedAssemblyLoadContext).Target)!; - return context; - } - - private static void MonoResolveUnmanagedDll (string unmanagedDllName, IntPtr gchManagedAssemblyLoadContext, ref IntPtr dll) - { - AssemblyLoadContext context = GetAssemblyLoadContext (gchManagedAssemblyLoadContext); - dll = context.LoadUnmanagedDll(unmanagedDllName); - } - - private static void MonoResolveUnmanagedDllUsingEvent (string unmanagedDllName, Assembly assembly, IntPtr gchManagedAssemblyLoadContext, ref IntPtr dll) - { - AssemblyLoadContext context = GetAssemblyLoadContext (gchManagedAssemblyLoadContext); - dll = context.GetResolvedUnmanagedDll(assembly, unmanagedDllName); - } - -#region Copied from AssemblyLoadContext.CoreCLR.cs, modified until our AssemblyBuilder implementation is functional - private static RuntimeAssembly? GetRuntimeAssembly(Assembly? asm) - { - return - asm == null ? null : - asm is RuntimeAssembly rtAssembly ? rtAssembly : - //asm is System.Reflection.Emit.AssemblyBuilder ab ? ab.InternalAssembly : - null; - } -#endregion - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Runtime/Remoting/Contexts/Context.cs b/netcore/System.Private.CoreLib/src/System/Runtime/Remoting/Contexts/Context.cs deleted file mode 100644 index 33064066db8..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Runtime/Remoting/Contexts/Context.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - -namespace System.Runtime.Remoting.Contexts { - - [StructLayout (LayoutKind.Sequential)] - /* FIXME: Mono: this was public in mscorlib */ - internal class Context - { -#pragma warning disable 169, 414 - #region Sync with domain-internals.h - int domain_id; - int context_id; - UIntPtr static_data; /* GC-tracked */ - UIntPtr data; - #endregion -#pragma warning restore 169, 414 - - [MethodImpl (MethodImplOptions.InternalCall)] - extern static void RegisterContext (Context ctx); - - [MethodImpl (MethodImplOptions.InternalCall)] - extern static void ReleaseContext (Context ctx); - - public Context () - { -#if false - domain_id = Thread.GetDomainID(); - context_id = Interlocked.Increment (ref global_count); - - RegisterContext (this); -#endif - } - - ~Context () - { - ReleaseContext (this); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/RuntimeArgumentHandle.cs b/netcore/System.Private.CoreLib/src/System/RuntimeArgumentHandle.cs deleted file mode 100644 index 983606c90b2..00000000000 --- a/netcore/System.Private.CoreLib/src/System/RuntimeArgumentHandle.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -// - -namespace System -{ - public ref struct RuntimeArgumentHandle - { - internal IntPtr args; - } -} diff --git a/netcore/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs b/netcore/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs deleted file mode 100644 index 46fff28b4cc..00000000000 --- a/netcore/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.Serialization; - -namespace System -{ - [Serializable] - public struct RuntimeFieldHandle : ISerializable - { - readonly IntPtr value; - - internal RuntimeFieldHandle (IntPtr v) - { - value = v; - } - - RuntimeFieldHandle (SerializationInfo info, StreamingContext context) - { - throw new PlatformNotSupportedException (); - } - - public void GetObjectData (SerializationInfo info, StreamingContext context) - { - throw new PlatformNotSupportedException (); - } - - public IntPtr Value { - get { - return value; - } - } - - internal bool IsNullHandle () - { - return value == IntPtr.Zero; - } - - public override bool Equals (object? obj) - { - if (obj == null || GetType () != obj.GetType ()) - return false; - - return value == ((RuntimeFieldHandle)obj).Value; - } - - public bool Equals (RuntimeFieldHandle handle) - { - return value == handle.Value; - } - - public override int GetHashCode () - { - return value.GetHashCode (); - } - - public static bool operator == (RuntimeFieldHandle left, RuntimeFieldHandle right) - { - return left.Equals (right); - } - - public static bool operator != (RuntimeFieldHandle left, RuntimeFieldHandle right) - { - return !left.Equals (right); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern void SetValueInternal (FieldInfo fi, object obj, object value); - - internal static void SetValue (RuntimeFieldInfo field, Object obj, Object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized) - { - SetValueInternal (field, obj, value); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static unsafe extern internal Object GetValueDirect (RuntimeFieldInfo field, RuntimeType fieldType, void *pTypedRef, RuntimeType contextType); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static unsafe extern internal void SetValueDirect (RuntimeFieldInfo field, RuntimeType fieldType, void* pTypedRef, Object value, RuntimeType contextType); - } - -} diff --git a/netcore/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs b/netcore/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs deleted file mode 100644 index 2e48cb4c686..00000000000 --- a/netcore/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs +++ /dev/null @@ -1,90 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Reflection; -using System.Runtime.Serialization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; - -namespace System -{ - [Serializable] - public struct RuntimeMethodHandle : ISerializable - { - readonly IntPtr value; - - internal RuntimeMethodHandle (IntPtr v) - { - value = v; - } - - RuntimeMethodHandle (SerializationInfo info, StreamingContext context) - { - throw new PlatformNotSupportedException (); - } - - public IntPtr Value => value; - - public void GetObjectData (SerializationInfo info, StreamingContext context) - { - throw new PlatformNotSupportedException (); - } - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern IntPtr GetFunctionPointer (IntPtr m); - - public IntPtr GetFunctionPointer () - { - return GetFunctionPointer (value); - } - - public override bool Equals (object? obj) - { - if (obj == null || GetType () != obj.GetType ()) - return false; - - return value == ((RuntimeMethodHandle)obj).Value; - } - - public bool Equals (RuntimeMethodHandle handle) - { - return value == handle.Value; - } - - public override int GetHashCode () - { - return value.GetHashCode (); - } - - public static bool operator == (RuntimeMethodHandle left, RuntimeMethodHandle right) - { - return left.Equals (right); - } - - public static bool operator != (RuntimeMethodHandle left, RuntimeMethodHandle right) - { - return !left.Equals (right); - } - - internal static string ConstructInstantiation (RuntimeMethodInfo method, TypeNameFormatFlags format) - { - var sb = new StringBuilder (); - var gen_params = method.GetGenericArguments (); - sb.Append ("["); - for (int j = 0; j < gen_params.Length; j++) { - if (j > 0) - sb.Append (","); - sb.Append (gen_params [j].Name); - } - sb.Append ("]"); - return sb.ToString (); - } - - internal bool IsNullHandle () - { - return value == IntPtr.Zero; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs b/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs deleted file mode 100644 index e7a2bf579e0..00000000000 --- a/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs +++ /dev/null @@ -1,2565 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Reflection; -using System.Globalization; -using System.Threading; -using System.Collections.Generic; -using System.Runtime.Serialization; -using System.Runtime.CompilerServices; -using System.Diagnostics.Contracts; -using System.Runtime.InteropServices; -using System.Diagnostics; - -namespace System -{ - // Keep this in sync with FormatFlags defined in typestring.h - internal enum TypeNameFormatFlags - { - FormatBasic = 0x00000000, // Not a bitmask, simply the tersest flag settings possible - FormatNamespace = 0x00000001, // Include namespace and/or enclosing class names in type names - FormatFullInst = 0x00000002, // Include namespace and assembly in generic types (regardless of other flag settings) - FormatAssembly = 0x00000004, // Include assembly display name in type names - FormatSignature = 0x00000008, // Include signature in method names - FormatNoVersion = 0x00000010, // Suppress version and culture information in all assembly names -#if _DEBUG - FormatDebug = 0x00000020, // For debug printing of types only -#endif - FormatAngleBrackets = 0x00000040, // Whether generic types are C<T> or C[T] - FormatStubInfo = 0x00000080, // Include stub info like {unbox-stub} - FormatGenericParam = 0x00000100, // Use !name and !!name for generic type and method parameters - - // If we want to be able to distinguish between overloads whose parameter types have the same name but come from different assemblies, - // we can add FormatAssembly | FormatNoVersion to FormatSerialization. But we are omitting it because it is not a useful scenario - // and including the assembly name will normally increase the size of the serialized data and also decrease the performance. - FormatSerialization = FormatNamespace | - FormatGenericParam | - FormatFullInst - } - - internal enum TypeNameKind - { - Name, - ToString, - SerializationName, - FullName, - } - - partial class RuntimeType - { - #region Definitions - - internal enum MemberListType - { - All, - CaseSensitive, - CaseInsensitive, - HandleToInfo - } - - // Helper to build lists of MemberInfos. Special cased to avoid allocations for lists of one element. - private struct ListBuilder<T> where T : class - { - T[] _items; - T _item; - int _count; - int _capacity; - - public ListBuilder(int capacity) - { - _items = null; - _item = null; - _count = 0; - _capacity = capacity; - } - - public T this[int index] - { - get - { - Contract.Requires(index < Count); - return (_items != null) ? _items[index] : _item; - } - } - - public T[] ToArray() - { - if (_count == 0) - return Array.Empty<T> (); - if (_count == 1) - return new T[1] { _item }; - - Array.Resize(ref _items, _count); - _capacity = _count; - return _items; - } - - public void CopyTo(Object[] array, int index) - { - if (_count == 0) - return; - - if (_count == 1) - { - array[index] = _item; - return; - } - - Array.Copy(_items, 0, array, index, _count); - } - - public int Count - { - get - { - return _count; - } - } - - public void Add(T item) - { - if (_count == 0) - { - _item = item; - } - else - { - if (_count == 1) - { - if (_capacity < 2) - _capacity = 4; - _items = new T[_capacity]; - _items[0] = _item; - } - else - if (_capacity == _count) - { - int newCapacity = 2 * _capacity; - Array.Resize(ref _items, newCapacity); - _capacity = newCapacity; - } - - _items[_count] = item; - } - _count++; - } - } - - #endregion - - #region Static Members - - #region Internal - - internal static RuntimeType GetType(String typeName, bool throwOnError, bool ignoreCase, bool reflectionOnly, - ref StackCrawlMark stackMark) - { - if (typeName == null) - throw new ArgumentNullException("typeName"); - Contract.EndContractBlock(); - - return RuntimeTypeHandle.GetTypeByName( - typeName, throwOnError, ignoreCase, reflectionOnly, ref stackMark, false); - } - - private static void ThrowIfTypeNeverValidGenericArgument(RuntimeType type) - { - if (type.IsPointer || type.IsByRef || type == typeof(void)) - throw new ArgumentException( - Environment.GetResourceString("Argument_NeverValidGenericArgument", type.ToString())); - } - - internal static void SanityCheckGenericArguments(RuntimeType[] genericArguments, RuntimeType[] genericParamters) - { - if (genericArguments == null) - throw new ArgumentNullException(); - Contract.EndContractBlock(); - - for(int i = 0; i < genericArguments.Length; i++) - { - if (genericArguments[i] == null) - throw new ArgumentNullException(); - - ThrowIfTypeNeverValidGenericArgument(genericArguments[i]); - } - - if (genericArguments.Length != genericParamters.Length) - throw new ArgumentException( - Environment.GetResourceString("Argument_NotEnoughGenArguments", genericArguments.Length, genericParamters.Length)); - } - - private static void SplitName(string fullname, out string name, out string ns) - { - name = null; - ns = null; - - if (fullname == null) - return; - - // Get namespace - int nsDelimiter = fullname.LastIndexOf(".", StringComparison.Ordinal); - if (nsDelimiter != -1 ) - { - ns = fullname.Substring(0, nsDelimiter); - int nameLength = fullname.Length - ns.Length - 1; - if (nameLength != 0) - name = fullname.Substring(nsDelimiter + 1, nameLength); - else - name = ""; - Contract.Assert(fullname.Equals(ns + "." + name)); - } - else - { - name = fullname; - } - - } - #endregion - - #region Filters - internal static BindingFlags FilterPreCalculate(bool isPublic, bool isInherited, bool isStatic) - { - BindingFlags bindingFlags = isPublic ? BindingFlags.Public : BindingFlags.NonPublic; - - if (isInherited) - { - // We arrange things so the DeclaredOnly flag means "include inherited members" - bindingFlags |= BindingFlags.DeclaredOnly; - - if (isStatic) - { - bindingFlags |= BindingFlags.Static | BindingFlags.FlattenHierarchy; - } - else - { - bindingFlags |= BindingFlags.Instance; - } - } - else - { - if (isStatic) - { - bindingFlags |= BindingFlags.Static; - } - else - { - bindingFlags |= BindingFlags.Instance; - } - } - - return bindingFlags; - } - - // Calculate prefixLookup, ignoreCase, and listType for use by GetXXXCandidates - private static void FilterHelper( - BindingFlags bindingFlags, ref string name, bool allowPrefixLookup, out bool prefixLookup, - out bool ignoreCase, out MemberListType listType) - { - prefixLookup = false; - ignoreCase = false; - - if (name != null) - { - if ((bindingFlags & BindingFlags.IgnoreCase) != 0) - { - name = name.ToLower(CultureInfo.InvariantCulture); - ignoreCase = true; - listType = MemberListType.CaseInsensitive; - } - else - { - listType = MemberListType.CaseSensitive; - } - - if (allowPrefixLookup && name.EndsWith("*", StringComparison.Ordinal)) - { - // We set prefixLookup to true if name ends with a "*". - // We will also set listType to All so that all members are included in - // the candidates which are later filtered by FilterApplyPrefixLookup. - name = name.Substring(0, name.Length - 1); - prefixLookup = true; - listType = MemberListType.All; - } - } - else - { - listType = MemberListType.All; - } - } - - // Used by the singular GetXXX APIs (Event, Field, Interface, NestedType) where prefixLookup is not supported. - private static void FilterHelper(BindingFlags bindingFlags, ref string name, out bool ignoreCase, out MemberListType listType) - { - bool prefixLookup; - FilterHelper(bindingFlags, ref name, false, out prefixLookup, out ignoreCase, out listType); - } - - // Only called by GetXXXCandidates, GetInterfaces, and GetNestedTypes when FilterHelper has set "prefixLookup" to true. - // Most of the plural GetXXX methods allow prefix lookups while the singular GetXXX methods mostly do not. - private static bool FilterApplyPrefixLookup(MemberInfo memberInfo, string name, bool ignoreCase) - { - Contract.Assert(name != null); - - if (ignoreCase) - { - if (!memberInfo.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase)) - return false; - } - else - { - if (!memberInfo.Name.StartsWith(name, StringComparison.Ordinal)) - return false; - } - - return true; - } - - - // Used by FilterApplyType to perform all the filtering based on name and BindingFlags - private static bool FilterApplyBase( - MemberInfo memberInfo, BindingFlags bindingFlags, bool isPublic, bool isNonProtectedInternal, bool isStatic, - string name, bool prefixLookup) - { - #region Preconditions - Contract.Requires(memberInfo != null); - Contract.Requires(name == null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLower(CultureInfo.InvariantCulture).Equals(name))); - #endregion - - #region Filter by Public & Private - if (isPublic) - { - if ((bindingFlags & BindingFlags.Public) == 0) - return false; - } - else - { - if ((bindingFlags & BindingFlags.NonPublic) == 0) - return false; - } - #endregion - - bool isInherited = !Object.ReferenceEquals(memberInfo.DeclaringType, memberInfo.ReflectedType); - - #region Filter by DeclaredOnly - if ((bindingFlags & BindingFlags.DeclaredOnly) != 0 && isInherited) - return false; - #endregion - - #region Filter by Static & Instance - if (memberInfo.MemberType != MemberTypes.TypeInfo && - memberInfo.MemberType != MemberTypes.NestedType) - { - if (isStatic) - { - if ((bindingFlags & BindingFlags.FlattenHierarchy) == 0 && isInherited) - return false; - - if ((bindingFlags & BindingFlags.Static) == 0) - return false; - } - else - { - if ((bindingFlags & BindingFlags.Instance) == 0) - return false; - } - } - #endregion - - #region Filter by name wrt prefixLookup and implicitly by case sensitivity - if (prefixLookup == true) - { - if (!FilterApplyPrefixLookup(memberInfo, name, (bindingFlags & BindingFlags.IgnoreCase) != 0)) - return false; - } - #endregion - - #region Asymmetries - // @Asymmetry - Internal, inherited, instance, non-protected, non-virtual, non-abstract members returned - // iff BindingFlags !DeclaredOnly, Instance and Public are present except for fields - if (((bindingFlags & BindingFlags.DeclaredOnly) == 0) && // DeclaredOnly not present - isInherited && // Is inherited Member - - (isNonProtectedInternal) && // Is non-protected internal member - ((bindingFlags & BindingFlags.NonPublic) != 0) && // BindingFlag.NonPublic present - - (!isStatic) && // Is instance member - ((bindingFlags & BindingFlags.Instance) != 0)) // BindingFlag.Instance present - { - MethodInfo methodInfo = memberInfo as MethodInfo; - - if (methodInfo == null) - return false; - - if (!methodInfo.IsVirtual && !methodInfo.IsAbstract) - return false; - } - #endregion - - return true; - } - - - // Used by GetInterface and GetNestedType(s) which don't need parameter type filtering. - private static bool FilterApplyType( - Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns) - { - Contract.Requires((object)type != null); - Contract.Assert(type is RuntimeType); - - bool isPublic = type.IsNestedPublic || type.IsPublic; - bool isStatic = false; - - if (!FilterApplyBase(type, bindingFlags, isPublic, type.IsNestedAssembly, isStatic, name, prefixLookup)) - return false; - - if (ns != null && ns != type.Namespace) - return false; - - return true; - } - - - private static bool FilterApplyMethodInfo( - RuntimeMethodInfo method, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) - { - // Optimization: Pre-Calculate the method binding flags to avoid casting. - return FilterApplyMethodBase(method, method.BindingFlags, bindingFlags, callConv, argumentTypes); - } - - private static bool FilterApplyConstructorInfo( - RuntimeConstructorInfo constructor, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) - { - // Optimization: Pre-Calculate the method binding flags to avoid casting. - return FilterApplyMethodBase(constructor, constructor.BindingFlags, bindingFlags, callConv, argumentTypes); - } - - // Used by GetMethodCandidates/GetConstructorCandidates, InvokeMember, and CreateInstanceImpl to perform the necessary filtering. - // Should only be called by FilterApplyMethodInfo and FilterApplyConstructorInfo. - private static bool FilterApplyMethodBase( - MethodBase methodBase, BindingFlags methodFlags, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) - { - Contract.Requires(methodBase != null); - - bindingFlags ^= BindingFlags.DeclaredOnly; - #region Check CallingConvention - if ((callConv & CallingConventions.Any) == 0) - { - if ((callConv & CallingConventions.VarArgs) != 0 && - (methodBase.CallingConvention & CallingConventions.VarArgs) == 0) - return false; - - if ((callConv & CallingConventions.Standard) != 0 && - (methodBase.CallingConvention & CallingConventions.Standard) == 0) - return false; - } - #endregion - - #region If argumentTypes supplied - if (argumentTypes != null) - { - ParameterInfo[] parameterInfos = methodBase.GetParametersNoCopy(); - - if (argumentTypes.Length != parameterInfos.Length) - { - #region Invoke Member, Get\Set & Create Instance specific case - // If the number of supplied arguments differs than the number in the signature AND - // we are not filtering for a dynamic call -- InvokeMethod or CreateInstance -- filter out the method. - if ((bindingFlags & - (BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.GetProperty | BindingFlags.SetProperty)) == 0) - return false; - - bool testForParamArray = false; - bool excessSuppliedArguments = argumentTypes.Length > parameterInfos.Length; - - if (excessSuppliedArguments) - { // more supplied arguments than parameters, additional arguments could be vararg - #region Varargs - // If method is not vararg, additional arguments can not be passed as vararg - if ((methodBase.CallingConvention & CallingConventions.VarArgs) == 0) - { - testForParamArray = true; - } - else - { - // If Binding flags did not include varargs we would have filtered this vararg method. - // This Invariant established during callConv check. - Contract.Assert((callConv & CallingConventions.VarArgs) != 0); - } - #endregion - } - else - {// fewer supplied arguments than parameters, missing arguments could be optional - #region OptionalParamBinding - if ((bindingFlags & BindingFlags.OptionalParamBinding) == 0) - { - testForParamArray = true; - } - else - { - // From our existing code, our policy here is that if a parameterInfo - // is optional then all subsequent parameterInfos shall be optional. - - // Thus, iff the first parameterInfo is not optional then this MethodInfo is no longer a canidate. - if (!parameterInfos[argumentTypes.Length].IsOptional) - testForParamArray = true; - } - #endregion - } - - #region ParamArray - if (testForParamArray) - { - if (parameterInfos.Length == 0) - return false; - - // The last argument of the signature could be a param array. - bool shortByMoreThanOneSuppliedArgument = argumentTypes.Length < parameterInfos.Length - 1; - - if (shortByMoreThanOneSuppliedArgument) - return false; - - ParameterInfo lastParameter = parameterInfos[parameterInfos.Length - 1]; - - if (!lastParameter.ParameterType.IsArray) - return false; - - if (!lastParameter.IsDefined(typeof(ParamArrayAttribute), false)) - return false; - } - #endregion - - #endregion - } - else - { - #region Exact Binding - if ((bindingFlags & BindingFlags.ExactBinding) != 0) - { - // Legacy behavior is to ignore ExactBinding when InvokeMember is specified. - // Why filter by InvokeMember? If the answer is we leave this to the binder then why not leave - // all the rest of this to the binder too? Further, what other semanitc would the binder - // use for BindingFlags.ExactBinding besides this one? Further, why not include CreateInstance - // in this if statement? That's just InvokeMethod with a constructor, right? - if ((bindingFlags & (BindingFlags.InvokeMethod)) == 0) - { - for(int i = 0; i < parameterInfos.Length; i ++) - { - // a null argument type implies a null arg which is always a perfect match - if ((object)argumentTypes[i] != null && !argumentTypes[i].MatchesParameterTypeExactly(parameterInfos[i])) - return false; - } - } - } - #endregion - } - } - #endregion - - return true; - } - - #endregion - - #endregion - - #region Private Data Members - - internal static readonly RuntimeType ValueType = (RuntimeType)typeof(System.ValueType); - internal static readonly RuntimeType EnumType = (RuntimeType)typeof(System.Enum); - - private static readonly RuntimeType ObjectType = (RuntimeType)typeof(System.Object); - private static readonly RuntimeType StringType = (RuntimeType)typeof(System.String); - private static readonly RuntimeType DelegateType = (RuntimeType)typeof(System.Delegate); - - #endregion - - #region Constructor - internal RuntimeType() { throw new NotSupportedException(); } - #endregion - - #region Type Overrides - - #region Get XXXInfo Candidates - private ListBuilder<MethodInfo> GetMethodCandidates( - String name, BindingFlags bindingAttr, CallingConventions callConv, - Type[] types, int genericParamCount, bool allowPrefixLookup) - { - bool prefixLookup, ignoreCase; - MemberListType listType; - FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType); - - RuntimeMethodInfo[] cache = GetMethodsByName (name, bindingAttr, listType, this); - ListBuilder<MethodInfo> candidates = new ListBuilder<MethodInfo>(cache.Length); - - for (int i = 0; i < cache.Length; i++) - { - RuntimeMethodInfo methodInfo = cache[i]; - if (genericParamCount != -1) { - bool is_generic = methodInfo.IsGenericMethod; - if (genericParamCount == 0 && is_generic) - continue; - else if (genericParamCount > 0 && !is_generic) - continue; - var args = methodInfo.GetGenericArguments (); - if (args.Length != genericParamCount) - continue; - } - if (FilterApplyMethodInfo(methodInfo, bindingAttr, callConv, types) && - (!prefixLookup || FilterApplyPrefixLookup(methodInfo, name, ignoreCase))) - { - candidates.Add(methodInfo); - } - } - - return candidates; - } - - private ListBuilder<ConstructorInfo> GetConstructorCandidates( - string name, BindingFlags bindingAttr, CallingConventions callConv, - Type[] types, bool allowPrefixLookup) - { - bool prefixLookup, ignoreCase; - MemberListType listType; - FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType); - - if (!string.IsNullOrEmpty (name) && name != ConstructorInfo.ConstructorName && name != ConstructorInfo.TypeConstructorName) - return new ListBuilder<ConstructorInfo> (0); - RuntimeConstructorInfo[] cache = GetConstructors_internal (bindingAttr, this); - ListBuilder<ConstructorInfo> candidates = new ListBuilder<ConstructorInfo>(cache.Length); - for (int i = 0; i < cache.Length; i++) - { - RuntimeConstructorInfo constructorInfo = cache[i]; - if (FilterApplyConstructorInfo(constructorInfo, bindingAttr, callConv, types) && - (!prefixLookup || FilterApplyPrefixLookup(constructorInfo, name, ignoreCase))) - { - candidates.Add(constructorInfo); - } - } - - return candidates; - } - - - private ListBuilder<PropertyInfo> GetPropertyCandidates( - String name, BindingFlags bindingAttr, Type[] types, bool allowPrefixLookup) - { - bool prefixLookup, ignoreCase; - MemberListType listType; - FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType); - - RuntimePropertyInfo[] cache = GetPropertiesByName (name, bindingAttr, listType, this); - bindingAttr ^= BindingFlags.DeclaredOnly; - - ListBuilder<PropertyInfo> candidates = new ListBuilder<PropertyInfo>(cache.Length); - for (int i = 0; i < cache.Length; i++) - { - RuntimePropertyInfo propertyInfo = cache[i]; - if ((bindingAttr & propertyInfo.BindingFlags) == propertyInfo.BindingFlags && - (!prefixLookup || FilterApplyPrefixLookup(propertyInfo, name, ignoreCase)) && - (types == null || (propertyInfo.GetIndexParameters().Length == types.Length))) - { - candidates.Add(propertyInfo); - } - } - - return candidates; - } - - private ListBuilder<EventInfo> GetEventCandidates(String name, BindingFlags bindingAttr, bool allowPrefixLookup) - { - bool prefixLookup, ignoreCase; - MemberListType listType; - FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType); - - RuntimeEventInfo[] cache = GetEvents_internal (name, bindingAttr, listType, this); - bindingAttr ^= BindingFlags.DeclaredOnly; - - ListBuilder<EventInfo> candidates = new ListBuilder<EventInfo>(cache.Length); - for (int i = 0; i < cache.Length; i++) - { - RuntimeEventInfo eventInfo = cache[i]; - if ((bindingAttr & eventInfo.BindingFlags) == eventInfo.BindingFlags && - (!prefixLookup || FilterApplyPrefixLookup(eventInfo, name, ignoreCase))) - { - candidates.Add(eventInfo); - } - } - - return candidates; - } - - private ListBuilder<FieldInfo> GetFieldCandidates(String name, BindingFlags bindingAttr, bool allowPrefixLookup) - { - bool prefixLookup, ignoreCase; - MemberListType listType; - FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType); - - RuntimeFieldInfo[] cache = GetFields_internal (name, bindingAttr, listType, this); - bindingAttr ^= BindingFlags.DeclaredOnly; - - ListBuilder<FieldInfo> candidates = new ListBuilder<FieldInfo>(cache.Length); - for (int i = 0; i < cache.Length; i++) - { - RuntimeFieldInfo fieldInfo = cache[i]; - if ((bindingAttr & fieldInfo.BindingFlags) == fieldInfo.BindingFlags && - (!prefixLookup || FilterApplyPrefixLookup(fieldInfo, name, ignoreCase))) - { - candidates.Add(fieldInfo); - } - } - - return candidates; - } - - private ListBuilder<Type> GetNestedTypeCandidates(String fullname, BindingFlags bindingAttr, bool allowPrefixLookup) - { - bool prefixLookup, ignoreCase; - bindingAttr &= ~BindingFlags.Static; - string name, ns; - MemberListType listType; - SplitName(fullname, out name, out ns); - FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType); - - RuntimeType[] cache = GetNestedTypes_internal (name, bindingAttr, listType); - ListBuilder<Type> candidates = new ListBuilder<Type>(cache.Length); - for (int i = 0; i < cache.Length; i++) - { - RuntimeType nestedClass = cache[i]; - if (FilterApplyType(nestedClass, bindingAttr, name, prefixLookup, ns)) - { - candidates.Add(nestedClass); - } - } - - return candidates; - } - - #endregion - - #region Get All XXXInfos - public override MethodInfo[] GetMethods(BindingFlags bindingAttr) - { - return GetMethodCandidates(null, bindingAttr, CallingConventions.Any, null, -1, false).ToArray(); - } - - [ComVisible(true)] - public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) - { - return GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, null, false).ToArray(); - } - - public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) - { - return GetPropertyCandidates(null, bindingAttr, null, false).ToArray(); - } - - public override EventInfo[] GetEvents(BindingFlags bindingAttr) - { - return GetEventCandidates(null, bindingAttr, false).ToArray(); - } - - public override FieldInfo[] GetFields(BindingFlags bindingAttr) - { - return GetFieldCandidates(null, bindingAttr, false).ToArray(); - } - - public override Type[] GetNestedTypes(BindingFlags bindingAttr) - { - return GetNestedTypeCandidates(null, bindingAttr, false).ToArray(); - } - - public override MemberInfo[] GetMembers(BindingFlags bindingAttr) - { - ListBuilder<MethodInfo> methods = GetMethodCandidates(null, bindingAttr, CallingConventions.Any, null, -1, false); - ListBuilder<ConstructorInfo> constructors = GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, null, false); - ListBuilder<PropertyInfo> properties = GetPropertyCandidates(null, bindingAttr, null, false); - ListBuilder<EventInfo> events = GetEventCandidates(null, bindingAttr, false); - ListBuilder<FieldInfo> fields = GetFieldCandidates(null, bindingAttr, false); - ListBuilder<Type> nestedTypes = GetNestedTypeCandidates(null, bindingAttr, false); - // Interfaces are excluded from the result of GetMembers - - MemberInfo[] members = new MemberInfo[ - methods.Count + - constructors.Count + - properties.Count + - events.Count + - fields.Count + - nestedTypes.Count]; - - int i = 0; - methods.CopyTo(members, i); i += methods.Count; - constructors.CopyTo(members, i); i += constructors.Count; - properties.CopyTo(members, i); i += properties.Count; - events.CopyTo(members, i); i += events.Count; - fields.CopyTo(members, i); i += fields.Count; - nestedTypes.CopyTo(members, i); i += nestedTypes.Count; - Contract.Assert(i == members.Length); - - return members; - } - - #endregion - - protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) - { - return GetMethodImpl (name, -1, bindingAttr, binder, callConvention, types, modifiers); - } - - protected override MethodInfo GetMethodImpl(String name, int genericParamCount, - BindingFlags bindingAttr, Binder? binder, CallingConventions callConv, - Type[]? types, ParameterModifier[]? modifiers) - { - ListBuilder<MethodInfo> candidates = GetMethodCandidates(name, bindingAttr, callConv, types, genericParamCount, false); - if (candidates.Count == 0) - return null; - - if (types == null || types.Length == 0) - { - MethodInfo firstCandidate = candidates[0]; - - if (candidates.Count == 1) - { - return firstCandidate; - } - else if (types == null) - { - for (int j = 1; j < candidates.Count; j++) - { - MethodInfo methodInfo = candidates[j]; - if (!System.DefaultBinder.CompareMethodSig (methodInfo, firstCandidate)) - throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); - } - - // All the methods have the exact same name and sig so return the most derived one. - return System.DefaultBinder.FindMostDerivedNewSlotMeth(candidates.ToArray(), candidates.Count) as MethodInfo; - } - } - - if (binder == null) - binder = DefaultBinder; - - return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo; - } - - protected override ConstructorInfo GetConstructorImpl( - BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, - Type[] types, ParameterModifier[]? modifiers) - { - ListBuilder<ConstructorInfo> candidates = GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, types, false); - - if (candidates.Count == 0) - return null; - - if (types.Length == 0 && candidates.Count == 1) - { - ConstructorInfo firstCandidate = candidates[0]; - - ParameterInfo[] parameters = firstCandidate.GetParametersNoCopy(); - if (parameters == null || parameters.Length == 0) - { - return firstCandidate; - } - } - - if ((bindingAttr & BindingFlags.ExactBinding) != 0) - return System.DefaultBinder.ExactBinding(candidates.ToArray(), types, modifiers) as ConstructorInfo; - - if (binder == null) - binder = DefaultBinder; - - return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as ConstructorInfo; - } - - - protected override PropertyInfo GetPropertyImpl( - String name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) - { - if (name == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); - - ListBuilder<PropertyInfo> candidates = GetPropertyCandidates(name, bindingAttr, types, false); - - if (candidates.Count == 0) - return null; - - if (types == null || types.Length == 0) - { - // no arguments - if (candidates.Count == 1) - { - PropertyInfo firstCandidate = candidates[0]; - - if ((object)returnType != null && !returnType.IsEquivalentTo(firstCandidate.PropertyType)) - return null; - - return firstCandidate; - } - else - { - if ((object)returnType == null) - // if we are here we have no args or property type to select over and we have more than one property with that name - throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); - } - } - - if ((bindingAttr & BindingFlags.ExactBinding) != 0) - return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types, modifiers); - - if (binder == null) - binder = DefaultBinder; - - return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers); - } - - public override EventInfo GetEvent(String name, BindingFlags bindingAttr) - { - if (name == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); - - bool ignoreCase; - MemberListType listType; - FilterHelper(bindingAttr, ref name, out ignoreCase, out listType); - - RuntimeEventInfo[] cache = GetEvents_internal (name, bindingAttr, listType, this); - EventInfo match = null; - - bindingAttr ^= BindingFlags.DeclaredOnly; - - for (int i = 0; i < cache.Length; i++) - { - RuntimeEventInfo eventInfo = cache[i]; - if ((bindingAttr & eventInfo.BindingFlags) == eventInfo.BindingFlags) - { - if (match != null) - throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); - - match = eventInfo; - } - } - - return match; - } - - public override FieldInfo GetField(String name, BindingFlags bindingAttr) - { - if (name == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); - - bool ignoreCase; - MemberListType listType; - FilterHelper(bindingAttr, ref name, out ignoreCase, out listType); - - RuntimeFieldInfo[] cache = GetFields_internal (name, bindingAttr, listType, this); - FieldInfo match = null; - - bindingAttr ^= BindingFlags.DeclaredOnly; - bool multipleStaticFieldMatches = false; - - for (int i = 0; i < cache.Length; i++) - { - RuntimeFieldInfo fieldInfo = cache[i]; - if ((bindingAttr & fieldInfo.BindingFlags) == fieldInfo.BindingFlags) - { - if (match != null) - { - if (Object.ReferenceEquals(fieldInfo.DeclaringType, match.DeclaringType)) - throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); - - if ((match.DeclaringType.IsInterface == true) && (fieldInfo.DeclaringType.IsInterface == true)) - multipleStaticFieldMatches = true; - } - - if (match == null || fieldInfo.DeclaringType.IsSubclassOf(match.DeclaringType) || match.DeclaringType.IsInterface) - match = fieldInfo; - } - } - - if (multipleStaticFieldMatches && match.DeclaringType.IsInterface) - throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); - - return match; - } - - public override Type GetInterface(String fullname, bool ignoreCase) - { - if (fullname == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); - - BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic; - - bindingAttr &= ~BindingFlags.Static; - - if (ignoreCase) - bindingAttr |= BindingFlags.IgnoreCase; - - string name, ns; - MemberListType listType; - SplitName(fullname, out name, out ns); - FilterHelper(bindingAttr, ref name, out ignoreCase, out listType); - - List<RuntimeType> list = null; - var nameComparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - foreach (RuntimeType t in GetInterfaces ()) { - - if (!String.Equals(t.Name, name, nameComparison)) { - continue; - } - - if (list == null) - list = new List<RuntimeType> (2); - - list.Add (t); - } - - if (list == null) - return null; - - var cache = list.ToArray (); - RuntimeType match = null; - - for (int i = 0; i < cache.Length; i++) - { - RuntimeType iface = cache[i]; - if (FilterApplyType(iface, bindingAttr, name, false, ns)) - { - if (match != null) - throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); - - match = iface; - } - } - - return match; - } - - public override Type GetNestedType(String fullname, BindingFlags bindingAttr) - { - if (fullname == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); - - bool ignoreCase; - bindingAttr &= ~BindingFlags.Static; - string name, ns; - MemberListType listType; - SplitName(fullname, out name, out ns); - FilterHelper(bindingAttr, ref name, out ignoreCase, out listType); - RuntimeType[] cache = GetNestedTypes_internal (name, bindingAttr, listType); - RuntimeType match = null; - - for (int i = 0; i < cache.Length; i++) - { - RuntimeType nestedType = cache[i]; - if (FilterApplyType(nestedType, bindingAttr, name, false, ns)) - { - if (match != null) - throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); - - match = nestedType; - } - } - - return match; - } - - public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) - { - if (name == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); - - ListBuilder<MethodInfo> methods = new ListBuilder<MethodInfo>(); - ListBuilder<ConstructorInfo> constructors = new ListBuilder<ConstructorInfo>(); - ListBuilder<PropertyInfo> properties = new ListBuilder<PropertyInfo>(); - ListBuilder<EventInfo> events = new ListBuilder<EventInfo>(); - ListBuilder<FieldInfo> fields = new ListBuilder<FieldInfo>(); - ListBuilder<Type> nestedTypes = new ListBuilder<Type>(); - - int totalCount = 0; - - // Methods - if ((type & MemberTypes.Method) != 0) - { - methods = GetMethodCandidates(name, bindingAttr, CallingConventions.Any, null, -1, true); - if (type == MemberTypes.Method) - return methods.ToArray(); - totalCount += methods.Count; - } - - // Constructors - if ((type & MemberTypes.Constructor) != 0) - { - constructors = GetConstructorCandidates(name, bindingAttr, CallingConventions.Any, null, true); - if (type == MemberTypes.Constructor) - return constructors.ToArray(); - totalCount += constructors.Count; - } - - // Properties - if ((type & MemberTypes.Property) != 0) - { - properties = GetPropertyCandidates(name, bindingAttr, null, true); - if (type == MemberTypes.Property) - return properties.ToArray(); - totalCount += properties.Count; - } - - // Events - if ((type & MemberTypes.Event) != 0) - { - events = GetEventCandidates(name, bindingAttr, true); - if (type == MemberTypes.Event) - return events.ToArray(); - totalCount += events.Count; - } - - // Fields - if ((type & MemberTypes.Field) != 0) - { - fields = GetFieldCandidates(name, bindingAttr, true); - if (type == MemberTypes.Field) - return fields.ToArray(); - totalCount += fields.Count; - } - - // NestedTypes - if ((type & (MemberTypes.NestedType | MemberTypes.TypeInfo)) != 0) - { - nestedTypes = GetNestedTypeCandidates(name, bindingAttr, true); - if (type == MemberTypes.NestedType || type == MemberTypes.TypeInfo) - return nestedTypes.ToArray(); - totalCount += nestedTypes.Count; - } - - MemberInfo[] compressMembers = (type == (MemberTypes.Method | MemberTypes.Constructor)) ? - new MethodBase[totalCount] : new MemberInfo[totalCount]; - - int i = 0; - methods.CopyTo(compressMembers, i); i += methods.Count; - constructors.CopyTo(compressMembers, i); i += constructors.Count; - properties.CopyTo(compressMembers, i); i += properties.Count; - events.CopyTo(compressMembers, i); i += events.Count; - fields.CopyTo(compressMembers, i); i += fields.Count; - nestedTypes.CopyTo(compressMembers, i); i += nestedTypes.Count; - Contract.Assert(i == compressMembers.Length); - - return compressMembers; - } - #endregion - - - #region Hierarchy - - // Reflexive, symmetric, transitive. - public override bool IsEquivalentTo(Type? other) - { - RuntimeType otherRtType = other as RuntimeType; - if ((object)otherRtType == null) - return false; - - if (otherRtType == this) - return true; - - // It's not worth trying to perform further checks in managed - // as they would lead to FCalls anyway. - return RuntimeTypeHandle.IsEquivalentTo(this, otherRtType); - } - - #endregion - - #region Attributes - - internal bool IsDelegate() - { - return GetBaseType() == typeof(System.MulticastDelegate); - } - - public override bool IsEnum => GetBaseType() == EnumType; - - public override GenericParameterAttributes GenericParameterAttributes - { - get - { - if (!IsGenericParameter) - throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter")); - Contract.EndContractBlock(); - - return GetGenericParameterAttributes (); - } - } - - #endregion - - #region Generics - - internal RuntimeType[] GetGenericArgumentsInternal() - { - return (RuntimeType[]) GetGenericArgumentsInternal (true); - } - - public override Type[] GetGenericArguments() - { - Type[] types = GetGenericArgumentsInternal (false); - - if (types == null) - types = Array.Empty<Type> (); - - return types; - } - - public override Type MakeGenericType(Type[] instantiation) - { - if (instantiation == null) - throw new ArgumentNullException("instantiation"); - Contract.EndContractBlock(); - - RuntimeType[] instantiationRuntimeType = new RuntimeType[instantiation.Length]; - - if (!IsGenericTypeDefinition) - throw new InvalidOperationException( - Environment.GetResourceString("Arg_NotGenericTypeDefinition", this)); - - if (GetGenericArguments().Length != instantiation.Length) - throw new ArgumentException(Environment.GetResourceString("Argument_GenericArgsCount"), "instantiation"); - - for (int i = 0; i < instantiation.Length; i ++) - { - Type instantiationElem = instantiation[i]; - if (instantiationElem == null) - throw new ArgumentNullException(); - - RuntimeType rtInstantiationElem = instantiationElem as RuntimeType; - - if (rtInstantiationElem == null) - { - if (instantiationElem.IsSignatureType) - return MakeGenericSignatureType (this, instantiation); - Type[] instantiationCopy = new Type[instantiation.Length]; - for (int iCopy = 0; iCopy < instantiation.Length; iCopy++) - instantiationCopy[iCopy] = instantiation[iCopy]; - instantiation = instantiationCopy; - - throw new NotImplementedException (); - } - - instantiationRuntimeType[i] = rtInstantiationElem; - } - - RuntimeType[] genericParameters = GetGenericArgumentsInternal(); - - SanityCheckGenericArguments(instantiationRuntimeType, genericParameters); - - Type ret = null; - ret = MakeGenericType (this, instantiationRuntimeType); - if (ret == null) - throw new TypeLoadException (); - return ret; - } - - public override int GenericParameterPosition - { - get - { - if (!IsGenericParameter) - throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter")); - Contract.EndContractBlock(); - return GetGenericParameterPosition (); - } - } - - #endregion - - #region Invoke Member - private const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF; - private const BindingFlags InvocationMask = (BindingFlags)0x0000FF00; - private const BindingFlags BinderNonCreateInstance = BindingFlags.InvokeMethod | BinderGetSetField | BinderGetSetProperty; - private const BindingFlags BinderGetSetProperty = BindingFlags.GetProperty | BindingFlags.SetProperty; - private const BindingFlags BinderSetInvokeProperty = BindingFlags.InvokeMethod | BindingFlags.SetProperty; - private const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField; - private const BindingFlags BinderSetInvokeField = BindingFlags.SetField | BindingFlags.InvokeMethod; - private const BindingFlags BinderNonFieldGetSet = (BindingFlags)0x00FFF300; - private const BindingFlags ClassicBindingMask = - BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty | - BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty; - private static RuntimeType s_typedRef = (RuntimeType)typeof(TypedReference); - - - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - public override Object InvokeMember( - String name, BindingFlags bindingFlags, Binder? binder, Object? target, - Object?[]? providedArgs, ParameterModifier[]? modifiers, CultureInfo? culture, String[]? namedParams) - { - if (IsGenericParameter) - throw new InvalidOperationException(Environment.GetResourceString("Arg_GenericParameter")); - Contract.EndContractBlock(); - - #region Preconditions - if ((bindingFlags & InvocationMask) == 0) - // "Must specify binding flags describing the invoke operation required." - throw new ArgumentException(Environment.GetResourceString("Arg_NoAccessSpec"),"bindingFlags"); - - // Provide a default binding mask if none is provided - if ((bindingFlags & MemberBindingMask) == 0) - { - bindingFlags |= BindingFlags.Instance | BindingFlags.Public; - - if ((bindingFlags & BindingFlags.CreateInstance) == 0) - bindingFlags |= BindingFlags.Static; - } - - // There must not be more named parameters than provided arguments - if (namedParams != null) - { - if (providedArgs != null) - { - if (namedParams.Length > providedArgs.Length) - // "Named parameter array can not be bigger than argument array." - throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamTooBig"), "namedParams"); - } - else - { - if (namedParams.Length != 0) - // "Named parameter array can not be bigger than argument array." - throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamTooBig"), "namedParams"); - } - } - #endregion - - #region Check that any named paramters are not null - if (namedParams != null && Array.IndexOf(namedParams, null) != -1) - // "Named parameter value must not be null." - throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamNull"),"namedParams"); - #endregion - - int argCnt = (providedArgs != null) ? providedArgs.Length : 0; - - #region Get a Binder - if (binder == null) - binder = DefaultBinder; - - #endregion - - #region Delegate to Activator.CreateInstance - if ((bindingFlags & BindingFlags.CreateInstance) != 0) - { - if ((bindingFlags & BindingFlags.CreateInstance) != 0 && (bindingFlags & BinderNonCreateInstance) != 0) - // "Can not specify both CreateInstance and another access type." - throw new ArgumentException(Environment.GetResourceString("Arg_CreatInstAccess"),"bindingFlags"); - - return Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture); - } - #endregion - - // PutDispProperty and\or PutRefDispProperty ==> SetProperty. - if ((bindingFlags & (BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) != 0) - bindingFlags |= BindingFlags.SetProperty; - - #region Name - if (name == null) - throw new ArgumentNullException("name"); - - if (name.Length == 0 || name.Equals(@"[DISPID=0]")) - { - name = GetDefaultMemberName(); - - if (name == null) - { - // in InvokeMember we always pretend there is a default member if none is provided and we make it ToString - name = "ToString"; - } - } - #endregion - - #region GetField or SetField - bool IsGetField = (bindingFlags & BindingFlags.GetField) != 0; - bool IsSetField = (bindingFlags & BindingFlags.SetField) != 0; - - if (IsGetField || IsSetField) - { - #region Preconditions - if (IsGetField) - { - if (IsSetField) - // "Can not specify both Get and Set on a field." - throw new ArgumentException(Environment.GetResourceString("Arg_FldSetGet"),"bindingFlags"); - - if ((bindingFlags & BindingFlags.SetProperty) != 0) - // "Can not specify both GetField and SetProperty." - throw new ArgumentException(Environment.GetResourceString("Arg_FldGetPropSet"),"bindingFlags"); - } - else - { - Contract.Assert(IsSetField); - - if (providedArgs == null) - throw new ArgumentNullException("providedArgs"); - - if ((bindingFlags & BindingFlags.GetProperty) != 0) - // "Can not specify both SetField and GetProperty." - throw new ArgumentException(Environment.GetResourceString("Arg_FldSetPropGet"),"bindingFlags"); - - if ((bindingFlags & BindingFlags.InvokeMethod) != 0) - // "Can not specify Set on a Field and Invoke on a method." - throw new ArgumentException(Environment.GetResourceString("Arg_FldSetInvoke"),"bindingFlags"); - } - #endregion - - #region Lookup Field - FieldInfo selFld = null; - FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[]; - - Contract.Assert(flds != null); - - if (flds.Length == 1) - { - selFld = flds[0]; - } - else if (flds.Length > 0) - { - selFld = binder.BindToField(bindingFlags, flds, IsGetField ? Empty.Value : providedArgs[0], culture); - } - #endregion - - if (selFld != null) - { - #region Invocation on a field - if (selFld.FieldType.IsArray || Object.ReferenceEquals(selFld.FieldType, typeof(System.Array))) - { - #region Invocation of an array Field - int idxCnt; - - if ((bindingFlags & BindingFlags.GetField) != 0) - { - idxCnt = argCnt; - } - else - { - idxCnt = argCnt - 1; - } - - if (idxCnt > 0) - { - // Verify that all of the index values are ints - int[] idx = new int[idxCnt]; - for (int i=0;i<idxCnt;i++) - { - try - { - idx[i] = ((IConvertible)providedArgs[i]).ToInt32(null); - } - catch (InvalidCastException) - { - throw new ArgumentException(Environment.GetResourceString("Arg_IndexMustBeInt")); - } - } - - // Set or get the value... - Array a = (Array) selFld.GetValue(target); - - // Set or get the value in the array - if ((bindingFlags & BindingFlags.GetField) != 0) - { - return a.GetValue(idx); - } - else - { - a.SetValue(providedArgs[idxCnt],idx); - return null; - } - } - #endregion - } - - if (IsGetField) - { - #region Get the field value - if (argCnt != 0) - throw new ArgumentException(Environment.GetResourceString("Arg_FldGetArgErr"),"bindingFlags"); - - return selFld.GetValue(target); - #endregion - } - else - { - #region Set the field Value - if (argCnt != 1) - throw new ArgumentException(Environment.GetResourceString("Arg_FldSetArgErr"),"bindingFlags"); - - selFld.SetValue(target,providedArgs[0],bindingFlags,binder,culture); - - return null; - #endregion - } - #endregion - } - - if ((bindingFlags & BinderNonFieldGetSet) == 0) - throw new MissingFieldException(FullName, name); - } - #endregion - - #region Caching Logic - /* - bool useCache = false; - - // Note that when we add something to the cache, we are careful to ensure - // that the actual providedArgs matches the parameters of the method. Otherwise, - // some default argument processing has occurred. We don't want anyone - // else with the same (insufficient) number of actual arguments to get a - // cache hit because then they would bypass the default argument processing - // and the invocation would fail. - if (bDefaultBinder && namedParams == null && argCnt < 6) - useCache = true; - - if (useCache) - { - MethodBase invokeMethod = GetMethodFromCache (name, bindingFlags, argCnt, providedArgs); - - if (invokeMethod != null) - return ((MethodInfo) invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture); - } - */ - #endregion - - #region Property PreConditions - // @Legacy - This is RTM behavior - bool isGetProperty = (bindingFlags & BindingFlags.GetProperty) != 0; - bool isSetProperty = (bindingFlags & BindingFlags.SetProperty) != 0; - - if (isGetProperty || isSetProperty) - { - #region Preconditions - if (isGetProperty) - { - Contract.Assert(!IsSetField); - - if (isSetProperty) - throw new ArgumentException(Environment.GetResourceString("Arg_PropSetGet"), "bindingFlags"); - } - else - { - Contract.Assert(isSetProperty); - - Contract.Assert(!IsGetField); - - if ((bindingFlags & BindingFlags.InvokeMethod) != 0) - throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), "bindingFlags"); - } - #endregion - } - #endregion - - MethodInfo[] finalists = null; - MethodInfo finalist = null; - - #region BindingFlags.InvokeMethod - if ((bindingFlags & BindingFlags.InvokeMethod) != 0) - { - #region Lookup Methods - MethodInfo[] semiFinalists = GetMember(name, MemberTypes.Method, bindingFlags) as MethodInfo[]; - List<MethodInfo> results = null; - - for(int i = 0; i < semiFinalists.Length; i ++) - { - MethodInfo semiFinalist = semiFinalists[i]; - Contract.Assert(semiFinalist != null); - - if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt])) - continue; - - if (finalist == null) - { - finalist = semiFinalist; - } - else - { - if (results == null) - { - results = new List<MethodInfo>(semiFinalists.Length); - results.Add(finalist); - } - - results.Add(semiFinalist); - } - } - - if (results != null) - { - Contract.Assert(results.Count > 1); - finalists = new MethodInfo[results.Count]; - results.CopyTo(finalists); - } - #endregion - } - #endregion - - Contract.Assert(finalists == null || finalist != null); - - #region BindingFlags.GetProperty or BindingFlags.SetProperty - if (finalist == null && isGetProperty || isSetProperty) - { - #region Lookup Property - PropertyInfo[] semiFinalists = GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[]; - List<MethodInfo> results = null; - - for(int i = 0; i < semiFinalists.Length; i ++) - { - MethodInfo semiFinalist = null; - - if (isSetProperty) - { - semiFinalist = semiFinalists[i].GetSetMethod(true); - } - else - { - semiFinalist = semiFinalists[i].GetGetMethod(true); - } - - if (semiFinalist == null) - continue; - - if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt])) - continue; - - if (finalist == null) - { - finalist = semiFinalist; - } - else - { - if (results == null) - { - results = new List<MethodInfo>(semiFinalists.Length); - results.Add(finalist); - } - - results.Add(semiFinalist); - } - } - - if (results != null) - { - Contract.Assert(results.Count > 1); - finalists = new MethodInfo[results.Count]; - results.CopyTo(finalists); - } - #endregion - } - #endregion - - if (finalist != null) - { - #region Invoke - if (finalists == null && - argCnt == 0 && - finalist.GetParametersNoCopy().Length == 0 && - (bindingFlags & BindingFlags.OptionalParamBinding) == 0) - { - //if (useCache && argCnt == props[0].GetParameters().Length) - // AddMethodToCache(name, bindingFlags, argCnt, providedArgs, props[0]); - - return finalist.Invoke(target, bindingFlags, binder, providedArgs, culture); - } - - if (finalists == null) - finalists = new MethodInfo[] { finalist }; - - if (providedArgs == null) - providedArgs = Array.Empty<Object>(); - - Object state = null; - - - MethodBase invokeMethod = null; - - try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs, modifiers, culture, namedParams, out state); } - catch(MissingMethodException) { } - - if (invokeMethod == null) - throw new MissingMethodException(FullName, name); - - //if (useCache && argCnt == invokeMethod.GetParameters().Length) - // AddMethodToCache(name, bindingFlags, argCnt, providedArgs, invokeMethod); - - Object result = ((MethodInfo)invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture); - - if (state != null) - binder.ReorderArgumentArray(ref providedArgs, state); - - return result; - #endregion - } - - throw new MissingMethodException(FullName, name); - } - #endregion - - public static bool operator ==(RuntimeType left, RuntimeType right) - { - return object.ReferenceEquals(left, right); - } - - public static bool operator !=(RuntimeType left, RuntimeType right) - { - return !object.ReferenceEquals(left, right); - } - - #region Legacy Internal - private void CreateInstanceCheckThis() - { - if (ContainsGenericParameters) - throw new ArgumentException( - Environment.GetResourceString("Acc_CreateGenericEx", this)); - Contract.EndContractBlock(); - - Type elementType = this.GetRootElementType(); - - if (Object.ReferenceEquals(elementType, typeof(ArgIterator))) - throw new NotSupportedException(Environment.GetResourceString("Acc_CreateArgIterator")); - - if (Object.ReferenceEquals(elementType, typeof(void))) - throw new NotSupportedException(Environment.GetResourceString("Acc_CreateVoid")); - } - - internal Object CreateInstanceImpl( - BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) - { - CreateInstanceCheckThis(); - - Object server = null; - - try - { - try - { - if (args == null) - args = Array.Empty<Object> (); - - int argCnt = args.Length; - - // Without a binder we need to do use the default binder... - if (binder == null) - binder = DefaultBinder; - - // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors - // so a call to GetMemberCons would fail - bool publicOnly = (bindingAttr & BindingFlags.NonPublic) == 0; - bool wrapExceptions = (bindingAttr & BindingFlags.DoNotWrapExceptions) == 0; - if (argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0 - && (IsValueType)) - { - server = CreateInstanceDefaultCtor(publicOnly, false, true, wrapExceptions); - } - else - { - ConstructorInfo[] candidates = GetConstructors(bindingAttr); - List<MethodBase> matches = new List<MethodBase>(candidates.Length); - - // We cannot use Type.GetTypeArray here because some of the args might be null - Type[] argsType = new Type[argCnt]; - for (int i = 0; i < argCnt; i++) - { - if (args[i] != null) - { - argsType[i] = args[i].GetType(); - } - } - - for(int i = 0; i < candidates.Length; i ++) - { - if (FilterApplyConstructorInfo((RuntimeConstructorInfo)candidates[i], bindingAttr, CallingConventions.Any, argsType)) - matches.Add(candidates[i]); - } - - MethodBase[] cons = new MethodBase[matches.Count]; - matches.CopyTo(cons); - if (cons != null && cons.Length == 0) - cons = null; - - if (cons == null) - { - throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName)); - } - - MethodBase invokeMethod; - Object state = null; - - try - { - invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args, null, culture, null, out state); - } - catch (MissingMethodException) { invokeMethod = null; } - - if (invokeMethod == null) - { - throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName)); - } - - if (invokeMethod.GetParametersNoCopy().Length == 0) - { - if (args.Length != 0) - { - - Contract.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) == - CallingConventions.VarArgs); - throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, - Environment.GetResourceString("NotSupported_CallToVarArg"))); - } - - // fast path?? - server = Activator.CreateInstance(this, nonPublic: true, wrapExceptions: wrapExceptions); - } - else - { - server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture); - if (state != null) - binder.ReorderArgumentArray(ref args, state); - } - } - } - finally - { - } - } - catch (Exception) - { - throw; - } - - //Console.WriteLine(server); - return server; - } - - // Helper to invoke the default (parameterless) ctor. - // fillCache is set in the SL2/3 compat mode or when called from Marshal.PtrToStructure. - [DebuggerStepThroughAttribute] - [Diagnostics.DebuggerHidden] - internal Object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, bool wrapExceptions) - { - if (IsByRefLike) - throw new NotSupportedException (SR.NotSupported_ByRefLike); - - return CreateInstanceSlow(publicOnly, wrapExceptions, skipCheckThis, fillCache); - } - - #endregion - - TypeCache cache; - - internal TypeCache Cache { - get { - if (cache == null) - LazyInitializer.EnsureInitialized (ref cache, () => new TypeCache ()); - - return cache; - } - } - - internal sealed class TypeCache - { - public Enum.EnumInfo EnumInfo; - public TypeCode TypeCode; - // this is the displayed form: special characters - // ,+*&*[]\ in the identifier portions of the names - // have been escaped with a leading backslash (\) - public string full_name; - public bool default_ctor_cached; - public RuntimeConstructorInfo default_ctor; - } - - - internal RuntimeType (Object obj) - { - throw new NotImplementedException (); - } - - internal RuntimeConstructorInfo GetDefaultConstructor () - { - var cache = Cache; - RuntimeConstructorInfo ctor = null; - - if (Volatile.Read (ref cache.default_ctor_cached)) - return cache.default_ctor; - - var ctors = GetConstructorCandidates ( - null, - BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly, CallingConventions.Any, - Array.Empty<Type> (), false); - - if (ctors.Count == 1) - cache.default_ctor = ctor = (RuntimeConstructorInfo) ctors [0]; - - // Note down even if we found no constructors - Volatile.Write (ref cache.default_ctor_cached, true); - - return ctor; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern MethodInfo GetCorrespondingInflatedMethod (MethodInfo generic); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern ConstructorInfo GetCorrespondingInflatedConstructor (ConstructorInfo generic); - - internal override MethodInfo GetMethod (MethodInfo fromNoninstanciated) - { - if (fromNoninstanciated == null) - throw new ArgumentNullException ("fromNoninstanciated"); - return GetCorrespondingInflatedMethod (fromNoninstanciated); - } - - internal override ConstructorInfo GetConstructor (ConstructorInfo fromNoninstanciated) - { - if (fromNoninstanciated == null) - throw new ArgumentNullException ("fromNoninstanciated"); - return GetCorrespondingInflatedConstructor (fromNoninstanciated); - } - - internal override FieldInfo GetField (FieldInfo fromNoninstanciated) - { - /* create sensible flags from given FieldInfo */ - BindingFlags flags = fromNoninstanciated.IsStatic ? BindingFlags.Static : BindingFlags.Instance; - flags |= fromNoninstanciated.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic; - return GetField (fromNoninstanciated.Name, flags); - } - - string GetDefaultMemberName () - { - object [] att = GetCustomAttributes (typeof (DefaultMemberAttribute), true); - return att.Length != 0 ? ((DefaultMemberAttribute) att [0]).MemberName : null; - } - - RuntimeConstructorInfo m_serializationCtor; - internal RuntimeConstructorInfo GetSerializationCtor() - { - if (m_serializationCtor == null) { - var s_SICtorParamTypes = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; - - m_serializationCtor = GetConstructor( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - null, - CallingConventions.Any, - s_SICtorParamTypes, - null) as RuntimeConstructorInfo; - } - - return m_serializationCtor; - } - - internal Object CreateInstanceSlow(bool publicOnly, bool wrapExceptions, bool skipCheckThis, bool fillCache) - { - //bool bNeedSecurityCheck = true; - //bool bCanBeCached = false; - //bool bSecurityCheckOff = false; - - if (!skipCheckThis) - CreateInstanceCheckThis(); - - //if (!fillCache) - // bSecurityCheckOff = true; - - return CreateInstanceMono (!publicOnly, wrapExceptions); - } - - object CreateInstanceMono (bool nonPublic, bool wrapExceptions) - { - var ctor = GetDefaultConstructor (); - if (!nonPublic && ctor != null && !ctor.IsPublic) { - throw new MissingMethodException(SR.Format(SR.Arg_NoDefCTor, FullName)); - } - - if (ctor == null) { - Type elementType = this.GetRootElementType(); - if (ReferenceEquals (elementType, typeof (TypedReference)) || ReferenceEquals (elementType, typeof (RuntimeArgumentHandle))) - throw new NotSupportedException (Environment.GetResourceString ("NotSupported_ContainsStackPtr")); - - if (IsValueType) - return CreateInstanceInternal (this); - - throw new MissingMethodException ("Default constructor not found for type " + FullName); - } - - // TODO: .net does more checks in unmanaged land in RuntimeTypeHandle::CreateInstance - if (IsAbstract) { - throw new MissingMethodException ("Cannot create an abstract class '{0}'.", FullName); - } - - return ctor.InternalInvoke (null, null, wrapExceptions); - } - - internal Object CheckValue (Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr) - { - bool failed = false; - var res = TryConvertToType (value, ref failed); - if (!failed) - return res; - - if ((invokeAttr & BindingFlags.ExactBinding) == BindingFlags.ExactBinding) - throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_ObjObjEx"), value.GetType(), this)); - - if (binder != null && binder != Type.DefaultBinder) - return binder.ChangeType (value, this, culture); - - throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_ObjObjEx"), value.GetType(), this)); - } - - object TryConvertToType (object value, ref bool failed) - { - if (IsInstanceOfType (value)) { - return value; - } - - if (IsByRef) { - var elementType = GetElementType (); - if (value == null || elementType.IsInstanceOfType (value)) { - return value; - } - } - - if (value == null) - return value; - - if (IsEnum) { - var type = Enum.GetUnderlyingType (this); - if (type == value.GetType ()) - return value; - var res = IsConvertibleToPrimitiveType (value, this); - if (res != null) - return res; - } else if (IsPrimitive) { - var res = IsConvertibleToPrimitiveType (value, this); - if (res != null) - return res; - } else if (IsPointer) { - var vtype = value.GetType (); - if (vtype == typeof (IntPtr) || vtype == typeof (UIntPtr)) - return value; - if (value is Pointer pointer) { - Type pointerType = pointer.GetPointerType (); - if (pointerType == this) - return pointer.GetPointerValue (); - } - } - - failed = true; - return null; - } - - // Binder uses some incompatible conversion rules. For example - // int value cannot be used with decimal parameter but in other - // ways it's more flexible than normal convertor, for example - // long value can be used with int based enum - static object IsConvertibleToPrimitiveType (object value, Type targetType) - { - var type = value.GetType (); - if (type.IsEnum) { - type = Enum.GetUnderlyingType (type); - if (type == targetType) - return value; - } - - var from = Type.GetTypeCode (type); - var to = Type.GetTypeCode (targetType); - - switch (to) { - case TypeCode.Char: - switch (from) { - case TypeCode.Byte: - return (Char) (Byte) value; - case TypeCode.UInt16: - return value; - } - break; - case TypeCode.Int16: - switch (from) { - case TypeCode.Byte: - return (Int16) (Byte) value; - case TypeCode.SByte: - return (Int16) (SByte) value; - } - break; - case TypeCode.UInt16: - switch (from) { - case TypeCode.Byte: - return (UInt16) (Byte) value; - case TypeCode.Char: - return value; - } - break; - case TypeCode.Int32: - switch (from) { - case TypeCode.Byte: - return (Int32) (Byte) value; - case TypeCode.SByte: - return (Int32) (SByte) value; - case TypeCode.Char: - return (Int32) (Char) value; - case TypeCode.Int16: - return (Int32) (Int16) value; - case TypeCode.UInt16: - return (Int32) (UInt16) value; - } - break; - case TypeCode.UInt32: - switch (from) { - case TypeCode.Byte: - return (UInt32) (Byte) value; - case TypeCode.Char: - return (UInt32) (Char) value; - case TypeCode.UInt16: - return (UInt32) (UInt16) value; - } - break; - case TypeCode.Int64: - switch (from) { - case TypeCode.Byte: - return (Int64) (Byte) value; - case TypeCode.SByte: - return (Int64) (SByte) value; - case TypeCode.Int16: - return (Int64) (Int16) value; - case TypeCode.Char: - return (Int64) (Char) value; - case TypeCode.UInt16: - return (Int64) (UInt16) value; - case TypeCode.Int32: - return (Int64) (Int32) value; - case TypeCode.UInt32: - return (Int64) (UInt32) value; - } - break; - case TypeCode.UInt64: - switch (from) { - case TypeCode.Byte: - return (UInt64) (Byte) value; - case TypeCode.Char: - return (UInt64) (Char) value; - case TypeCode.UInt16: - return (UInt64) (UInt16) value; - case TypeCode.UInt32: - return (UInt64) (UInt32) value; - } - break; - case TypeCode.Single: - switch (from) { - case TypeCode.Byte: - return (Single) (Byte) value; - case TypeCode.SByte: - return (Single) (SByte) value; - case TypeCode.Int16: - return (Single) (Int16) value; - case TypeCode.Char: - return (Single) (Char) value; - case TypeCode.UInt16: - return (Single) (UInt16) value; - case TypeCode.Int32: - return (Single) (Int32) value; - case TypeCode.UInt32: - return (Single) (UInt32) value; - case TypeCode.Int64: - return (Single) (Int64) value; - case TypeCode.UInt64: - return (Single) (UInt64) value; - } - break; - case TypeCode.Double: - switch (from) { - case TypeCode.Byte: - return (Double) (Byte) value; - case TypeCode.SByte: - return (Double) (SByte) value; - case TypeCode.Char: - return (Double) (Char) value; - case TypeCode.Int16: - return (Double) (Int16) value; - case TypeCode.UInt16: - return (Double) (UInt16) value; - case TypeCode.Int32: - return (Double) (Int32) value; - case TypeCode.UInt32: - return (Double) (UInt32) value; - case TypeCode.Int64: - return (Double) (Int64) value; - case TypeCode.UInt64: - return (Double) (UInt64) value; - case TypeCode.Single: - return (Double) (Single) value; - } - break; - } - - // Everything else is rejected - return null; - } - - string GetCachedName (TypeNameKind kind) - { - switch (kind) { - case TypeNameKind.SerializationName: - return ToString (); - default: - throw new NotImplementedException (); - } - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern Type make_array_type (int rank); - - public override Type MakeArrayType () - { - return make_array_type (0); - } - - public override Type MakeArrayType (int rank) - { - if (rank < 1 || rank > 255) - throw new IndexOutOfRangeException (); - return make_array_type (rank); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern Type make_byref_type (); - - public override Type MakeByRefType () - { - if (IsByRef) - throw new TypeLoadException ("Can not call MakeByRefType on a ByRef type"); - return make_byref_type (); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern Type MakePointerType (Type type); - - public override Type MakePointerType () - { - if (IsByRef) - throw new TypeLoadException ($"Could not load type '{GetType()}' from assembly '{AssemblyQualifiedName}"); - return MakePointerType (this); - } - - public override StructLayoutAttribute? StructLayoutAttribute { - get { - return GetStructLayoutAttribute (); - } - } - - public override bool ContainsGenericParameters { - get { - if (IsGenericParameter) - return true; - - if (IsGenericType) { - foreach (Type arg in GetGenericArguments ()) - if (arg.ContainsGenericParameters) - return true; - } - - if (HasElementType) - return GetElementType ().ContainsGenericParameters; - - return false; - } - } - - public override Type[] GetGenericParameterConstraints () - { - if (!IsGenericParameter) - throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter")); - - var paramInfo = new Mono.RuntimeGenericParamInfoHandle (RuntimeTypeHandle.GetGenericParameterInfo (this)); - Type[] constraints = paramInfo.Constraints; - - return constraints ?? Array.Empty<Type> (); - } - - internal static object CreateInstanceForAnotherGenericParameter (Type genericType, RuntimeType genericArgument) - { - var gt = (RuntimeType) MakeGenericType (genericType, new Type [] { genericArgument }); - var ctor = gt.GetDefaultConstructor (); - return ctor.InternalInvoke (null, null, wrapExceptions: true); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern Type MakeGenericType (Type gt, Type [] types); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern IntPtr GetMethodsByName_native (IntPtr namePtr, BindingFlags bindingAttr, MemberListType listType); - - internal RuntimeMethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, MemberListType listType, RuntimeType reflectedType) - { - var refh = new RuntimeTypeHandle (reflectedType); - using (var namePtr = new Mono.SafeStringMarshal (name)) - using (var h = new Mono.SafeGPtrArrayHandle (GetMethodsByName_native (namePtr.Value, bindingAttr, listType))) { - var n = h.Length; - var a = new RuntimeMethodInfo [n]; - for (int i = 0; i < n; i++) { - var mh = new RuntimeMethodHandle (h[i]); - a[i] = (RuntimeMethodInfo) RuntimeMethodInfo.GetMethodFromHandleNoGenericCheck (mh, refh); - } - return a; - } - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern IntPtr GetPropertiesByName_native (IntPtr name, BindingFlags bindingAttr, MemberListType listType); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern IntPtr GetConstructors_native (BindingFlags bindingAttr); - - RuntimeConstructorInfo[] GetConstructors_internal (BindingFlags bindingAttr, RuntimeType reflectedType) - { - var refh = new RuntimeTypeHandle (reflectedType); - using (var h = new Mono.SafeGPtrArrayHandle (GetConstructors_native (bindingAttr))) { - var n = h.Length; - var a = new RuntimeConstructorInfo [n]; - for (int i = 0; i < n; i++) { - var mh = new RuntimeMethodHandle (h[i]); - a[i] = (RuntimeConstructorInfo) RuntimeMethodInfo.GetMethodFromHandleNoGenericCheck (mh, refh); - } - return a; - } - } - - RuntimePropertyInfo[] GetPropertiesByName (string name, BindingFlags bindingAttr, MemberListType listType, RuntimeType reflectedType) - { - var refh = new RuntimeTypeHandle (reflectedType); - using (var namePtr = new Mono.SafeStringMarshal (name)) - using (var h = new Mono.SafeGPtrArrayHandle (GetPropertiesByName_native (namePtr.Value, bindingAttr, listType))) { - var n = h.Length; - var a = new RuntimePropertyInfo [n]; - for (int i = 0; i < n; i++) { - var ph = new Mono.RuntimePropertyHandle (h[i]); - a[i] = (RuntimePropertyInfo) RuntimePropertyInfo.GetPropertyFromHandle (ph, refh); - } - return a; - } - } - - public override InterfaceMapping GetInterfaceMap (Type ifaceType) - { - if (IsGenericParameter) - throw new InvalidOperationException(Environment.GetResourceString("Arg_GenericParameter")); - - if ((object)ifaceType == null) - throw new ArgumentNullException("ifaceType"); - - RuntimeType ifaceRtType = ifaceType as RuntimeType; - - if (ifaceRtType == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "ifaceType"); - - InterfaceMapping res; - if (!ifaceType.IsInterface) - throw new ArgumentException ("Argument must be an interface.", "ifaceType"); - if (IsInterface) - throw new ArgumentException ("'this' type cannot be an interface itself"); - res.TargetType = this; - res.InterfaceType = ifaceType; - GetInterfaceMapData (this, ifaceType, out res.TargetMethods, out res.InterfaceMethods); - if (res.TargetMethods == null) - throw new ArgumentException ("Interface not found", "ifaceType"); - - return res; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - static extern void GetInterfaceMapData (Type t, Type iface, out MethodInfo[] targets, out MethodInfo[] methods); - - public override Guid GUID { - get { - object[] att = GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), true); - if (att.Length == 0) - return Guid.Empty; - return new Guid(((System.Runtime.InteropServices.GuidAttribute)att[0]).Value); - } - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern void GetPacking (out int packing, out int size); - - public override string ToString() - { - return getFullName (false, false); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern object CreateInstanceInternal (Type type); - - public extern override MethodBase? DeclaringMethod { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - get; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern string getFullName(bool full_name, bool assembly_qualified); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern Type[] GetGenericArgumentsInternal (bool runtimeArray); - - GenericParameterAttributes GetGenericParameterAttributes () { - return (new Mono.RuntimeGenericParamInfoHandle (RuntimeTypeHandle.GetGenericParameterInfo (this))).Attributes; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern int GetGenericParameterPosition (); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern IntPtr GetEvents_native (IntPtr name, MemberListType listType); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern IntPtr GetFields_native (IntPtr name, BindingFlags bindingAttr, MemberListType listType); - - RuntimeFieldInfo[] GetFields_internal (string name, BindingFlags bindingAttr, MemberListType listType, RuntimeType reflectedType) - { - var refh = new RuntimeTypeHandle (reflectedType); - using (var namePtr = new Mono.SafeStringMarshal (name)) - using (var h = new Mono.SafeGPtrArrayHandle (GetFields_native (namePtr.Value, bindingAttr, listType))) { - int n = h.Length; - var a = new RuntimeFieldInfo[n]; - for (int i = 0; i < n; i++) { - var fh = new RuntimeFieldHandle (h[i]); - a[i] = (RuntimeFieldInfo) FieldInfo.GetFieldFromHandle (fh, refh); - } - return a; - } - } - - RuntimeEventInfo[] GetEvents_internal (string name, BindingFlags bindingAttr, MemberListType listType, RuntimeType reflectedType) - { - var refh = new RuntimeTypeHandle (reflectedType); - using (var namePtr = new Mono.SafeStringMarshal (name)) - using (var h = new Mono.SafeGPtrArrayHandle (GetEvents_native (namePtr.Value, listType))) { - int n = h.Length; - var a = new RuntimeEventInfo[n]; - for (int i = 0; i < n; i++) { - var eh = new Mono.RuntimeEventHandle (h[i]); - a[i] = (RuntimeEventInfo) RuntimeEventInfo.GetEventFromHandle (eh, refh); - } - return a; - } - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern override Type[] GetInterfaces(); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern IntPtr GetNestedTypes_native (IntPtr name, BindingFlags bindingAttr, MemberListType listType); - - RuntimeType[] GetNestedTypes_internal (string displayName, BindingFlags bindingAttr, MemberListType listType) - { - string internalName = null; - if (displayName != null) - internalName = displayName; - using (var namePtr = new Mono.SafeStringMarshal (internalName)) - using (var h = new Mono.SafeGPtrArrayHandle (GetNestedTypes_native (namePtr.Value, bindingAttr, listType))) { - int n = h.Length; - var a = new RuntimeType [n]; - for (int i = 0; i < n; i++) { - var th = new RuntimeTypeHandle (h[i]); - a[i] = (RuntimeType) Type.GetTypeFromHandle (th); - } - return a; - } - } - - public override string? AssemblyQualifiedName { - get { - return getFullName (true, true); - } - } - - public extern override Type? DeclaringType { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - get; - } - - public extern override string Name { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - get; - } - - public extern override string? Namespace { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - get; - } - - public override string? FullName { - get { - // See https://github.com/mono/mono/issues/18180 and - // https://github.com/dotnet/runtime/blob/f23e2796ab5f6fea71c9fdacac024822280253db/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs#L1468-L1472 - if (ContainsGenericParameters && !GetRootElementType().IsGenericTypeDefinition) - return null; - - string fullName; - var cache = Cache; - if ((fullName = cache.full_name) == null) - fullName = cache.full_name = getFullName (true, false); - - return fullName; - } - } - - public sealed override bool HasSameMetadataDefinitionAs (MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeType> (other); - - public override bool IsSZArray { - get { - return RuntimeTypeHandle.IsSzArray (this); - } - } - - internal override bool IsUserType { - get { - return false; - } - } - - public override bool IsSubclassOf(Type type) - { - if ((object)type == null) - throw new ArgumentNullException("type"); - - RuntimeType rtType = type as RuntimeType; - if (rtType == null) - return false; - - return RuntimeTypeHandle.IsSubclassOf (this, rtType); - } - - private const int DEFAULT_PACKING_SIZE = 8; - - internal StructLayoutAttribute GetStructLayoutAttribute () - { - if (IsInterface || HasElementType || IsGenericParameter) - return null; - - int pack = 0, size = 0; - LayoutKind layoutKind = LayoutKind.Auto; - switch (Attributes & TypeAttributes.LayoutMask) - { - case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break; - case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break; - case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break; - default: break; - } - - CharSet charSet = CharSet.None; - switch (Attributes & TypeAttributes.StringFormatMask) - { - case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break; - case TypeAttributes.AutoClass: charSet = CharSet.Auto; break; - case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break; - default: break; - } - - GetPacking (out pack, out size); - - // Metadata parameter checking should not have allowed 0 for packing size. - // The runtime later converts a packing size of 0 to 8 so do the same here - // because it's more useful from a user perspective. - if (pack == 0) - pack = DEFAULT_PACKING_SIZE; - - return new StructLayoutAttribute (layoutKind) { Pack = pack, Size = size, CharSet = charSet }; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs b/netcore/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs deleted file mode 100644 index f0c194d3898..00000000000 --- a/netcore/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs +++ /dev/null @@ -1,332 +0,0 @@ -// -// Authors: -// Miguel de Icaza (miguel@ximian.com) -// Andreas Nahr (ClassDevelopment@A-SoftTech.com) -// -// (C) Ximian, Inc. http://www.ximian.com -// -// -// Copyright (C) 2004 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System.Runtime.Serialization; -using System.Runtime.CompilerServices; -using System.Reflection; -using System.Threading; - -namespace System -{ - [Serializable] - public struct RuntimeTypeHandle : ISerializable - { - readonly IntPtr value; - - internal RuntimeTypeHandle (IntPtr val) - { - value = val; - } - - internal RuntimeTypeHandle (RuntimeType type) - : this (type._impl.value) - { - } - - RuntimeTypeHandle (SerializationInfo info, StreamingContext context) - { - throw new PlatformNotSupportedException (); - } - - public IntPtr Value { - get { - return value; - } - } - - public void GetObjectData (SerializationInfo info, StreamingContext context) - { - throw new PlatformNotSupportedException (); - } - - public override bool Equals (object? obj) - { - if (obj == null || GetType () != obj.GetType ()) - return false; - - return value == ((RuntimeTypeHandle)obj).Value; - } - - public bool Equals (RuntimeTypeHandle handle) - { - return value == handle.Value; - } - - public override int GetHashCode () - { - return value.GetHashCode (); - } - - public static bool operator == (RuntimeTypeHandle left, Object right) - { - return (right != null) && (right is RuntimeTypeHandle) && left.Equals ((RuntimeTypeHandle)right); - } - - public static bool operator != (RuntimeTypeHandle left, Object right) - { - return (right == null) || !(right is RuntimeTypeHandle) || !left.Equals ((RuntimeTypeHandle)right); - } - - public static bool operator == (Object left, RuntimeTypeHandle right) - { - return (left != null) && (left is RuntimeTypeHandle) && ((RuntimeTypeHandle)left).Equals (right); - } - - public static bool operator != (Object left, RuntimeTypeHandle right) - { - return (left == null) || !(left is RuntimeTypeHandle) || !((RuntimeTypeHandle)left).Equals (right); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern TypeAttributes GetAttributes (RuntimeType type); - - [CLSCompliant (false)] - public ModuleHandle GetModuleHandle () - { - // Although MS' runtime is crashing here, we prefer throwing an exception. - // The check is needed because Type.GetTypeFromHandle returns null - // for zero handles. - if (value == IntPtr.Zero) - throw new InvalidOperationException ("Object fields may not be properly initialized"); - - return Type.GetTypeFromHandle (this).Module.ModuleHandle; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern int GetMetadataToken (RuntimeType type); - - internal static int GetToken (RuntimeType type) - { - return GetMetadataToken (type); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static Type GetGenericTypeDefinition_impl (RuntimeType type); - - internal static Type GetGenericTypeDefinition (RuntimeType type) - { - return GetGenericTypeDefinition_impl (type); - } - - internal static bool IsPrimitive (RuntimeType type) - { - CorElementType corElemType = GetCorElementType (type); - return (corElemType >= CorElementType.ELEMENT_TYPE_BOOLEAN && corElemType <= CorElementType.ELEMENT_TYPE_R8) || - corElemType == CorElementType.ELEMENT_TYPE_I || - corElemType == CorElementType.ELEMENT_TYPE_U; - } - - internal static bool IsByRef (RuntimeType type) - { - CorElementType corElemType = GetCorElementType (type); - return corElemType == CorElementType.ELEMENT_TYPE_BYREF; - } - - internal static bool IsPointer (RuntimeType type) - { - CorElementType corElemType = GetCorElementType (type); - return corElemType == CorElementType.ELEMENT_TYPE_PTR; - } - - internal static bool IsArray (RuntimeType type) - { - CorElementType corElemType = GetCorElementType (type); - return corElemType == CorElementType.ELEMENT_TYPE_ARRAY || corElemType == CorElementType.ELEMENT_TYPE_SZARRAY; - } - - internal static bool IsSzArray (RuntimeType type) - { - CorElementType corElemType = GetCorElementType (type); - return corElemType == CorElementType.ELEMENT_TYPE_SZARRAY; - } - - internal static bool HasElementType (RuntimeType type) - { - CorElementType corElemType = GetCorElementType(type); - - return ((corElemType == CorElementType.ELEMENT_TYPE_ARRAY || corElemType == CorElementType.ELEMENT_TYPE_SZARRAY) // IsArray - || (corElemType == CorElementType.ELEMENT_TYPE_PTR) // IsPointer - || (corElemType == CorElementType.ELEMENT_TYPE_BYREF)); // IsByRef - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal static extern CorElementType GetCorElementType (RuntimeType type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static bool HasInstantiation (RuntimeType type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static bool IsComObject (RuntimeType type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static bool IsInstanceOfType (RuntimeType type, Object o); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static bool HasReferences (RuntimeType type); - - internal static bool IsComObject (RuntimeType type, bool isGenericCOM) - { - return isGenericCOM ? false : IsComObject (type); - } - - internal static bool IsContextful (RuntimeType type) - { - return false; - } - - internal static bool IsEquivalentTo (RuntimeType rtType1, RuntimeType rtType2) - { - // refence check is done earlier and we don't recognize anything else - return false; - } - - internal static bool IsInterface (RuntimeType type) - { - return (type.Attributes & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static int GetArrayRank(RuntimeType type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static RuntimeAssembly GetAssembly (RuntimeType type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static RuntimeType GetElementType (RuntimeType type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static RuntimeModule GetModule (RuntimeType type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static bool IsGenericVariable (RuntimeType type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static RuntimeType GetBaseType (RuntimeType type); - - internal static bool CanCastTo (RuntimeType type, RuntimeType target) - { - return type_is_assignable_from (target, type); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern bool type_is_assignable_from (Type a, Type b); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static bool IsGenericTypeDefinition (RuntimeType type); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static IntPtr GetGenericParameterInfo (RuntimeType type); - - internal static bool IsSubclassOf (RuntimeType childType, RuntimeType baseType) - { - return is_subclass_of (childType._impl.Value, baseType._impl.Value); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static bool is_subclass_of (IntPtr childType, IntPtr baseType); - - [PreserveDependency (".ctor()", "System.Runtime.CompilerServices.IsByRefLikeAttribute")] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static bool IsByRefLike (RuntimeType type); - - internal static bool IsTypeDefinition (RuntimeType type) - { - // That's how it has been done on CoreFX but we have no GetCorElementType method implementation - // see https://github.com/dotnet/coreclr/pull/11355 - - // CorElementType corElemType = GetCorElementType (type); - // if (!((corElemType >= CorElementType.Void && corElemType < CorElementType.Ptr) || - // corElemType == CorElementType.ValueType || - // corElemType == CorElementType.Class || - // corElemType == CorElementType.TypedByRef || - // corElemType == CorElementType.I || - // corElemType == CorElementType.U || - // corElemType == CorElementType.Object)) - // return false; - // if (HasInstantiation (type) && !IsGenericTypeDefinition (type)) - // return false; - // return true; - - // It's like a workaround mentioned in https://github.com/dotnet/corefx/issues/17345 - return !type.HasElementType && !type.IsConstructedGenericType && !type.IsGenericParameter; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern RuntimeType internal_from_name (string name, ref StackCrawlMark stackMark, Assembly callerAssembly, bool throwOnError, bool ignoreCase, bool reflectionOnly); - - internal static RuntimeType GetTypeByName (string typeName, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark, - bool loadTypeFromPartialName) - { - if (typeName == null) - throw new ArgumentNullException ("typeName"); - - if (typeName == String.Empty) - if (throwOnError) - throw new TypeLoadException ("A null or zero length string does not represent a valid Type."); - else - return null; - - if (reflectionOnly) { - int idx = typeName.IndexOf (','); - if (idx < 0 || idx == 0 || idx == typeName.Length - 1) - throw new ArgumentException ("Assembly qualifed type name is required", "typeName"); - string an = typeName.Substring (idx + 1); - Assembly a; - try { - a = Assembly.ReflectionOnlyLoad (an); - } catch { - if (throwOnError) - throw; - return null; - } - return (RuntimeType)a.GetType (typeName.Substring (0, idx), throwOnError, ignoreCase); - } - - var t = internal_from_name (typeName, ref stackMark, null, throwOnError, ignoreCase, false); - if (throwOnError && t == null) - throw new TypeLoadException ("Error loading '" + typeName + "'"); - return t; - } - - internal static IntPtr[] CopyRuntimeTypeHandles (RuntimeTypeHandle[] inHandles, out int length) - { - if (inHandles == null || inHandles.Length == 0) { - length = 0; - return null; - } - - IntPtr[] outHandles = new IntPtr [inHandles.Length]; - for (int i = 0; i < inHandles.Length; i++) - outHandles [i] = inHandles [i].Value; - length = outHandles.Length; - return outHandles; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Security/DynamicSecurityMethodAttribute.cs b/netcore/System.Private.CoreLib/src/System/Security/DynamicSecurityMethodAttribute.cs deleted file mode 100644 index 83be902a2c5..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Security/DynamicSecurityMethodAttribute.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -namespace System.Security -{ - // DynamicSecurityMethodAttribute: - // All methods that use StackCrawlMark should be marked with this attribute. This attribute - // disables inlining of the calling method to allow stackwalking to find the exact caller. - // - // This attribute used to indicate that the target method requires space for a security object - // to be allocated on the callers stack. It is not used for this purpose anymore because of security - // stackwalks are not ever done in CoreCLR. - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] - internal sealed class DynamicSecurityMethodAttribute : Attribute - { - public DynamicSecurityMethodAttribute() { } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/String.Mono.cs b/netcore/System.Private.CoreLib/src/System/String.Mono.cs deleted file mode 100644 index c103a1e8ac0..00000000000 --- a/netcore/System.Private.CoreLib/src/System/String.Mono.cs +++ /dev/null @@ -1,144 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; -using Internal.Runtime.CompilerServices; - -namespace System -{ - partial class String - { - [Intrinsic] - public static readonly String Empty; - - public int Length { - [Intrinsic] - get => _stringLength; - } - - [IndexerName ("Chars")] - public char this [int index] { - [Intrinsic] - get => this [index]; - } - - public static String Intern (String str) - { - if (str == null) - throw new ArgumentNullException(nameof(str)); - - return InternalIntern (str); - } - - public static String IsInterned (String str) - { - if (str == null) - throw new ArgumentNullException(nameof(str)); - - return InternalIsInterned (str); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static String FastAllocateString (int length); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static String InternalIsInterned (String str); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static String InternalIntern (String str); - - // TODO: Should be pointing to Buffer instead - #region Runtime method-to-ir dependencies - - static unsafe void memset (byte *dest, int val, int len) - { - if (len < 8) { - while (len != 0) { - *dest = (byte)val; - ++dest; - --len; - } - return; - } - if (val != 0) { - val = val | (val << 8); - val = val | (val << 16); - } - // align to 4 - int rest = (int)dest & 3; - if (rest != 0) { - rest = 4 - rest; - len -= rest; - do { - *dest = (byte)val; - ++dest; - --rest; - } while (rest != 0); - } - while (len >= 16) { - ((int*)dest) [0] = val; - ((int*)dest) [1] = val; - ((int*)dest) [2] = val; - ((int*)dest) [3] = val; - dest += 16; - len -= 16; - } - while (len >= 4) { - ((int*)dest) [0] = val; - dest += 4; - len -= 4; - } - // tail bytes - while (len > 0) { - *dest = (byte)val; - dest++; - len--; - } - } - - static unsafe void memcpy (byte *dest, byte *src, int size) - { - Buffer.Memcpy (dest, src, size); - } - - /* Used by the runtime */ - internal static unsafe void bzero (byte *dest, int len) { - memset (dest, 0, len); - } - - internal static unsafe void bzero_aligned_1 (byte *dest, int len) { - ((byte*)dest) [0] = 0; - } - - internal static unsafe void bzero_aligned_2 (byte *dest, int len) { - ((short*)dest) [0] = 0; - } - - internal static unsafe void bzero_aligned_4 (byte *dest, int len) { - ((int*)dest) [0] = 0; - } - - internal static unsafe void bzero_aligned_8 (byte *dest, int len) { - ((long*)dest) [0] = 0; - } - - internal static unsafe void memcpy_aligned_1 (byte *dest, byte *src, int size) { - ((byte*)dest) [0] = ((byte*)src) [0]; - } - - internal static unsafe void memcpy_aligned_2 (byte *dest, byte *src, int size) { - ((short*)dest) [0] = ((short*)src) [0]; - } - - internal static unsafe void memcpy_aligned_4 (byte *dest, byte *src, int size) { - ((int*)dest) [0] = ((int*)src) [0]; - } - - internal static unsafe void memcpy_aligned_8 (byte *dest, byte *src, int size) { - ((long*)dest) [0] = ((long*)src) [0]; - } - - #endregion - } -}
\ No newline at end of file diff --git a/netcore/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.Mono.cs b/netcore/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.Mono.cs deleted file mode 100644 index 5318ecbfbda..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.Mono.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Win32.SafeHandles; -using System.Runtime.CompilerServices; - -namespace System.Threading -{ - partial class EventWaitHandle - { - public bool Set () - { - SafeWaitHandle handle = ValidateHandle (out bool release); - - try { - return SetEventInternal (handle.DangerousGetHandle ()); - } finally { - if (release) - handle.DangerousRelease (); - } - } - - public bool Reset () - { - SafeWaitHandle handle = ValidateHandle (out bool release); - - try { - return ResetEventInternal (handle.DangerousGetHandle ()); - } finally { - if (release) - handle.DangerousRelease (); - } - } - - unsafe void CreateEventCore (bool initialState, EventResetMode mode, string name, out bool createdNew) - { - if (name != null) - throw new PlatformNotSupportedException (SR.PlatformNotSupported_NamedSynchronizationPrimitives); - - SafeWaitHandle handle = new SafeWaitHandle (CreateEventInternal (mode == EventResetMode.ManualReset, initialState, null, 0, out int errorCode), ownsHandle: true); - if (errorCode != 0) - throw new NotImplementedException ("errorCode"); - SafeWaitHandle = handle; - - createdNew = true; - } - - static OpenExistingResult OpenExistingWorker (string name, out EventWaitHandle result) - { - throw new PlatformNotSupportedException (SR.PlatformNotSupported_NamedSynchronizationPrimitives); - } - - internal static bool Set (SafeWaitHandle waitHandle) - { - bool release = false; - try { - waitHandle.DangerousAddRef (ref release); - return SetEventInternal (waitHandle.DangerousGetHandle ()); - } finally { - if (release) - waitHandle.DangerousRelease (); - } - } - - SafeWaitHandle ValidateHandle (out bool success) - { - // The field value is modifiable via the public <see cref="WaitHandle.SafeWaitHandle"/> property, save it locally - // to ensure that one instance is used in all places in this method - SafeWaitHandle waitHandle = SafeWaitHandle; - if (waitHandle.IsInvalid) - { - throw new InvalidOperationException (); - } - - success = false; - waitHandle.DangerousAddRef (ref success); - return waitHandle; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - unsafe static extern IntPtr CreateEventInternal (bool manual, bool initialState, char *name, int name_length, out int errorCode); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern bool ResetEventInternal (IntPtr handle); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern bool SetEventInternal (IntPtr handle); - - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/Interlocked.cs b/netcore/System.Private.CoreLib/src/System/Threading/Interlocked.cs deleted file mode 100644 index cbc041c7d35..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/Interlocked.cs +++ /dev/null @@ -1,165 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; -using Internal.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; - -namespace System.Threading -{ - public static class Interlocked - { - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static int CompareExchange (ref int location1, int value, int comparand); - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void CompareExchange (ref object location1, ref object value, ref object comparand, ref object result); - - [Intrinsic] - public static object CompareExchange (ref object location1, object value, object comparand) - { - // This avoids coop handles, esp. on the output which would be particularly inefficient. - // Passing everything by ref is equivalent to coop handles -- ref to locals at least. - // - // location1's treatment is unclear. But note that passing it by handle would be incorrect, - // as it would use a local alias, which the coop marshaling does, to avoid the unclarity here, - // that of a ref being to a managed frame vs. a native frame. Perhaps that could be revisited. - // - // So there a hole here, that of calling this function with location1 being in a native frame. - // Usually it will be to a field, static or not, and not even to managed stack. - // - // This is usually intrinsified. Ideally it is always intrinisified. - // - object result = null; - CompareExchange (ref location1, ref value, ref comparand, ref result); - return result; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern static float CompareExchange (ref float location1, float value, float comparand); - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static int Decrement (ref int location); - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static long Decrement (ref long location); - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static int Increment (ref int location); - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static long Increment (ref long location); - - [Intrinsic] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern static int Exchange (ref int location1, int value); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static void Exchange (ref object location1, ref object value, ref object result); - - public static object Exchange (ref object location1, object value) - { - // See CompareExchange(object) for comments. - object result = null; - Exchange (ref location1, ref value, ref result); - return result; - } - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static float Exchange (ref float location1, float value); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern static long CompareExchange (ref long location1, long value, long comparand); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern static IntPtr CompareExchange (ref IntPtr location1, IntPtr value, IntPtr comparand); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern static double CompareExchange (ref double location1, double value, double comparand); - - [return: NotNullIfNotNull("location1")] - [Intrinsic] - public static T CompareExchange<T> (ref T location1, T value, T comparand) where T : class? - { - unsafe { - if (Unsafe.AsPointer (ref location1) == null) - throw new NullReferenceException (); - } - // Besides avoiding coop handles for efficiency, - // and correctness, this also appears needed to - // avoid an assertion failure in the runtime, related to - // coop handles over generics. - // - // See CompareExchange(object) for comments. - // - // This is not entirely convincing due to lack of volatile. - // -#pragma warning disable 8654 // null problems; is there another way? - T result = null; -#pragma warning restore 8654 - // T : class so call the object overload. - CompareExchange (ref Unsafe.As<T, object?> (ref location1), ref Unsafe.As<T, object?>(ref value), ref Unsafe.As<T, object?>(ref comparand), ref Unsafe.As<T, object?>(ref result)); - return result; - } - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static long Exchange (ref long location1, long value); - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static IntPtr Exchange (ref IntPtr location1, IntPtr value); - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static double Exchange (ref double location1, double value); - - [return: NotNullIfNotNull("location1")] - [Intrinsic] - public static T Exchange<T> (ref T location1, T value) where T : class? - { - unsafe { - if (Unsafe.AsPointer (ref location1) == null) - throw new NullReferenceException (); - } - // See CompareExchange(T) for comments. - // - // This is not entirely convincing due to lack of volatile. - // -#pragma warning disable 8654 // null problems; is there another way? - T result = null; -#pragma warning restore 8654 - // T : class so call the object overload. - Exchange (ref Unsafe.As<T,object?>(ref location1), ref Unsafe.As<T, object?>(ref value), ref Unsafe.As<T, object?>(ref result)); - return result; - } - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static long Read (ref long location); - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static int Add (ref int location1, int value); - - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public extern static long Add (ref long location1, long value); - - [Intrinsic] - public static void MemoryBarrier () - { - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern static void MemoryBarrierProcessWide (); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Unix.Mono.cs b/netcore/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Unix.Mono.cs deleted file mode 100644 index b43b6cd4d51..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Unix.Mono.cs +++ /dev/null @@ -1,131 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Internal.Runtime.CompilerServices; - -namespace System.Threading -{ - internal unsafe sealed partial class LowLevelLifoSemaphore : IDisposable - { - struct WaitEntry - { - public object condition; - public bool signaled; - public void* previous; - public void* next; - } - - private object mutex; - private void* head; - private uint pending_signals; - - private void Create (int maximumSignalCount) - { - mutex = new object(); - head = null; - pending_signals = 0; - } - - public void Dispose () - { - } - - private bool WaitCore (int timeoutMs) - { - WaitEntry wait_entry = new WaitEntry (); - bool mutexLocked = false; - bool waitEntryLocked = false; - - try { - Monitor.try_enter_with_atomic_var (mutex, Timeout.Infinite, false, ref mutexLocked); - - if (pending_signals > 0) { - --pending_signals; - return true; - } - - wait_entry.condition = new object(); - wait_entry.previous = null; - wait_entry.next = head; - if (head != null) { - Unsafe.AsRef<WaitEntry> (head).previous = Unsafe.AsPointer<WaitEntry> (ref wait_entry); - } - head = Unsafe.AsPointer<WaitEntry> (ref wait_entry); - } - finally { - if (mutexLocked) { - Monitor.Exit (mutex); - } - } - - try { - Monitor.try_enter_with_atomic_var (wait_entry.condition, Timeout.Infinite, false, ref waitEntryLocked); - if (!wait_entry.signaled) { - Monitor.Monitor_wait (wait_entry.condition, timeoutMs, false); - } - } - finally { - if (waitEntryLocked) - Monitor.Exit (wait_entry.condition); - } - - mutexLocked = false; - try { - Monitor.try_enter_with_atomic_var (mutex, Timeout.Infinite, false, ref mutexLocked); - - if (!wait_entry.signaled) { - if (head == Unsafe.AsPointer<WaitEntry> (ref wait_entry)) { - head = wait_entry.next; - } - if (wait_entry.next != null) { - Unsafe.AsRef<WaitEntry> (wait_entry.next).previous = wait_entry.previous; - } - if (wait_entry.previous != null) { - Unsafe.AsRef<WaitEntry> (wait_entry.previous).next = wait_entry.next; - } - } - } - finally { - if (mutexLocked) { - Monitor.Exit (mutex); - } - } - - return wait_entry.signaled; - } - - private void ReleaseCore (int count) - { - bool mutexLocked = false; - try { - Monitor.try_enter_with_atomic_var (mutex, Timeout.Infinite, false, ref mutexLocked); - while (count > 0) { - if (head != null) { - ref WaitEntry wait_entry = ref Unsafe.AsRef<WaitEntry> (head); - head = wait_entry.next; - if (head != null) { - Unsafe.AsRef<WaitEntry> (head).previous = null; - } - wait_entry.previous = null; - wait_entry.next = null; - lock (wait_entry.condition) - { - wait_entry.signaled = true; - Monitor.Pulse (wait_entry.condition); - } - --count; - } else { - pending_signals += (uint)count; - count = 0; - } - } - } - finally { - if (mutexLocked) { - Monitor.Exit (mutex); - } - } - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/LowLevelLock.cs b/netcore/System.Private.CoreLib/src/System/Threading/LowLevelLock.cs deleted file mode 100644 index d2fc5cfedeb..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/LowLevelLock.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; - -namespace System.Threading -{ - // This class provides implementation of uninterruptible lock for internal - // use by thread pool. - internal class LowLevelLock : IDisposable - { - public void Dispose () - { - } - - public bool TryAcquire() - { - bool lockTaken = false; - Monitor.try_enter_with_atomic_var (this, 0, false, ref lockTaken); - return lockTaken; - } - - public void Acquire() - { - bool lockTaken = false; - Monitor.try_enter_with_atomic_var (this, Timeout.Infinite, false, ref lockTaken); - } - - public void Release() - { - Monitor.Exit (this); - } - - [Conditional("DEBUG")] - public void VerifyIsLocked() - { - Debug.Assert (Monitor.IsEntered (this)); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/LowLevelSpinWaiter.cs b/netcore/System.Private.CoreLib/src/System/Threading/LowLevelSpinWaiter.cs deleted file mode 100644 index f5d52223768..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/LowLevelSpinWaiter.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; - -namespace System.Threading -{ - internal struct LowLevelSpinWaiter - { - public static void Wait (int spinIndex, int sleep0Threshold, int processorCount) - { - Debug.Assert (spinIndex >= 0); - Debug.Assert (sleep0Threshold >= 0); - - // Wait - // - // (spinIndex - Sleep0Threshold) % 2 != 0: The purpose of this check is to interleave Thread.Yield/Sleep(0) with - // Thread.SpinWait. Otherwise, the following issues occur: - // - When there are no threads to switch to, Yield and Sleep(0) become no-op and it turns the spin loop into a - // busy-spin that may quickly reach the max spin count and cause the thread to enter a wait state. Completing the - // spin loop too early can cause excessive context switcing from the wait. - // - If there are multiple threads doing Yield and Sleep(0) (typically from the same spin loop due to contention), - // they may switch between one another, delaying work that can make progress. - if (processorCount > 1 && (spinIndex < sleep0Threshold || (spinIndex - sleep0Threshold) % 2 != 0)) { - // Cap the maximum spin count to a value such that many thousands of CPU cycles would not be wasted doing - // the equivalent of YieldProcessor(), as that that point SwitchToThread/Sleep(0) are more likely to be able to - // allow other useful work to run. Long YieldProcessor() loops can help to reduce contention, but Sleep(1) is - // usually better for that. - // - // Thread.OptimalMaxSpinWaitsPerSpinIteration: - // - See Thread::InitializeYieldProcessorNormalized(), which describes and calculates this value. - // - int n = Thread.OptimalMaxSpinWaitsPerSpinIteration; - if (spinIndex <= 30 && (1 << spinIndex) < n) - { - n = 1 << spinIndex; - } - Thread.SpinWait (n); - return; - } - - // Thread.Sleep(int) is interruptible. The current operation may not allow thread interrupt - // (for instance, LowLevelLock.Acquire as part of EventWaitHandle.Set). Use the - // uninterruptible version of Sleep(0). Not doing Thread.Yield, it does not seem to have any - // benefit over Sleep(0). - Thread.UninterruptibleSleep0 (); - - // Don't want to Sleep(1) in this spin wait: - // - Don't want to spin for that long, since a proper wait will follow when the spin wait fails - // - Sleep(1) would put the thread into a wait state, and a proper wait will follow when the spin wait fails - // anyway (the intended use for this class), so it's preferable to put the thread into the proper wait state - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/Monitor.cs b/netcore/System.Private.CoreLib/src/System/Threading/Monitor.cs deleted file mode 100644 index 5c94a164ca7..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/Monitor.cs +++ /dev/null @@ -1,178 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; - -namespace System.Threading -{ - public static class Monitor - { - [Intrinsic] - [MethodImplAttribute (MethodImplOptions.InternalCall)] // Interpreter is missing this intrinsic - public static void Enter (object obj) => Enter (obj); - - [Intrinsic] - public static void Enter (object obj, ref bool lockTaken) - { - // TODO: Interpreter is missing this intrinsic - if (lockTaken) - throw new ArgumentException (SR.Argument_MustBeFalse, nameof (lockTaken)); - - ReliableEnterTimeout (obj, (int) Timeout.Infinite, ref lockTaken); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - public static extern void Exit (object obj); - - public static bool TryEnter (object obj) - { - bool lockTaken = false; - TryEnter (obj, 0, ref lockTaken); - return lockTaken; - } - - public static void TryEnter (object obj, ref bool lockTaken) - { - if (lockTaken) - throw new ArgumentException (SR.Argument_MustBeFalse, nameof (lockTaken)); - - ReliableEnterTimeout (obj, 0, ref lockTaken); - } - - public static bool TryEnter (object obj, int millisecondsTimeout) - { - bool lockTaken = false; - TryEnter (obj, millisecondsTimeout, ref lockTaken); - return lockTaken; - } - - static int MillisecondsTimeoutFromTimeSpan (TimeSpan timeout) - { - long tm = (long) timeout.TotalMilliseconds; - if (tm < -1 || tm > (long) int.MaxValue) - throw new ArgumentOutOfRangeException (nameof (timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return (int) tm; - } - - public static bool TryEnter (object obj, TimeSpan timeout) - { - return TryEnter (obj, MillisecondsTimeoutFromTimeSpan (timeout)); - } - - public static void TryEnter (object obj, int millisecondsTimeout, ref bool lockTaken) - { - if (lockTaken) - throw new ArgumentException (SR.Argument_MustBeFalse, nameof (lockTaken)); - ReliableEnterTimeout (obj, millisecondsTimeout, ref lockTaken); - } - - public static void TryEnter(object obj, TimeSpan timeout, ref bool lockTaken) - { - if (lockTaken) - throw new ArgumentException (SR.Argument_MustBeFalse, nameof (lockTaken)); - ReliableEnterTimeout (obj, MillisecondsTimeoutFromTimeSpan (timeout), ref lockTaken); - } - - public static bool IsEntered (object obj) - { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - return IsEnteredNative (obj); - } - - public static bool Wait (object obj, int millisecondsTimeout, bool exitContext) - { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - return ObjWait (exitContext, millisecondsTimeout, obj); - } - - public static bool Wait (object obj, TimeSpan timeout, bool exitContext) => Wait (obj, MillisecondsTimeoutFromTimeSpan (timeout), exitContext); - - public static bool Wait (object obj, int millisecondsTimeout) => Wait (obj, millisecondsTimeout, false); - - public static bool Wait(object obj, TimeSpan timeout) => Wait (obj, MillisecondsTimeoutFromTimeSpan (timeout), false); - - public static bool Wait(object obj) => Wait (obj, Timeout.Infinite, false); - - public static void Pulse (object obj) - { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - ObjPulse (obj); - } - - public static void PulseAll (object obj) - { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - ObjPulseAll (obj); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static bool Monitor_test_synchronised (object obj); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void Monitor_pulse (object obj); - - static void ObjPulse (object obj) - { - if (!Monitor_test_synchronised (obj)) - throw new SynchronizationLockException ("Object is not synchronized"); - - Monitor_pulse (obj); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void Monitor_pulse_all (object obj); - - static void ObjPulseAll (object obj) - { - if (!Monitor_test_synchronised (obj)) - throw new SynchronizationLockException ("Object is not synchronized"); - - Monitor_pulse_all (obj); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static bool Monitor_wait (object obj, int ms, bool allowInterruption); - - static bool ObjWait (bool exitContext, int millisecondsTimeout, object obj) - { - if (millisecondsTimeout < 0 && millisecondsTimeout != (int) Timeout.Infinite) - throw new ArgumentOutOfRangeException ("millisecondsTimeout"); - if (!Monitor_test_synchronised (obj)) - throw new SynchronizationLockException ("Object is not synchronized"); - - return Monitor_wait (obj, millisecondsTimeout, true); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - internal extern static void try_enter_with_atomic_var (object obj, int millisecondsTimeout, bool allowInterruption, ref bool lockTaken); - - static void ReliableEnterTimeout (object obj, int timeout, ref bool lockTaken) - { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - - if (timeout < 0 && timeout != (int) Timeout.Infinite) - throw new ArgumentOutOfRangeException (nameof (timeout)); - - try_enter_with_atomic_var (obj, timeout, true, ref lockTaken); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static bool Monitor_test_owner (object obj); - - static bool IsEnteredNative (object obj) - { - return Monitor_test_owner (obj); - } - - public extern static long LockContentionCount { - [MethodImplAttribute (MethodImplOptions.InternalCall)] - get; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/Mutex.Unix.Mono.cs b/netcore/System.Private.CoreLib/src/System/Threading/Mutex.Unix.Mono.cs deleted file mode 100644 index d5065da3547..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/Mutex.Unix.Mono.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; -using System.IO; - -namespace System.Threading -{ - partial class Mutex - { - Mutex (IntPtr handle) => Handle = handle; - - public void ReleaseMutex () - { - if (!ReleaseMutex_internal (Handle)) - throw new ApplicationException (SR.Arg_SynchronizationLockException); - } - - void CreateMutexCore (bool initiallyOwned, string name, out bool createdNew) => - Handle = CreateMutex_internal (initiallyOwned, name, out createdNew); - - unsafe static IntPtr CreateMutex_internal (bool initiallyOwned, string name, out bool created) - { - fixed (char *fixed_name = name) - return CreateMutex_icall (initiallyOwned, fixed_name, - name?.Length ?? 0, out created); - } - - static OpenExistingResult OpenExistingWorker (string name, out Mutex result) - { - if (name == null) - throw new ArgumentNullException (nameof (name)); - - result = null; - if ((name.Length == 0) || - (name.Length > 260)) { - return OpenExistingResult.NameInvalid; - } - - MonoIOError error; - IntPtr handle = OpenMutex_internal (name, out error); - if (handle == IntPtr.Zero) { - if (error == MonoIOError.ERROR_FILE_NOT_FOUND) { - return OpenExistingResult.NameNotFound; - } else if (error == MonoIOError.ERROR_ACCESS_DENIED) { - throw new UnauthorizedAccessException (); - } else { - return OpenExistingResult.PathNotFound; - } - } - - result = new Mutex (handle); - return OpenExistingResult.Success; - } - - unsafe static IntPtr OpenMutex_internal (string name, out MonoIOError error) - { - fixed (char *fixed_name = name) - return OpenMutex_icall (fixed_name, name?.Length ?? 0, 0x000001 /* MutexRights.Modify */, out error); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private unsafe static extern IntPtr CreateMutex_icall (bool initiallyOwned, char *name, int name_length, out bool created); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private unsafe static extern IntPtr OpenMutex_icall (char *name, int name_length, int rights, out MonoIOError error); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern bool ReleaseMutex_internal (IntPtr handle); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/Overlapped.cs b/netcore/System.Private.CoreLib/src/System/Threading/Overlapped.cs deleted file mode 100644 index 321207172d4..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/Overlapped.cs +++ /dev/null @@ -1,320 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Runtime.InteropServices; - -namespace System.Threading -{ - #region class _IOCompletionCallback - - internal unsafe class _IOCompletionCallback - { - private IOCompletionCallback _ioCompletionCallback; - private ExecutionContext _executionContext; - private uint _errorCode; // Error code - private uint _numBytes; // No. of bytes transferred - private NativeOverlapped* _pNativeOverlapped; - - internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ExecutionContext executionContext) - { - _ioCompletionCallback = ioCompletionCallback; - _executionContext = executionContext; - } - - // Context callback: same sig for SendOrPostCallback and ContextCallback - internal static ContextCallback s_ccb = new ContextCallback(IOCompletionCallback_Context); - private static void IOCompletionCallback_Context(object? state) - { - _IOCompletionCallback helper = (_IOCompletionCallback)state!; - Debug.Assert(helper != null, "_IOCompletionCallback cannot be null"); - helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pNativeOverlapped); - } - - //TODO: call from ThreadPool - internal static unsafe void PerformIOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* pNativeOverlapped) - { - do - { - OverlappedData overlapped = OverlappedData.GetOverlappedFromNative(pNativeOverlapped); - - if (overlapped._callback is IOCompletionCallback iocb) - { - // We got here because of UnsafePack (or) Pack with EC flow suppressed - iocb(errorCode, numBytes, pNativeOverlapped); - } - else - { - // We got here because of Pack - var helper = (_IOCompletionCallback)overlapped._callback; - helper._errorCode = errorCode; - helper._numBytes = numBytes; - helper._pNativeOverlapped = pNativeOverlapped; - ExecutionContext.Run(helper._executionContext, s_ccb, helper); - } - - //Quickly check the VM again, to see if a packet has arrived. - //OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes); - pNativeOverlapped = null; - } while (pNativeOverlapped != null); - } - } - - #endregion class _IOCompletionCallback - - #region class OverlappedData - - internal unsafe sealed class OverlappedData - { - internal IAsyncResult _asyncResult; - internal object _callback; // IOCompletionCallback or _IOCompletionCallback - internal Overlapped _overlapped; - private object _userObject; - private NativeOverlapped * _pNativeOverlapped; - private IntPtr _eventHandle; - private int _offsetLow; - private int _offsetHigh; - private GCHandle[] _pinnedData; - - internal ref IAsyncResult AsyncResult => ref _asyncResult; - - internal ref int OffsetLow => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->OffsetLow : ref _offsetLow; - internal ref int OffsetHigh => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->OffsetHigh : ref _offsetHigh; - internal ref IntPtr EventHandle => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->EventHandle : ref _eventHandle; - - internal unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, object userData) - { - if (_pNativeOverlapped != null) - { - throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack); - } - - if (iocb != null) - { - ExecutionContext ec = ExecutionContext.Capture(); - _callback = (ec != null && !ec.IsDefault) ? new _IOCompletionCallback(iocb, ec) : (object)iocb; - } - else - { - _callback = null; - } - _userObject = userData; - return AllocateNativeOverlapped(); - } - - internal unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, object userData) - { - if (_pNativeOverlapped != null) - { - throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack); - } - _userObject = userData; - _callback = iocb; - return AllocateNativeOverlapped(); - } - - private unsafe NativeOverlapped* AllocateNativeOverlapped() - { - Debug.Assert(_pinnedData == null); - - bool success = false; - try - { - if (_userObject != null) - { - if (_userObject.GetType() == typeof(object[])) - { - object[] objArray = (object[])_userObject; - - _pinnedData = new GCHandle[objArray.Length]; - for (int i = 0; i < objArray.Length; i++) - { - _pinnedData[i] = GCHandle.Alloc(objArray[i], GCHandleType.Pinned); - } - } - else - { - _pinnedData = new GCHandle[1]; - _pinnedData[0] = GCHandle.Alloc(_userObject, GCHandleType.Pinned); - } - } - - //CORERT: NativeOverlapped* pNativeOverlapped = (NativeOverlapped*)Interop.MemAlloc((UIntPtr)(sizeof(NativeOverlapped) + sizeof(GCHandle))); - NativeOverlapped* pNativeOverlapped = (NativeOverlapped*) Marshal.AllocHGlobal((IntPtr) (sizeof(NativeOverlapped) + sizeof(GCHandle))); - - *(GCHandle*)(pNativeOverlapped + 1) = default(GCHandle); - _pNativeOverlapped = pNativeOverlapped; - - _pNativeOverlapped->InternalLow = default; - _pNativeOverlapped->InternalHigh = default; - _pNativeOverlapped->OffsetLow = _offsetLow; - _pNativeOverlapped->OffsetHigh = _offsetHigh; - _pNativeOverlapped->EventHandle = _eventHandle; - - *(GCHandle*)(_pNativeOverlapped + 1) = GCHandle.Alloc(this); - - success = true; - return _pNativeOverlapped; - } - finally - { - if (!success) - FreeNativeOverlapped(); - } - } - - internal static unsafe void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr) - { - OverlappedData overlappedData = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr); - overlappedData.FreeNativeOverlapped(); - } - - private void FreeNativeOverlapped() - { - if (_pinnedData != null) - { - for (int i = 0; i < _pinnedData.Length; i++) - { - if (_pinnedData[i].IsAllocated) - { - _pinnedData[i].Free(); - } - } - _pinnedData = null; - } - - if (_pNativeOverlapped != null) - { - GCHandle handle = *(GCHandle*)(_pNativeOverlapped + 1); - if (handle.IsAllocated) - handle.Free(); - - Marshal.FreeHGlobal((IntPtr)_pNativeOverlapped); - //CORERT: Interop.MemFree((IntPtr)_pNativeOverlapped); - _pNativeOverlapped = null; - } - } - - internal static unsafe OverlappedData GetOverlappedFromNative(NativeOverlapped* pNativeOverlapped) - { - GCHandle handle = *(GCHandle*)(pNativeOverlapped + 1); - return (OverlappedData)handle.Target; - } - } - - #endregion class OverlappedData - - #region class Overlapped - - public class Overlapped - { - private OverlappedData _overlappedData; - - public Overlapped() - { - _overlappedData = new OverlappedData(); - _overlappedData._overlapped = this; - } - - public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar) : this() - { - _overlappedData.OffsetLow = offsetLo; - _overlappedData.OffsetHigh = offsetHi; - _overlappedData.EventHandle = hEvent; - _overlappedData.AsyncResult = ar; - } - - [Obsolete("This constructor is not 64-bit compatible. Use the constructor that takes an IntPtr for the event handle. http://go.microsoft.com/fwlink/?linkid=14202")] - public Overlapped(int offsetLo, int offsetHi, int hEvent, IAsyncResult ar) : this(offsetLo, offsetHi, new IntPtr(hEvent), ar) - { - } - - public IAsyncResult AsyncResult - { - get { return _overlappedData.AsyncResult; } - set { _overlappedData.AsyncResult = value; } - } - - public int OffsetLow - { - get { return _overlappedData.OffsetLow; } - set { _overlappedData.OffsetLow = value; } - } - - public int OffsetHigh - { - get { return _overlappedData.OffsetHigh; } - set { _overlappedData.OffsetHigh = value; } - } - - [Obsolete("This property is not 64-bit compatible. Use EventHandleIntPtr instead. http://go.microsoft.com/fwlink/?linkid=14202")] - public int EventHandle - { - get { return EventHandleIntPtr.ToInt32(); } - set { EventHandleIntPtr = new IntPtr(value); } - } - - public IntPtr EventHandleIntPtr - { - get { return _overlappedData.EventHandle; } - set { _overlappedData.EventHandle = value; } - } - - /*==================================================================== - * Packs a managed overlapped class into native Overlapped struct. - * Roots the iocb and stores it in the ReservedCOR field of native Overlapped - * Pins the native Overlapped struct and returns the pinned index. - ====================================================================*/ - [Obsolete("This method is not safe. Use Pack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] - [CLSCompliant(false)] - public unsafe NativeOverlapped* Pack(IOCompletionCallback iocb) - { - return Pack(iocb, null); - } - - [CLSCompliant(false)] - public unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, object userData) - { - return _overlappedData.Pack(iocb, userData); - } - - [Obsolete("This method is not safe. Use UnsafePack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] - [CLSCompliant(false)] - public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb) - { - return UnsafePack(iocb, null); - } - - [CLSCompliant(false)] - public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, object userData) - { - return _overlappedData.UnsafePack(iocb, userData); - } - - /*==================================================================== - * Unpacks an unmanaged native Overlapped struct. - * Unpins the native Overlapped struct - ====================================================================*/ - [CLSCompliant(false)] - public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) - { - if (nativeOverlappedPtr == null) - throw new ArgumentNullException(nameof(nativeOverlappedPtr)); - - return OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped; - } - - [CLSCompliant(false)] - public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr) - { - if (nativeOverlappedPtr == null) - throw new ArgumentNullException(nameof(nativeOverlappedPtr)); - - OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped._overlappedData = null; - OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr); - } - } - - #endregion class Overlapped -}
\ No newline at end of file diff --git a/netcore/System.Private.CoreLib/src/System/Threading/PreAllocatedOverlapped.cs b/netcore/System.Private.CoreLib/src/System/Threading/PreAllocatedOverlapped.cs deleted file mode 100644 index 580bda2b692..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/PreAllocatedOverlapped.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Threading -{ - public sealed class PreAllocatedOverlapped : System.IDisposable - { - [System.CLSCompliantAttribute(false)] - public PreAllocatedOverlapped(System.Threading.IOCompletionCallback callback, object state, object pinData) { } - public void Dispose() { } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.Mono.cs b/netcore/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.Mono.cs deleted file mode 100644 index fe0426cb510..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.Mono.cs +++ /dev/null @@ -1,102 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; -using Microsoft.Win32.SafeHandles; -using System.IO; - -namespace System.Threading -{ - partial class Semaphore - { - const int MAX_PATH = 260; - - Semaphore (SafeWaitHandle handle) => this.SafeWaitHandle = handle; - - int ReleaseCore (int releaseCount) - { - if (!ReleaseSemaphore_internal (SafeWaitHandle.DangerousGetHandle (), releaseCount, out int previousCount)) - throw new SemaphoreFullException (); - - return previousCount; - } - - static OpenExistingResult OpenExistingWorker (string name, out Semaphore result) - { - if (name == null) - throw new ArgumentNullException (nameof (name)); - - if (name.Length == 0) - throw new ArgumentException (SR.Argument_StringZeroLength, nameof (name)); - - if (name.Length > MAX_PATH) - throw new ArgumentException (SR.Argument_WaitHandleNameTooLong); - - var myHandle = new SafeWaitHandle (OpenSemaphore_internal (name, - /*SemaphoreRights.Modify | SemaphoreRights.Synchronize*/ 0x000002 | 0x100000, - out MonoIOError errorCode), true); - - if (myHandle.IsInvalid) { - result = null; - switch (errorCode) { - case MonoIOError.ERROR_FILE_NOT_FOUND: - case MonoIOError.ERROR_INVALID_NAME: - return OpenExistingResult.NameNotFound; - case MonoIOError.ERROR_PATH_NOT_FOUND: - return OpenExistingResult.PathNotFound; - case MonoIOError.ERROR_INVALID_HANDLE when !string.IsNullOrEmpty (name): - return OpenExistingResult.NameInvalid; - default: - //this is for passed through NativeMethods Errors - throw new IOException ($"Unknown Error '{errorCode}'"); - } - } - - result = new Semaphore (myHandle); - return OpenExistingResult.Success; - } - - void CreateSemaphoreCore (int initialCount, int maximumCount, string name, out bool createdNew) - { - if (name?.Length > MAX_PATH) - throw new ArgumentException (SR.Argument_WaitHandleNameTooLong); - - var myHandle = new SafeWaitHandle (CreateSemaphore_internal (initialCount, maximumCount, name, out MonoIOError errorCode), true); - - if (myHandle.IsInvalid) { - if (errorCode == MonoIOError.ERROR_INVALID_HANDLE && !string.IsNullOrEmpty (name)) - throw new WaitHandleCannotBeOpenedException (SR.Format (SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); - - throw new IOException ($"Unknown Error '{errorCode}'"); - } - - this.SafeWaitHandle = myHandle; - createdNew = errorCode != MonoIOError.ERROR_ALREADY_EXISTS; - } - - unsafe static IntPtr CreateSemaphore_internal (int initialCount, int maximumCount, string name, out MonoIOError errorCode) - { - // FIXME Check for embedded nuls in name. - fixed (char *fixed_name = name) - return CreateSemaphore_icall (initialCount, maximumCount, - fixed_name, name?.Length ?? 0, out errorCode); - } - - unsafe static IntPtr OpenSemaphore_internal (string name, int rights, out MonoIOError errorCode) - { - // FIXME Check for embedded nuls in name. - fixed (char *fixed_name = name) - return OpenSemaphore_icall (fixed_name, name?.Length ?? 0, rights, out errorCode); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - unsafe static extern IntPtr CreateSemaphore_icall (int initialCount, int maximumCount, char* name, int nameLength, out MonoIOError errorCode); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - unsafe static extern IntPtr OpenSemaphore_icall (char* name, int nameLength, int rights, out MonoIOError errorCode); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern bool ReleaseSemaphore_internal (IntPtr handle, int releaseCount, out int previousCount); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/StackCrawlMark.cs b/netcore/System.Private.CoreLib/src/System/Threading/StackCrawlMark.cs deleted file mode 100644 index ebcd9d8e5f9..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/StackCrawlMark.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Threading -{ - // declaring a local var of this enum type and passing it by ref into a function that needs to do a - // stack crawl will both prevent inlining of the calle and pass an ESP point to stack crawl to - // Declaring these in EH clauses is illegal; they must declared in the main method body - internal enum StackCrawlMark - { - LookForMe = 0, - LookForMyCaller = 1, - LookForMyCallersCaller = 2, - LookForThread = 3 - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs b/netcore/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs deleted file mode 100644 index 202225aa64f..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs +++ /dev/null @@ -1,356 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Threading -{ - // - // Under netcore, there is only one thread object per thread - // - [StructLayout (LayoutKind.Sequential)] - partial class Thread - { -#pragma warning disable 169, 414, 649 - #region Sync with metadata/object-internals.h and InternalThread in mcs/class/corlib/System.Threading/Thread.cs - int lock_thread_id; - // stores a thread handle - IntPtr handle; - IntPtr native_handle; // used only on Win32 - /* accessed only from unmanaged code */ - private IntPtr name; - private int name_free; // bool - private int name_length; - private ThreadState state; - private object abort_exc; - private int abort_state_handle; - /* thread_id is only accessed from unmanaged code */ - internal Int64 thread_id; - private IntPtr debugger_thread; // FIXME switch to bool as soon as CI testing with corlib version bump works - private UIntPtr static_data; /* GC-tracked */ - private IntPtr runtime_thread_info; - /* current System.Runtime.Remoting.Contexts.Context instance - keep as an object to avoid triggering its class constructor when not needed */ - private object current_appcontext; - private object root_domain_thread; - internal byte[] _serialized_principal; - internal int _serialized_principal_version; - private IntPtr appdomain_refs; - private int interruption_requested; - private IntPtr longlived; - internal bool threadpool_thread; - private bool thread_interrupt_requested; - /* These are used from managed code */ - internal int stack_size; - internal byte apartment_state; - internal volatile int critical_region_level; - internal int managed_id; - private int small_id; - private IntPtr manage_callback; - private IntPtr flags; - private IntPtr thread_pinning_ref; - private IntPtr abort_protected_block_count; - private int priority; - private IntPtr owned_mutex; - private IntPtr suspended_event; - private int self_suspended; - private IntPtr thread_state; - - private Thread self; - private object pending_exception; - private object start_obj; - - /* This is used only to check that we are in sync between the representation - * of MonoInternalThread in native and InternalThread in managed - * - * DO NOT RENAME! DO NOT ADD FIELDS AFTER! */ - private IntPtr last; - #endregion -#pragma warning restore 169, 414, 649 - - string _name; - Delegate m_start; - object m_start_arg; - CultureInfo culture, ui_culture; - internal ExecutionContext _executionContext; - internal SynchronizationContext _synchronizationContext; - - Thread () - { - InitInternal (this); - } - - ~Thread () - { - FreeInternal (); - } - - internal static ulong CurrentOSThreadId { - get { - return GetCurrentOSThreadId (); - } - } - - public bool IsAlive { - get { - var state = GetState (this); - return (state & (ThreadState.Unstarted | ThreadState.Stopped | ThreadState.Aborted)) == 0; - } - } - - public bool IsBackground { - get { - var state = ValidateThreadState (); - return (state & ThreadState.Background) != 0; - } - set { - ValidateThreadState (); - if (value) { - SetState (this, ThreadState.Background); - } else { - ClrState (this, ThreadState.Background); - } - } - } - - public bool IsThreadPoolThread { - get { - ValidateThreadState (); - return threadpool_thread; - } - internal set { - threadpool_thread = value; - } - } - - public int ManagedThreadId => managed_id; - - internal static int OptimalMaxSpinWaitsPerSpinIteration { - get { - // Default from coreclr (src/utilcode/yieldprocessornormalized.cpp) - return 7; - } - } - - public ThreadPriority Priority { - get { - ValidateThreadState (); - return (ThreadPriority) priority; - } - set { - // TODO: arguments check - SetPriority (this, (int) value); - } - } - - public ThreadState ThreadState => GetState (this); - - void Create (ThreadStart start) => SetStartHelper ((Delegate) start, 0); // 0 will setup Thread with default stackSize - - void Create (ThreadStart start, int maxStackSize) => SetStartHelper ((Delegate) start, maxStackSize); - - void Create (ParameterizedThreadStart start) => SetStartHelper ((Delegate) start, 0); - - void Create (ParameterizedThreadStart start, int maxStackSize) => SetStartHelper ((Delegate) start, maxStackSize); - - public ApartmentState GetApartmentState () => ApartmentState.Unknown; - - public void DisableComObjectEagerCleanup () - { - // no-op - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static int GetCurrentProcessorNumber (); - - public static int GetCurrentProcessorId () - { - int id = GetCurrentProcessorNumber (); - - if (id < 0) - id = Environment.CurrentManagedThreadId; - - return id; - } - - public void Interrupt () - { - InterruptInternal (this); - } - - public bool Join (int millisecondsTimeout) - { - if (millisecondsTimeout < Timeout.Infinite) - throw new ArgumentOutOfRangeException (nameof (millisecondsTimeout), millisecondsTimeout, SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return JoinInternal (this, millisecondsTimeout); - } - - internal void ResetThreadPoolThread () - { - if (_name != null) - Name = null; - - if ((state & ThreadState.Background) == 0) - IsBackground = true; - - if ((ThreadPriority) priority != ThreadPriority.Normal) - Priority = ThreadPriority.Normal; - } - - void SetCultureOnUnstartedThreadNoCheck (CultureInfo value, bool uiCulture) - { - if (uiCulture) - ui_culture = value; - else - culture = value; - } - - void SetStartHelper (Delegate start, int maxStackSize) - { - m_start = start; - stack_size = maxStackSize; - } - - public static void SpinWait (int iterations) - { - if (iterations < 0) - return; - - while (iterations-- > 0) - SpinWait_nop (); - } - - public static void Sleep (int millisecondsTimeout) - { - if (millisecondsTimeout < Timeout.Infinite) - throw new ArgumentOutOfRangeException (nameof (millisecondsTimeout), millisecondsTimeout, SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - - SleepInternal (millisecondsTimeout, true); - } - - internal static void UninterruptibleSleep0 () => SleepInternal (0, false); - - public void Start () - { - StartInternal (this); - } - - public void Start (object parameter) - { - if (m_start is ThreadStart) - throw new InvalidOperationException (SR.InvalidOperation_ThreadWrongThreadStart); - - m_start_arg = parameter; - StartInternal (this); - } - - // Called from the runtime - internal void StartCallback () - { - if (culture != null) - CurrentCulture = culture; - if (ui_culture != null) - CurrentUICulture = ui_culture; - if (m_start is ThreadStart del) { - m_start = null; - del (); - } else { - var pdel = (ParameterizedThreadStart) m_start; - var arg = m_start_arg; - m_start = null; - m_start_arg = null; - pdel (arg); - } - } - - partial void ThreadNameChanged (string value) - { - // TODO: Should only raise the events - SetName (this, value); - } - - public static bool Yield () - { - return YieldInternal (); - } - - bool TrySetApartmentStateUnchecked (ApartmentState state) => state == ApartmentState.Unknown; - - ThreadState ValidateThreadState () - { - var state = GetState (this); - if ((state & ThreadState.Stopped) != 0) - throw new ThreadStateException ("Thread is dead; state can not be accessed."); - return state; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - private extern static ulong GetCurrentOSThreadId (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void InitInternal (Thread thread); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern static void InitializeCurrentThread_icall (ref Thread thread); - - [MethodImpl (MethodImplOptions.NoInlining)] - static Thread InitializeCurrentThread () { - Thread thread = null; - InitializeCurrentThread_icall (ref thread); - return thread; - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern void FreeInternal (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static ThreadState GetState (Thread thread); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void SetState (Thread thread, ThreadState set); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void ClrState (Thread thread, ThreadState clr); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static string GetName (Thread thread); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static unsafe extern void SetName_icall (Thread thread, char *name, int nameLength); - - static unsafe void SetName (Thread thread, String name) - { - fixed (char* fixed_name = name) - SetName_icall (thread, fixed_name, name?.Length ?? 0); - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static bool YieldInternal (); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static void SleepInternal (int millisecondsTimeout, bool allowInterruption); - - [Intrinsic] - static void SpinWait_nop () - { - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static Thread CreateInternal (); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static void StartInternal (Thread runtime_thread); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static bool JoinInternal (Thread thread, int millisecondsTimeout); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static void InterruptInternal (Thread thread); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - extern static void SetPriority (Thread thread, int priority); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Threading/ThreadPool.Mono.cs b/netcore/System.Private.CoreLib/src/System/Threading/ThreadPool.Mono.cs deleted file mode 100644 index b3b3039bc59..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/ThreadPool.Mono.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -namespace System.Threading -{ - public static partial class ThreadPool - { - private static void EnsureInitialized() - { - ThreadPoolGlobals.threadPoolInitialized = true; - ThreadPoolGlobals.enableWorkerTracking = false; - } - - internal static void ReportThreadStatus(bool isWorking) - { - } - - unsafe private static void NativeOverlappedCallback(object? obj) - { - NativeOverlapped* overlapped = (NativeOverlapped*)(IntPtr)obj!; - _IOCompletionCallback.PerformIOCompletionCallback (0, 0, overlapped); - } - - [CLSCompliant(false)] - unsafe public static bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped) - { - // OS doesn't signal handle, so do it here (CoreCLR does this assignment in ThreadPoolNative::CorPostQueuedCompletionStatus) - overlapped->InternalLow = (IntPtr)0; - // Both types of callbacks are executed on the same thread pool - return UnsafeQueueUserWorkItem (NativeOverlappedCallback, (IntPtr)overlapped); - } - - [Obsolete("ThreadPool.BindHandle(IntPtr) has been deprecated. Please use ThreadPool.BindHandle(SafeHandle) instead.", false)] - public static bool BindHandle(IntPtr osHandle) - { - throw new PlatformNotSupportedException (SR.Arg_PlatformNotSupported); // Replaced by ThreadPoolBoundHandle.BindHandle - } - - public static bool BindHandle(SafeHandle osHandle) - { - throw new PlatformNotSupportedException (SR.Arg_PlatformNotSupported); // Replaced by ThreadPoolBoundHandle.BindHandle - } - - private static long PendingUnmanagedWorkItemCount => 0; - } -}
\ No newline at end of file diff --git a/netcore/System.Private.CoreLib/src/System/Threading/WaitHandle.Mono.cs b/netcore/System.Private.CoreLib/src/System/Threading/WaitHandle.Mono.cs deleted file mode 100644 index fb11248a402..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Threading/WaitHandle.Mono.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System.Threading -{ - partial class WaitHandle - { - [MethodImplAttribute(MethodImplOptions.InternalCall)] - unsafe static extern int Wait_internal(IntPtr* handles, int numHandles, bool waitAll, int ms); - - static int WaitOneCore (IntPtr waitHandle, int millisecondsTimeout) - { - unsafe { - return Wait_internal (&waitHandle, 1, false, millisecondsTimeout); - } - } - - [MethodImpl (MethodImplOptions.InternalCall)] - static extern int SignalAndWait_Internal (IntPtr waitHandleToSignal, IntPtr waitHandleToWaitOn, int millisecondsTimeout); - - const int ERROR_TOO_MANY_POSTS = 0x12A; - const int ERROR_NOT_OWNED_BY_CALLER = 0x12B; - - static int SignalAndWaitCore (IntPtr waitHandleToSignal, IntPtr waitHandleToWaitOn, int millisecondsTimeout) - { - int ret = SignalAndWait_Internal (waitHandleToSignal, waitHandleToWaitOn, millisecondsTimeout); - if (ret == ERROR_TOO_MANY_POSTS) - throw new InvalidOperationException (SR.Threading_WaitHandleTooManyPosts); - if (ret == ERROR_NOT_OWNED_BY_CALLER) - throw new ApplicationException("Attempt to release mutex not owned by caller"); - return ret; - } - - internal static int WaitMultipleIgnoringSyncContext (Span<IntPtr> waitHandles, bool waitAll, int millisecondsTimeout) - { - unsafe { - fixed (IntPtr* handles = &MemoryMarshal.GetReference (waitHandles)) { - return Wait_internal (handles, waitHandles.Length, waitAll, millisecondsTimeout); - } - } - } - - // FIXME: Move to shared - internal static int WaitAny (ReadOnlySpan<WaitHandle> waitHandles, int millisecondsTimeout) => - WaitMultiple (waitHandles, false, millisecondsTimeout); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/Type.Mono.cs b/netcore/System.Private.CoreLib/src/System/Type.Mono.cs deleted file mode 100644 index a5f4fa1feea..00000000000 --- a/netcore/System.Private.CoreLib/src/System/Type.Mono.cs +++ /dev/null @@ -1,135 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Text; -using System.IO; -using System.Reflection; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading; - -namespace System -{ - partial class Type - { - #region keep in sync with object-internals.h - internal RuntimeTypeHandle _impl; - #endregion - - internal bool IsRuntimeImplemented () => this.UnderlyingSystemType is RuntimeType; - - internal virtual bool IsTypeBuilder () => false; - - public bool IsInterface { - get { - if (this is RuntimeType rt) - return RuntimeTypeHandle.IsInterface (rt); - - return (GetAttributeFlagsImpl () & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface; - } - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Type GetType (string typeName, bool throwOnError, bool ignoreCase) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeType.GetType (typeName, throwOnError, ignoreCase, false, ref stackMark); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Type GetType (string typeName, bool throwOnError) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeType.GetType (typeName, throwOnError, false, false, ref stackMark); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Type GetType (string typeName) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeType.GetType (typeName, false, false, false, ref stackMark); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Type GetType (string typeName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeType.GetType (typeName, assemblyResolver, typeResolver, false, false, ref stackMark); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Type GetType (string typeName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeType.GetType (typeName, assemblyResolver, typeResolver, throwOnError, false, ref stackMark); - } - - [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Type GetType (string typeName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RuntimeType.GetType (typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); - } - - static Type GetType (string typeName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { - return TypeNameParser.GetType (typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); - } - - public static Type? GetTypeFromHandle (RuntimeTypeHandle handle) - { - if (handle.Value == IntPtr.Zero) - return null; - - return internal_from_handle (handle.Value); - } - - public static Type GetTypeFromCLSID (Guid clsid, string? server, bool throwOnError) => throw new PlatformNotSupportedException (); - - public static Type GetTypeFromProgID (string progID, string? server, bool throwOnError) => throw new PlatformNotSupportedException (); - - internal virtual Type InternalResolve () - { - return UnderlyingSystemType; - } - - // Called from the runtime to return the corresponding finished Type object - internal virtual Type RuntimeResolve () - { - throw new NotImplementedException (); - } - - internal virtual bool IsUserType { - get { - return true; - } - } - - internal virtual MethodInfo GetMethod (MethodInfo fromNoninstanciated) - { - throw new InvalidOperationException ("can only be called in generic type"); - } - - internal virtual ConstructorInfo GetConstructor (ConstructorInfo fromNoninstanciated) - { - throw new InvalidOperationException ("can only be called in generic type"); - } - - internal virtual FieldInfo GetField (FieldInfo fromNoninstanciated) - { - throw new InvalidOperationException ("can only be called in generic type"); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - static extern Type internal_from_handle (IntPtr handle); - - [Intrinsic] - public static bool operator == (Type? left, Type? right) => left == right; - - public static bool operator != (Type? left, Type? right) - { - return !(left == right); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/TypeIdentifier.cs b/netcore/System.Private.CoreLib/src/System/TypeIdentifier.cs deleted file mode 100644 index 0460777d058..00000000000 --- a/netcore/System.Private.CoreLib/src/System/TypeIdentifier.cs +++ /dev/null @@ -1,221 +0,0 @@ -// -// Copyright (C) 2015 Xamarin, Inc (http://www.xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -namespace System -{ - // A TypeName is wrapper around type names in display form - // (that is, with special characters escaped). - // - // Note that in general if you unescape a type name, you will - // lose information: If the type name's DisplayName is - // Foo\+Bar+Baz (outer class ``Foo+Bar``, inner class Baz) - // unescaping the first plus will give you (outer class Foo, - // inner class Bar, innermost class Baz). - // - // The correct way to take a TypeName apart is to feed its - // DisplayName to TypeSpec.Parse() - // - interface TypeName : IEquatable<TypeName> - { - string DisplayName { - get; - } - - // add a nested name under this one. - TypeName NestedName (TypeIdentifier innerName); - } - - // A type identifier is a single component of a type name. - // Unlike a general typename, a type identifier can be be - // converted to internal form without loss of information. - interface TypeIdentifier : TypeName - { - string InternalName { - get; - } - } - - static class TypeNames - { - internal static TypeName FromDisplay (string displayName) - { - return new Display (displayName); - } - - internal abstract class ATypeName : TypeName - { - public abstract string DisplayName { get; } - - public abstract TypeName NestedName (TypeIdentifier innerName); - - public bool Equals (TypeName other) - { - return other != null && DisplayName == other.DisplayName; - } - - public override int GetHashCode () - { - return DisplayName.GetHashCode (); - } - - public override bool Equals (object? other) - { - return Equals (other as TypeName); - } - } - - private class Display : ATypeName - { - string displayName; - - internal Display (string displayName) - { - this.displayName = displayName; - } - - public override string DisplayName { get { return displayName; } } - - public override TypeName NestedName (TypeIdentifier innerName) - { - return new Display (DisplayName + "+" + innerName.DisplayName); - } - - } - } - - static class TypeIdentifiers - { - internal static TypeIdentifier FromDisplay (string displayName) - { - return new Display (displayName); - } - - internal static TypeIdentifier FromInternal (string internalName) - { - return new Internal (internalName); - } - - internal static TypeIdentifier FromInternal (string internalNameSpace, TypeIdentifier typeName) - { - return new Internal (internalNameSpace, typeName); - } - - // Only use if simpleName is certain not to contain - // unexpected characters that ordinarily require - // escaping: ,+*&[]\ - internal static TypeIdentifier WithoutEscape (string simpleName) - { - return new NoEscape (simpleName); - } - - private class Display : TypeNames.ATypeName, TypeIdentifier - { - string displayName; - string internal_name; //cached - - internal Display (string displayName) - { - this.displayName = displayName; - } - - public override string DisplayName { - get { return displayName; } - } - - public string InternalName { - get { - if (internal_name == null) - internal_name = GetInternalName (); - return internal_name; - } - } - - private string GetInternalName () - { - return TypeSpec.UnescapeInternalName (displayName); - } - - public override TypeName NestedName (TypeIdentifier innerName) - { - return TypeNames.FromDisplay (DisplayName + "+" + innerName.DisplayName); - } - } - - - private class Internal : TypeNames.ATypeName, TypeIdentifier - { - string internalName; - string display_name; //cached - - internal Internal (string internalName) - { - this.internalName = internalName; - } - - internal Internal (string nameSpaceInternal, TypeIdentifier typeName) - { - this.internalName = nameSpaceInternal + "." + typeName.InternalName; - } - - public override string DisplayName { - get { - if (display_name == null) - display_name = GetDisplayName (); - return display_name; - } - } - - public string InternalName { - get { return internalName; } - } - - private string GetDisplayName () - { - return TypeSpec.EscapeDisplayName (internalName); - } - - public override TypeName NestedName (TypeIdentifier innerName) - { - return TypeNames.FromDisplay (DisplayName + "+" + innerName.DisplayName); - } - - } - - private class NoEscape : TypeNames.ATypeName, TypeIdentifier - { - string simpleName; - internal NoEscape (string simpleName) - { - this.simpleName = simpleName; - } - - public override string DisplayName { get { return simpleName; } } - public string InternalName { get { return simpleName; } } - - public override TypeName NestedName (TypeIdentifier innerName) - { - return TypeNames.FromDisplay (DisplayName + "+" + innerName.DisplayName); - } - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/TypeLoadException.Mono.cs b/netcore/System.Private.CoreLib/src/System/TypeLoadException.Mono.cs deleted file mode 100644 index e8f8f13c729..00000000000 --- a/netcore/System.Private.CoreLib/src/System/TypeLoadException.Mono.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System -{ - partial class TypeLoadException - { - // Called by runtime - internal TypeLoadException (string className, string assemblyName) - : this (null) - { - _className = className; - _assemblyName = assemblyName; - } - - void SetMessageField () - { - if (_message != null) - return; - - if (_className == null) { - _message = SR.Arg_TypeLoadException; - return; - } - - _message = SR.Format ("Could not load type '{0}' from assembly '{1}'.", _className, _assemblyName ?? SR.IO_UnknownFileName); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/TypeNameParser.cs b/netcore/System.Private.CoreLib/src/System/TypeNameParser.cs deleted file mode 100644 index a4f01a7624d..00000000000 --- a/netcore/System.Private.CoreLib/src/System/TypeNameParser.cs +++ /dev/null @@ -1,409 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Text; -using System.IO; -using System.Reflection; -using System.Collections.Generic; -using System.Threading; - -namespace System -{ - internal static class TypeNameParser - { - static readonly char[] SPECIAL_CHARS = {',', '[', ']', '&', '*', '+', '\\'}; - - internal static Type GetType ( - string typeName, - Func<AssemblyName, Assembly> assemblyResolver, - Func<Assembly, string, bool, Type> typeResolver, - bool throwOnError, - bool ignoreCase, - ref StackCrawlMark stackMark) - { - if (typeName == null) - throw new ArgumentNullException (nameof (typeName)); - - ParsedName pname = ParseName (typeName, false, 0, out int end_pos); - if (pname == null) { - if (throwOnError) - throw new ArgumentException (); - return null; - } - - return ConstructType (pname, assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); - } - - static Type ConstructType ( - ParsedName pname, - Func<AssemblyName, Assembly> assemblyResolver, - Func<Assembly, string, bool, Type> typeResolver, - bool throwOnError, - bool ignoreCase, - ref StackCrawlMark stackMark) - { - // Resolve assembly - Assembly assembly = null; - if (pname.AssemblyName != null) { - assembly = ResolveAssembly (pname.AssemblyName, assemblyResolver, throwOnError, ref stackMark); - if (assembly == null) - // If throwOnError is true, an exception was already thrown - return null; - } - - // Resolve base type - var type = ResolveType (assembly, pname.Names, typeResolver, throwOnError, ignoreCase, ref stackMark); - if (type == null) - return null; - - // Resolve type arguments - if (pname.TypeArguments != null) { - var args = new Type [pname.TypeArguments.Count]; - for (int i = 0; i < pname.TypeArguments.Count; ++i) { - args [i] = ConstructType (pname.TypeArguments [i], assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); - if (args [i] == null) - return null; - } - type = type.MakeGenericType (args); - } - - // Resolve modifiers - if (pname.Modifiers != null) { - bool bounded = false; - foreach (var mod in pname.Modifiers) { - switch (mod) { - case 0: - type = type.MakeByRefType (); - break; - case -1: - type = type.MakePointerType (); - break; - case -2: - bounded = true; - break; - case 1: - if (bounded) - type = type.MakeArrayType (1); - else - type = type.MakeArrayType (); - break; - default: - type = type.MakeArrayType (mod); - break; - } - } - } - - return type; - } - - static Assembly ResolveAssembly (string name, Func<AssemblyName, Assembly> assemblyResolver, bool throwOnError, - ref StackCrawlMark stackMark) - { - var aname = new AssemblyName (name); - - if (assemblyResolver == null) { - if (throwOnError) { - return Assembly.Load (aname, ref stackMark, null); - } else { - try { - return Assembly.Load (aname, ref stackMark, null); - } catch (FileNotFoundException) { - return null; - } - } - } else { - var assembly = assemblyResolver (aname); - if (assembly == null && throwOnError) - throw new FileNotFoundException (SR.FileNotFound_ResolveAssembly, name); - return assembly; - } - } - - static Type ResolveType (Assembly assembly, List<string> names, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) - { - Type type = null; - - string name = EscapeTypeName (names [0]); - // Resolve the top level type. - if (typeResolver != null) { - type = typeResolver (assembly, name, ignoreCase); - if (type == null && throwOnError) { - if (assembly == null) - throw new TypeLoadException (SR.Format (SR.TypeLoad_ResolveType, name)); - else - throw new TypeLoadException (SR.Format (SR.TypeLoad_ResolveTypeFromAssembly, name, assembly.FullName)); - } - } else { - if (assembly == null) - type = RuntimeType.GetType (name, throwOnError, ignoreCase, false, ref stackMark); - else - type = assembly.GetType (name, throwOnError, ignoreCase); - } - - if (type == null) - return null; - - // Resolve nested types. - BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public; - if (ignoreCase) - bindingFlags |= BindingFlags.IgnoreCase; - - for (int i = 1; i < names.Count; ++i) { - type = type.GetNestedType (names[i], bindingFlags); - if (type == null) { - if (throwOnError) - throw new TypeLoadException (SR.Format (SR.TypeLoad_ResolveNestedType, names[i], names[i-1])); - else - break; - } - } - return type; - } - - static string EscapeTypeName (string name) - { - if (name.IndexOfAny (SPECIAL_CHARS) < 0) - return name; - - var sb = new StringBuilder (name.Length); - foreach (char c in name) { - if (Array.IndexOf<char> (SPECIAL_CHARS, c) >= 0) - sb.Append ('\\'); - sb.Append (c); - } - - return sb.ToString (); - } - - static string UnescapeTypeName (string name) - { - if (name.IndexOfAny (SPECIAL_CHARS) < 0) - return name; - - var sb = new StringBuilder (name.Length - 1); - for (int i = 0; i < name.Length; ++i) { - if (name [i] == '\\' && i + 1 < name.Length) - i++; - sb.Append (name [i]); - } - - return sb.ToString (); - } - - class ParsedName { - public List<string> Names; - public List<ParsedName> TypeArguments; - public List<int> Modifiers; - public string AssemblyName; - - /* For debugging - public override string ToString () { - var sb = new StringBuilder (); - sb.Append (Names [0]); - if (TypeArguments != null) { - sb.Append ("["); - for (int i = 0; i < TypeArguments.Count; ++i) { - if (TypeArguments [i].AssemblyName != null) - sb.Append ('['); - sb.Append (TypeArguments [i].ToString ()); - if (TypeArguments [i].AssemblyName != null) - sb.Append (']'); - if (i < TypeArguments.Count - 1) - sb.Append (", "); - } - sb.Append ("]"); - } - if (AssemblyName != null) - sb.Append ($", {AssemblyName}"); - return sb.ToString (); - } - */ - } - - // Ported from the C version in mono_reflection_parse_type_checked () - // Entries to the Names list are unescaped to internal form while AssemblyName is not, in an effort to maintain - // consistency with our native parser. Since this function is just called recursively, that should also be true - // for ParsedNames in TypeArguments. - static ParsedName ParseName (string name, bool recursed, int pos, out int end_pos) - { - end_pos = 0; - - while (pos < name.Length && name [pos] == ' ') - pos ++; - - var res = new ParsedName () { Names = new List<string> () }; - - int start = pos; - int name_start = pos; - bool in_modifiers = false; - while (pos < name.Length) { - switch (name [pos]) { - case '+': - res.Names.Add (UnescapeTypeName (name.Substring (name_start, pos - name_start))); - name_start = pos + 1; - break; - case '\\': - pos ++; - break; - case '&': - case '*': - case '[': - case ',': - case ']': - in_modifiers = true; - break; - default: - break; - } - if (in_modifiers) - break; - pos ++; - } - - res.Names.Add (UnescapeTypeName (name.Substring (name_start, pos - name_start))); - - bool isbyref = false; - bool isptr = false; - int rank = -1; - - bool end = false; - while (pos < name.Length && !end) { - switch (name [pos]) { - case '&': - if (isbyref) - return null; - pos ++; - isbyref = true; - isptr = false; - if (res.Modifiers == null) - res.Modifiers = new List<int> (); - res.Modifiers.Add (0); - break; - case '*': - if (isbyref) - return null; - pos ++; - if (res.Modifiers == null) - res.Modifiers = new List<int> (); - res.Modifiers.Add (-1); - isptr = true; - break; - case '[': - // An array or generic arguments - if (isbyref) - return null; - pos ++; - if (pos == name.Length) - return null; - - if (name [pos] == ',' || name [pos] == '*' || name [pos] == ']') { - // Array - bool bounded = false; - isptr = false; - rank = 1; - while (pos < name.Length) { - if (name [pos] == ']') - break; - if (name [pos] == ',') - rank ++; - else if (name [pos] == '*') /* '*' means unknown lower bound */ - bounded = true; - else - return null; - pos ++; - } - if (pos == name.Length) - return null; - if (name [pos] != ']') - return null; - pos ++; - /* bounded only allowed when rank == 1 */ - if (bounded && rank > 1) - return null; - /* n.b. bounded needs both modifiers: -2 == bounded, 1 == rank 1 array */ - if (res.Modifiers == null) - res.Modifiers = new List<int> (); - if (bounded) - res.Modifiers.Add (-2); - res.Modifiers.Add (rank); - } else { - // Generic args - if (rank > 0 || isptr) - return null; - isptr = false; - res.TypeArguments = new List<ParsedName> (); - while (pos < name.Length) { - while (pos < name.Length && name [pos] == ' ') - pos ++; - bool fqname = false; - if (pos < name.Length && name [pos] == '[') { - pos ++; - fqname = true; - } - - var arg = ParseName (name, true, pos, out pos); - if (arg == null) - return null; - res.TypeArguments.Add (arg); - - /*MS is lenient on [] delimited parameters that aren't fqn - and F# uses them.*/ - if (fqname && pos < name.Length && name [pos] != ']') { - if (name [pos] != ',') - return null; - pos ++; - int aname_start = pos; - while (pos < name.Length && name [pos] != ']') - pos ++; - if (pos == name.Length) - return null; - while (Char.IsWhiteSpace (name [aname_start])) - aname_start ++; - if (aname_start == pos) - return null; - arg.AssemblyName = name.Substring (aname_start, pos - aname_start); - pos ++; - } else if (fqname && pos < name.Length && name [pos] == ']') { - pos ++; - } - if (pos < name.Length && name [pos] == ']') { - pos ++; - break; - } else if (pos == name.Length) - return null; - pos ++; - } - } - break; - case ']': - if (recursed) { - end = true; - break; - } - return null; - case ',': - if (recursed) { - end = true; - break; - } - pos ++; - while (pos < name.Length && Char.IsWhiteSpace (name [pos])) - pos ++; - if (pos == name.Length) - return null; - res.AssemblyName = name.Substring (pos); - end = true; - break; - default: - return null; - } - if (end) - break; - } - - end_pos = pos; - return res; - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/TypeSpec.cs b/netcore/System.Private.CoreLib/src/System/TypeSpec.cs deleted file mode 100644 index 3391c1fd343..00000000000 --- a/netcore/System.Private.CoreLib/src/System/TypeSpec.cs +++ /dev/null @@ -1,620 +0,0 @@ -// -// System.Type.cs -// -// Author: -// Rodrigo Kumpera <kumpera@gmail.com> -// -// -// Copyright (C) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Threading; - -namespace System { - internal interface ModifierSpec { - Type Resolve (Type type); - Text.StringBuilder Append (Text.StringBuilder sb); - } - internal class ArraySpec : ModifierSpec - { - // dimensions == 1 and bound, or dimensions > 1 and !bound - int dimensions; - bool bound; - - internal ArraySpec (int dimensions, bool bound) - { - this.dimensions = dimensions; - this.bound = bound; - } - - public Type Resolve (Type type) - { - if (bound) - return type.MakeArrayType (1); - else if (dimensions == 1) - return type.MakeArrayType (); - return type.MakeArrayType (dimensions); - } - - public Text.StringBuilder Append (Text.StringBuilder sb) - { - if (bound) - return sb.Append ("[*]"); - return sb.Append ('[') - .Append (',', dimensions - 1) - .Append (']'); - - } - public override string ToString () - { - return Append (new Text.StringBuilder ()).ToString (); - } - - public int Rank { - get { - return dimensions; - } - } - - public bool IsBound { - get { - return bound; - } - } - } - - internal class PointerSpec : ModifierSpec - { - int pointer_level; - - internal PointerSpec (int pointer_level) { - this.pointer_level = pointer_level; - } - - public Type Resolve (Type type) { - for (int i = 0; i < pointer_level; ++i) - type = type.MakePointerType (); - return type; - } - - public Text.StringBuilder Append (Text.StringBuilder sb) - { - return sb.Append ('*', pointer_level); - } - - public override string ToString () { - return Append (new Text.StringBuilder ()).ToString (); - } - - } - - internal class TypeSpec - { - TypeIdentifier name; - string assembly_name; - List<TypeIdentifier> nested; - List<TypeSpec> generic_params; - List<ModifierSpec> modifier_spec; - bool is_byref; - - string display_fullname; // cache - - internal bool HasModifiers { - get { return modifier_spec != null; } - } - - internal bool IsNested { - get { return nested != null && nested.Count > 0; } - } - - internal bool IsByRef { - get { return is_byref; } - } - - internal TypeName Name { - get { return name; } - } - - internal IEnumerable<TypeName> Nested { - get { - if (nested != null) - return nested; - else - return Array.Empty<TypeName> (); - } - } - - internal IEnumerable<ModifierSpec> Modifiers { - get { - if (modifier_spec != null) - return modifier_spec; - else - return Array.Empty<ModifierSpec> (); - } - } - - [Flags] - internal enum DisplayNameFormat { - Default = 0x0, - WANT_ASSEMBLY = 0x1, - NO_MODIFIERS = 0x2, - } -#if DEBUG - public override string ToString () { - return GetDisplayFullName (DisplayNameFormat.WANT_ASSEMBLY); - } -#endif - - string GetDisplayFullName (DisplayNameFormat flags) - { - bool wantAssembly = (flags & DisplayNameFormat.WANT_ASSEMBLY) != 0; - bool wantModifiers = (flags & DisplayNameFormat.NO_MODIFIERS) == 0; - var sb = new Text.StringBuilder(name.DisplayName); - if (nested != null) { - foreach (var n in nested) - sb.Append ('+').Append (n.DisplayName); - } - - if (generic_params != null) { - sb.Append ('['); - for (int i = 0; i < generic_params.Count; ++i) { - if (i > 0) - sb.Append (", "); - if (generic_params [i].assembly_name != null) - sb.Append ('[').Append (generic_params [i].DisplayFullName).Append (']'); - else - sb.Append (generic_params [i].DisplayFullName); - } - sb.Append (']'); - } - - if (wantModifiers) - GetModifierString (sb); - - if (assembly_name != null && wantAssembly) - sb.Append (", ").Append (assembly_name); - - return sb.ToString(); - } - - internal string ModifierString () - { - return GetModifierString (new Text.StringBuilder ()).ToString (); - } - - private Text.StringBuilder GetModifierString (Text.StringBuilder sb) - { - if (modifier_spec != null) { - foreach (var md in modifier_spec) - md.Append (sb); - } - - if (is_byref) - sb.Append ('&'); - - return sb; - } - - internal string DisplayFullName { - get { - if (display_fullname == null) - display_fullname = GetDisplayFullName (DisplayNameFormat.Default); - return display_fullname; - } - } - - internal static TypeSpec Parse (string typeName) - { - int pos = 0; - if (typeName == null) - throw new ArgumentNullException ("typeName"); - - TypeSpec res = Parse (typeName, ref pos, false, true); - if (pos < typeName.Length) - throw new ArgumentException ("Count not parse the whole type name", "typeName"); - return res; - } - - internal static string EscapeDisplayName(string internalName) - { - // initial capacity = length of internalName. - // Maybe we won't have to escape anything. - var res = new Text.StringBuilder (internalName.Length); - foreach (char c in internalName) - { - switch (c) { - case '+': - case ',': - case '[': - case ']': - case '*': - case '&': - case '\\': - res.Append ('\\').Append (c); - break; - default: - res.Append (c); - break; - } - } - return res.ToString (); - } - - internal static string UnescapeInternalName(string displayName) - { - var res = new Text.StringBuilder (displayName.Length); - for (int i = 0; i < displayName.Length; ++i) - { - char c = displayName[i]; - if (c == '\\') - if (++i < displayName.Length) - c = displayName[i]; - res.Append (c); - } - return res.ToString (); - } - - internal static bool NeedsEscaping (string internalName) - { - foreach (char c in internalName) - { - switch (c) { - case ',': - case '+': - case '*': - case '&': - case '[': - case ']': - case '\\': - return true; - default: - break; - } - } - return false; - } - - internal Type Resolve (Func<AssemblyName,Assembly> assemblyResolver, Func<Assembly,string,bool,Type> typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) - { - Assembly asm = null; - if (assemblyResolver == null && typeResolver == null) - return RuntimeType.GetType (DisplayFullName, throwOnError, ignoreCase, false, ref stackMark); - - if (assembly_name != null) { - if (assemblyResolver != null) - asm = assemblyResolver (new AssemblyName (assembly_name)); - else - asm = Assembly.Load (assembly_name); - - if (asm == null) { - if (throwOnError) - throw new FileNotFoundException ("Could not resolve assembly '" + assembly_name + "'"); - return null; - } - } - - Type type = null; - if (typeResolver != null) - type = typeResolver (asm, name.DisplayName, ignoreCase); - else - type = asm.GetType (name.DisplayName, false, ignoreCase); - if (type == null) { - if (throwOnError) - throw new TypeLoadException ("Could not resolve type '" + name + "'"); - return null; - } - - if (nested != null) { - foreach (var n in nested) { - var tmp = type.GetNestedType (n.DisplayName, BindingFlags.Public | BindingFlags.NonPublic); - if (tmp == null) { - if (throwOnError) - throw new TypeLoadException ("Could not resolve type '" + n + "'"); - return null; - } - type = tmp; - } - } - - if (generic_params != null) { - Type[] args = new Type [generic_params.Count]; - for (int i = 0; i < args.Length; ++i) { - var tmp = generic_params [i].Resolve (assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); - if (tmp == null) { - if (throwOnError) - throw new TypeLoadException ("Could not resolve type '" + generic_params [i].name + "'"); - return null; - } - args [i] = tmp; - } - type = type.MakeGenericType (args); - } - - if (modifier_spec != null) { - foreach (var md in modifier_spec) - type = md.Resolve (type); - } - - if (is_byref) - type = type.MakeByRefType (); - - return type; - } - - void AddName (string type_name) - { - if (name == null) { - name = ParsedTypeIdentifier(type_name); - } else { - if (nested == null) - nested = new List <TypeIdentifier> (); - nested.Add (ParsedTypeIdentifier(type_name)); - } - } - - void AddModifier (ModifierSpec md) - { - if (modifier_spec == null) - modifier_spec = new List<ModifierSpec> (); - modifier_spec.Add (md); - } - - static void SkipSpace (string name, ref int pos) - { - int p = pos; - while (p < name.Length && Char.IsWhiteSpace (name [p])) - ++p; - pos = p; - } - - static void BoundCheck (int idx, string s) - { - if (idx >= s.Length) - throw new ArgumentException ("Invalid generic arguments spec", "typeName"); - } - - static TypeIdentifier ParsedTypeIdentifier (string displayName) - { - return TypeIdentifiers.FromDisplay(displayName); - } - - static TypeSpec Parse (string name, ref int p, bool is_recurse, bool allow_aqn) - { - // Invariants: - // - On exit p, is updated to pos the current unconsumed character. - // - // - The callee peeks at but does not consume delimiters following - // recurisve parse (so for a recursive call like the args of "Foo[P,Q]" - // we'll return with p either on ',' or on ']'. If the name was aqn'd - // "Foo[[P,assmblystuff],Q]" on return p with be on the ']' just - // after the "assmblystuff") - // - // - If allow_aqn is True, assembly qualification is optional. - // If allow_aqn is False, assembly qualification is prohibited. - int pos = p; - int name_start; - bool in_modifiers = false; - TypeSpec data = new TypeSpec (); - - SkipSpace (name, ref pos); - - name_start = pos; - - for (; pos < name.Length; ++pos) { - switch (name [pos]) { - case '+': - data.AddName (name.Substring (name_start, pos - name_start)); - name_start = pos + 1; - break; - case ',': - case ']': - data.AddName (name.Substring (name_start, pos - name_start)); - name_start = pos + 1; - in_modifiers = true; - if (is_recurse && !allow_aqn) { - p = pos; - return data; - } - break; - case '&': - case '*': - case '[': - if (name [pos] != '[' && is_recurse) - throw new ArgumentException ("Generic argument can't be byref or pointer type", "typeName"); - data.AddName (name.Substring (name_start, pos - name_start)); - name_start = pos + 1; - in_modifiers = true; - break; - case '\\': - pos++; - break; - } - if (in_modifiers) - break; - } - - if (name_start < pos) - data.AddName (name.Substring (name_start, pos - name_start)); - else if (name_start == pos) - data.AddName (String.Empty); - - if (in_modifiers) { - for (; pos < name.Length; ++pos) { - - switch (name [pos]) { - case '&': - if (data.is_byref) - throw new ArgumentException ("Can't have a byref of a byref", "typeName"); - - data.is_byref = true; - break; - case '*': - if (data.is_byref) - throw new ArgumentException ("Can't have a pointer to a byref type", "typeName"); - // take subsequent '*'s too - int pointer_level = 1; - while (pos+1 < name.Length && name[pos+1] == '*') { - ++pos; - ++pointer_level; - } - data.AddModifier (new PointerSpec(pointer_level)); - break; - case ',': - if (is_recurse && allow_aqn) { - int end = pos; - while (end < name.Length && name [end] != ']') - ++end; - if (end >= name.Length) - throw new ArgumentException ("Unmatched ']' while parsing generic argument assembly name"); - data.assembly_name = name.Substring (pos + 1, end - pos - 1).Trim (); - p = end; - return data; - } - if (is_recurse) { - p = pos; - return data; - } - if (allow_aqn) { - data.assembly_name = name.Substring (pos + 1).Trim (); - pos = name.Length; - } - break; - case '[': - if (data.is_byref) - throw new ArgumentException ("Byref qualifier must be the last one of a type", "typeName"); - ++pos; - if (pos >= name.Length) - throw new ArgumentException ("Invalid array/generic spec", "typeName"); - SkipSpace (name, ref pos); - - if (name [pos] != ',' && name [pos] != '*' && name [pos] != ']') {//generic args - List<TypeSpec> args = new List <TypeSpec> (); - if (data.HasModifiers) - throw new ArgumentException ("generic args after array spec or pointer type", "typeName"); - - while (pos < name.Length) { - SkipSpace (name, ref pos); - bool aqn = name [pos] == '['; - if (aqn) - ++pos; //skip '[' to the start of the type - args.Add (Parse (name, ref pos, true, aqn)); - BoundCheck (pos, name); - if (aqn) { - if (name [pos] == ']') - ++pos; - else - throw new ArgumentException ("Unclosed assembly-qualified type name at " + name[pos], "typeName"); - BoundCheck (pos, name); -} - - if (name [pos] == ']') - break; - if (name [pos] == ',') - ++pos; // skip ',' to the start of the next arg - else - throw new ArgumentException ("Invalid generic arguments separator " + name [pos], "typeName"); - - } - if (pos >= name.Length || name [pos] != ']') - throw new ArgumentException ("Error parsing generic params spec", "typeName"); - data.generic_params = args; - } else { //array spec - int dimensions = 1; - bool bound = false; - while (pos < name.Length && name [pos] != ']') { - if (name [pos] == '*') { - if (bound) - throw new ArgumentException ("Array spec cannot have 2 bound dimensions", "typeName"); - bound = true; - } - else if (name [pos] != ',') - throw new ArgumentException ("Invalid character in array spec " + name [pos], "typeName"); - else - ++dimensions; - - ++pos; - SkipSpace (name, ref pos); - } - if (pos >= name.Length || name [pos] != ']') - throw new ArgumentException ("Error parsing array spec", "typeName"); - if (dimensions > 1 && bound) - throw new ArgumentException ("Invalid array spec, multi-dimensional array cannot be bound", "typeName"); - data.AddModifier (new ArraySpec (dimensions, bound)); - } - - break; - case ']': - if (is_recurse) { - p = pos; - return data; - } - throw new ArgumentException ("Unmatched ']'", "typeName"); - default: - throw new ArgumentException ("Bad type def, can't handle '" + name [pos]+"'" + " at " + pos, "typeName"); - } - } - } - - p = pos; - return data; - } - - internal TypeName TypeNameWithoutModifiers () - { - return new TypeSpecTypeName (this, false); - } - - internal TypeName TypeName { - get { return new TypeSpecTypeName (this, true); } - } - - private class TypeSpecTypeName : TypeNames.ATypeName, TypeName { - TypeSpec ts; - bool want_modifiers; - - internal TypeSpecTypeName (TypeSpec ts, bool wantModifiers) - { - this.ts = ts; - this.want_modifiers = wantModifiers; - } - - public override string DisplayName { - get { - if (want_modifiers) - return ts.DisplayFullName; - else - return ts.GetDisplayFullName (DisplayNameFormat.NO_MODIFIERS); - } - } - - public override TypeName NestedName (TypeIdentifier innerName) - { - return TypeNames.FromDisplay(DisplayName + "+" + innerName.DisplayName); - } - } - - } -} - diff --git a/netcore/System.Private.CoreLib/src/System/TypedReference.cs b/netcore/System.Private.CoreLib/src/System/TypedReference.cs deleted file mode 100644 index 74a92a54997..00000000000 --- a/netcore/System.Private.CoreLib/src/System/TypedReference.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace System -{ - [CLSCompliantAttribute (false)] - public ref struct TypedReference - { - #region sync with object-internals.h - RuntimeTypeHandle type; - IntPtr Value; - IntPtr Type; - #endregion - - [CLSCompliant (false)] - public static TypedReference MakeTypedReference (object target, FieldInfo[] flds) - { - if (target == null) - throw new ArgumentNullException (nameof (target)); - if (flds == null) - throw new ArgumentNullException (nameof (flds)); - if (flds.Length == 0) - throw new ArgumentException (SR.Arg_ArrayZeroError, nameof (flds)); - - var fields = new IntPtr [flds.Length]; - var targetType = (RuntimeType)target.GetType (); - for (int i = 0; i < flds.Length; i++) { - var field = flds [i] as RuntimeFieldInfo; - if (field == null) - throw new ArgumentException (SR.Argument_MustBeRuntimeFieldInfo); - if (field.IsStatic) - throw new ArgumentException (SR.Argument_TypedReferenceInvalidField); - - if (targetType != field.GetDeclaringTypeInternal () && !targetType.IsSubclassOf (field.GetDeclaringTypeInternal ())) - throw new MissingMemberException (SR.MissingMemberTypeRef); - - var fieldType = (RuntimeType)field.FieldType; - if (fieldType.IsPrimitive) - throw new ArgumentException (SR.Arg_TypeRefPrimitve); - if (i < (flds.Length - 1) && !fieldType.IsValueType) - throw new MissingMemberException (SR.MissingMemberNestErr); - - fields[i] = field.FieldHandle.Value; - targetType = fieldType; - } - - var result = new TypedReference (); - - unsafe { - InternalMakeTypedReference (&result, target, fields, targetType); - } - return result; - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - unsafe static extern void InternalMakeTypedReference (void* result, Object target, IntPtr[] flds, RuntimeType lastFieldType); - - public override int GetHashCode () - { - if (Type == IntPtr.Zero) - return 0; - else - return __reftype (this).GetHashCode (); - } - - public override bool Equals (object? o) - { - throw new NotSupportedException (SR.NotSupported_NYI); - } - - [CLSCompliant (false)] - public unsafe static object ToObject (TypedReference value) - { - return InternalToObject (&value); - } - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - unsafe extern static object InternalToObject (void * value); - - internal bool IsNull { - get { - return Value == IntPtr.Zero && Type == IntPtr.Zero; - } - } - - [CLSCompliant (false)] - public static Type GetTargetType (TypedReference value) - { - return __reftype (value); - } - - [CLSCompliant (false)] - public static RuntimeTypeHandle TargetTypeToken (TypedReference value) - { - return __reftype (value).TypeHandle; - } - - [CLSCompliant (false)] - public unsafe static void SetTypedReference (TypedReference target, Object value) - { - throw new NotSupportedException (); - } - } -} diff --git a/netcore/System.Private.CoreLib/src/System/ValueType.cs b/netcore/System.Private.CoreLib/src/System/ValueType.cs deleted file mode 100644 index 86c86625a6e..00000000000 --- a/netcore/System.Private.CoreLib/src/System/ValueType.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace System -{ - [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom ("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public abstract class ValueType - { - // This is also used by RuntimeHelpers - internal static bool DefaultEquals (object o1, object o2) - { - RuntimeType o1_type = (RuntimeType) o1.GetType (); - RuntimeType o2_type = (RuntimeType) o2.GetType (); - - if (o1_type != o2_type) - return false; - - object[] fields; - bool res = InternalEquals (o1, o2, out fields); - if (fields == null) - return res; - - for (int i = 0; i < fields.Length; i += 2) { - object meVal = fields [i]; - object youVal = fields [i + 1]; - if (meVal == null) { - if (youVal == null) - continue; - - return false; - } - - if (!meVal.Equals (youVal)) - return false; - } - - return true; - } - - public override bool Equals (object? obj) - { - if (obj == null) - return false; - - return DefaultEquals (this, obj); - } - - public override int GetHashCode () - { - int result = InternalGetHashCode (this, out var fields); - - if (fields != null) - for (int i = 0; i < fields.Length; ++i) - if (fields [i] != null) - result ^= fields [i].GetHashCode (); - - return result; - } - - public override string ToString () - { - return GetType ().ToString (); - } - - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static int InternalGetHashCode (object o, out object[]? fields); - - [MethodImplAttribute (MethodImplOptions.InternalCall)] - extern static bool InternalEquals (object o1, object o2, out object[] fields); - } -} diff --git a/netcore/System.Private.CoreLib/src/System/WeakReference.Mono.cs b/netcore/System.Private.CoreLib/src/System/WeakReference.Mono.cs deleted file mode 100644 index 8f25c35596c..00000000000 --- a/netcore/System.Private.CoreLib/src/System/WeakReference.Mono.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -namespace System -{ - partial class WeakReference - { - bool trackResurrection; - GCHandle handle; - - public virtual bool IsAlive => Target != null; - - public virtual object Target { - get { - if (!handle.IsAllocated) - return null; - return handle.Target; - } - set { - handle.Target = value; - } - } - - public virtual bool TrackResurrection => IsTrackResurrection (); - - ~WeakReference () - { - handle.Free (); - } - - void Create (object target, bool trackResurrection) - { - if (trackResurrection) { - this.trackResurrection = true; - handle = GCHandle.Alloc (target, GCHandleType.WeakTrackResurrection); - } else { - handle = GCHandle.Alloc (target, GCHandleType.Weak); - } - } - - bool IsTrackResurrection () => trackResurrection; - } -} diff --git a/netcore/System.Private.CoreLib/src/System/WeakReference.T.Mono.cs b/netcore/System.Private.CoreLib/src/System/WeakReference.T.Mono.cs deleted file mode 100644 index a108f52769a..00000000000 --- a/netcore/System.Private.CoreLib/src/System/WeakReference.T.Mono.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -namespace System -{ - partial class WeakReference<T> - { - GCHandle handle; - bool trackResurrection; - - T Target { - get { - GCHandle h = handle; - return h.IsAllocated ? (T) h.Target : null; - } - } - - ~WeakReference () - { - handle.Free (); - } - - void Create (T target, bool trackResurrection) - { - if (trackResurrection) { - trackResurrection = true; - handle = GCHandle.Alloc (target, GCHandleType.WeakTrackResurrection); - } else { - handle = GCHandle.Alloc (target, GCHandleType.Weak); - } - } - - public void SetTarget (T target) - { - handle.Target = target; - } - - bool IsTrackResurrection () => trackResurrection; - } -} diff --git a/netcore/System.Private.CoreLib/src/System/__ComObject.cs b/netcore/System.Private.CoreLib/src/System/__ComObject.cs deleted file mode 100644 index 3676d0905ef..00000000000 --- a/netcore/System.Private.CoreLib/src/System/__ComObject.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System -{ - internal class __ComObject - { - __ComObject () - { - throw new NotSupportedException (); - } - } -} |